diff --git a/.github/workflows/plugin-boundaries.yml b/.github/workflows/plugin-boundaries.yml index e2f6b49df..40c815a2c 100644 --- a/.github/workflows/plugin-boundaries.yml +++ b/.github/workflows/plugin-boundaries.yml @@ -46,11 +46,14 @@ jobs: run: pnpm --dir ui test --run - name: Typecheck and build UI run: pnpm --dir ui build + - name: Install plugin packaging dependencies + run: python3 -m pip install --disable-pip-version-check -r scripts/plugin-package-requirements.txt - name: Validate formatting and plugin boundaries run: | cargo fmt --all --check cargo metadata --format-version 1 --locked > /dev/null python3 scripts/check-plugin-boundaries.py + python3 scripts/check-plugin-conformance.py python3 -m unittest discover -s scripts/tests - name: Test all workspace crates (including app and PackageKit) run: cargo test --locked --workspace diff --git a/AGENTS.md b/AGENTS.md index 1a7f12c34..5a7b1f249 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -12,6 +12,13 @@ - These conventions do not authorize committing, pushing, or rewriting history; perform those actions only when requested. +## Specification changes + +- When an instruction appears to change an OpenSpec specification, state the + interpretation and ask before editing specs, unless the user already asked + for the update. Once authorized, keep the proposal, design, delta and main + specs and tasks consistent, and report the files changed. + ## Architecture Guardrails (Tauri v2 + React + TanStack) - **Async Tauri Commands**: All Rust commands exposed to the frontend must be @@ -89,3 +96,7 @@ However, it **does not** replace native OS acceptance for: For those OS-level checks, use `cargo xwin test --workspace --target x86_64-pc-windows-msvc --locked` and `scripts/install-windows-wsl.sh` as documented in [docs/development.md](docs/development.md). + +Cross-compiled checks show that the Windows build compiles; they are not native Windows +acceptance. Keep native Windows acceptance tasks open until a native run is recorded in +[docs/windows-verification.md](docs/windows-verification.md). diff --git a/Cargo.lock b/Cargo.lock index 195c332f7..b2db9cb44 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1535,6 +1535,7 @@ name = "gamenode-app" version = "0.1.0" dependencies = [ "async-trait", + "base64 0.22.1", "futures-util", "gamenode-api", "gamenode-core", @@ -1544,13 +1545,20 @@ dependencies = [ "gamenode-plugin-steam", "getrandom 0.4.3", "httpmock", + "image", "mimalloc", + "ring", "rustix", + "semver", "serde", "serde_json", + "sha2 0.10.9", + "spdx", "tauri", "tauri-build", + "tauri-plugin-dialog", "tempfile", + "thiserror 2.0.21", "tokio", "tokio-stream", "toml 1.2.0+spec-1.1.0", @@ -1562,6 +1570,7 @@ dependencies = [ "webview2-com", "windows-core", "windows-sys 0.61.2", + "zip", ] [[package]] @@ -1573,6 +1582,7 @@ dependencies = [ "serde", "serde_json", "serde_yaml", + "sha2 0.10.9", "thiserror 2.0.21", "toml 1.2.0+spec-1.1.0", "tracing", @@ -1584,6 +1594,7 @@ dependencies = [ name = "gamenode-platform" version = "0.1.0" dependencies = [ + "base64 0.22.1", "dirs", "gamenode-core", "getrandom 0.4.3", @@ -1593,8 +1604,10 @@ dependencies = [ "notify", "open", "reqwest", + "ring", "rusqlite", "rustix", + "semver", "serde", "serde_json", "serde_yaml", @@ -1645,6 +1658,8 @@ dependencies = [ "serde", "tempfile", "tokio", + "tokio-stream", + "tonic", "tracing", "tracing-subscriber", "zbus", @@ -1656,9 +1671,11 @@ version = "0.1.0" dependencies = [ "prost", "prost-build", + "prost-types", "protoc-bin-vendored", "serde", "serde_json", + "sha2 0.10.9", "thiserror 2.0.21", "tonic", "tonic-prost", @@ -1673,6 +1690,7 @@ dependencies = [ "async-trait", "gamenode-plugin-protocol", "hyper-util", + "serde_json", "tempfile", "thiserror 2.0.21", "tokio", @@ -3372,6 +3390,7 @@ checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272" dependencies = [ "bitflags 2.13.2", "block2", + "libc", "objc2", "objc2-core-foundation", ] @@ -4193,6 +4212,32 @@ dependencies = [ "web-sys", ] +[[package]] +name = "rfd" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20dafead71c16a34e1ff357ddefc8afc11e7d51d6d2b9fbd07eaa48e3e540220" +dependencies = [ + "block2", + "dispatch2", + "glib-sys", + "gobject-sys", + "gtk-sys", + "js-sys", + "libc", + "log", + "objc2", + "objc2-app-kit", + "objc2-core-foundation", + "objc2-foundation", + "percent-encoding", + "raw-window-handle", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "windows-sys 0.61.2", +] + [[package]] name = "ring" version = "0.17.14" @@ -4859,6 +4904,15 @@ dependencies = [ "system-deps", ] +[[package]] +name = "spdx" +version = "0.13.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "646c5a367da914e3babcb9cd8e91c37ccaac42325b8f86f036513ad103f2a716" +dependencies = [ + "smallvec", +] + [[package]] name = "sqlite-wasm-rs" version = "0.6.2" @@ -5192,6 +5246,64 @@ dependencies = [ "tauri-utils", ] +[[package]] +name = "tauri-plugin" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67fb21a77e8f94e8beb3325e583102488659365af0a3948b7ea244c5b779c291" +dependencies = [ + "anyhow", + "glob", + "plist", + "schemars 0.8.22", + "serde", + "serde_json", + "tauri-utils", + "walkdir", +] + +[[package]] +name = "tauri-plugin-dialog" +version = "2.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce0fb9c2b6d34a9720627ed930ebc8af26f61e648695aecaeb03d5c33c5896f5" +dependencies = [ + "log", + "raw-window-handle", + "rfd", + "serde", + "serde_json", + "tauri", + "tauri-plugin", + "tauri-plugin-fs", + "thiserror 2.0.21", + "url", +] + +[[package]] +name = "tauri-plugin-fs" +version = "2.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d58eb1d4984e535f47a642ffec09a2da6f5c18a12b5902d12126cb7626d628b" +dependencies = [ + "anyhow", + "dunce", + "glob", + "log", + "objc2-foundation", + "percent-encoding", + "schemars 0.8.22", + "serde", + "serde_json", + "serde_repr", + "tauri", + "tauri-plugin", + "tauri-utils", + "thiserror 2.0.21", + "toml 1.2.0+spec-1.1.0", + "url", +] + [[package]] name = "tauri-runtime" version = "2.12.2" diff --git a/crates/app/Cargo.toml b/crates/app/Cargo.toml index 5fc87559c..bfb1df854 100644 --- a/crates/app/Cargo.toml +++ b/crates/app/Cargo.toml @@ -35,6 +35,7 @@ gamenode-platform.workspace = true gamenode-api.workspace = true gamenode-plugin-protocol.workspace = true async-trait.workspace = true +base64 = "0.22.1" mimalloc = { version = "0.1.52", optional = true } futures-util = "0.3" getrandom.workspace = true @@ -42,19 +43,25 @@ serde = { workspace = true } serde_json.workspace = true toml.workspace = true tauri = { version = "2", features = ["tray-icon"] } +tauri-plugin-dialog = "2" tokio = { workspace = true, features = ["rt-multi-thread", "macros", "time", "sync", "process", "net", "io-util"] } tracing.workspace = true tracing-appender = "0.2.3" tracing-subscriber = { version = "0.3.23", default-features = false, features = ["fmt", "env-filter", "ansi"] } url.workspace = true +semver = "1.0.27" +spdx = "0.13.6" +sha2 = "0.10.9" +thiserror.workspace = true tonic = { version = "0.14", features = ["transport"] } tokio-stream = { version = "0.1", features = ["net"] } +zip = { version = "2.4", default-features = false, features = ["deflate"] } [target.'cfg(target_os = "linux")'.dependencies] rustix = { workspace = true, features = ["fs", "process"] } [target.'cfg(target_os = "windows")'.dependencies] -windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_System_Threading", "Win32_Globalization", "Win32_UI_WindowsAndMessaging"] } +windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_Security", "Win32_System_Threading", "Win32_System_JobObjects", "Win32_Globalization", "Win32_UI_WindowsAndMessaging", "Win32_Storage_FileSystem"] } webview2-com = "0.39" windows-core = "0.62" @@ -65,5 +72,7 @@ tauri-build = { version = "2", features = [] } gamenode-plugin-sdk = { path = "../plugin-sdk" } gamenode-plugin-steam = { path = "../plugin-steam" } httpmock = "0.9.0" +ring = "0.17.14" tempfile.workspace = true tokio = { workspace = true, features = ["test-util"] } +image = { version = "0.25", default-features = false, features = ["png", "jpeg", "webp"] } diff --git a/crates/app/capabilities/default.json b/crates/app/capabilities/default.json index a5db11d22..1218afe52 100644 --- a/crates/app/capabilities/default.json +++ b/crates/app/capabilities/default.json @@ -13,6 +13,7 @@ "core:window:allow-toggle-maximize", "core:window:allow-close", "core:window:allow-start-dragging", - "core:window:allow-is-maximized" + "core:window:allow-is-maximized", + "dialog:allow-open" ] } diff --git a/crates/app/gen/schemas/acl-manifests.json b/crates/app/gen/schemas/acl-manifests.json index 2ebbc8dec..b8e19ecc0 100644 --- a/crates/app/gen/schemas/acl-manifests.json +++ b/crates/app/gen/schemas/acl-manifests.json @@ -1 +1 @@ -{"core":{"default_permission":{"identifier":"default","description":"Default core plugins set.","permissions":["core:path:default","core:event:default","core:window:default","core:webview:default","core:app:default","core:image:default","core:resources:default","core:menu:default","core:tray:default"]},"permissions":{},"permission_sets":{},"global_scope_schema":null},"core:app":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin.","permissions":["allow-version","allow-name","allow-tauri-version","allow-identifier","allow-bundle-type","allow-register-listener","allow-remove-listener","allow-supports-multiple-windows"]},"permissions":{"allow-app-hide":{"identifier":"allow-app-hide","description":"Enables the app_hide command without any pre-configured scope.","commands":{"allow":["app_hide"],"deny":[]}},"allow-app-show":{"identifier":"allow-app-show","description":"Enables the app_show command without any pre-configured scope.","commands":{"allow":["app_show"],"deny":[]}},"allow-bundle-type":{"identifier":"allow-bundle-type","description":"Enables the bundle_type command without any pre-configured scope.","commands":{"allow":["bundle_type"],"deny":[]}},"allow-default-window-icon":{"identifier":"allow-default-window-icon","description":"Enables the default_window_icon command without any pre-configured scope.","commands":{"allow":["default_window_icon"],"deny":[]}},"allow-exit":{"identifier":"allow-exit","description":"Enables the exit command without any pre-configured scope.","commands":{"allow":["exit"],"deny":[]}},"allow-fetch-data-store-identifiers":{"identifier":"allow-fetch-data-store-identifiers","description":"Enables the fetch_data_store_identifiers command without any pre-configured scope.","commands":{"allow":["fetch_data_store_identifiers"],"deny":[]}},"allow-identifier":{"identifier":"allow-identifier","description":"Enables the identifier command without any pre-configured scope.","commands":{"allow":["identifier"],"deny":[]}},"allow-name":{"identifier":"allow-name","description":"Enables the name command without any pre-configured scope.","commands":{"allow":["name"],"deny":[]}},"allow-register-listener":{"identifier":"allow-register-listener","description":"Enables the register_listener command without any pre-configured scope.","commands":{"allow":["register_listener"],"deny":[]}},"allow-remove-data-store":{"identifier":"allow-remove-data-store","description":"Enables the remove_data_store command without any pre-configured scope.","commands":{"allow":["remove_data_store"],"deny":[]}},"allow-remove-listener":{"identifier":"allow-remove-listener","description":"Enables the remove_listener command without any pre-configured scope.","commands":{"allow":["remove_listener"],"deny":[]}},"allow-set-app-theme":{"identifier":"allow-set-app-theme","description":"Enables the set_app_theme command without any pre-configured scope.","commands":{"allow":["set_app_theme"],"deny":[]}},"allow-set-dock-visibility":{"identifier":"allow-set-dock-visibility","description":"Enables the set_dock_visibility command without any pre-configured scope.","commands":{"allow":["set_dock_visibility"],"deny":[]}},"allow-supports-multiple-windows":{"identifier":"allow-supports-multiple-windows","description":"Enables the supports_multiple_windows command without any pre-configured scope.","commands":{"allow":["supports_multiple_windows"],"deny":[]}},"allow-tauri-version":{"identifier":"allow-tauri-version","description":"Enables the tauri_version command without any pre-configured scope.","commands":{"allow":["tauri_version"],"deny":[]}},"allow-version":{"identifier":"allow-version","description":"Enables the version command without any pre-configured scope.","commands":{"allow":["version"],"deny":[]}},"deny-app-hide":{"identifier":"deny-app-hide","description":"Denies the app_hide command without any pre-configured scope.","commands":{"allow":[],"deny":["app_hide"]}},"deny-app-show":{"identifier":"deny-app-show","description":"Denies the app_show command without any pre-configured scope.","commands":{"allow":[],"deny":["app_show"]}},"deny-bundle-type":{"identifier":"deny-bundle-type","description":"Denies the bundle_type command without any pre-configured scope.","commands":{"allow":[],"deny":["bundle_type"]}},"deny-default-window-icon":{"identifier":"deny-default-window-icon","description":"Denies the default_window_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["default_window_icon"]}},"deny-exit":{"identifier":"deny-exit","description":"Denies the exit command without any pre-configured scope.","commands":{"allow":[],"deny":["exit"]}},"deny-fetch-data-store-identifiers":{"identifier":"deny-fetch-data-store-identifiers","description":"Denies the fetch_data_store_identifiers command without any pre-configured scope.","commands":{"allow":[],"deny":["fetch_data_store_identifiers"]}},"deny-identifier":{"identifier":"deny-identifier","description":"Denies the identifier command without any pre-configured scope.","commands":{"allow":[],"deny":["identifier"]}},"deny-name":{"identifier":"deny-name","description":"Denies the name command without any pre-configured scope.","commands":{"allow":[],"deny":["name"]}},"deny-register-listener":{"identifier":"deny-register-listener","description":"Denies the register_listener command without any pre-configured scope.","commands":{"allow":[],"deny":["register_listener"]}},"deny-remove-data-store":{"identifier":"deny-remove-data-store","description":"Denies the remove_data_store command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_data_store"]}},"deny-remove-listener":{"identifier":"deny-remove-listener","description":"Denies the remove_listener command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_listener"]}},"deny-set-app-theme":{"identifier":"deny-set-app-theme","description":"Denies the set_app_theme command without any pre-configured scope.","commands":{"allow":[],"deny":["set_app_theme"]}},"deny-set-dock-visibility":{"identifier":"deny-set-dock-visibility","description":"Denies the set_dock_visibility command without any pre-configured scope.","commands":{"allow":[],"deny":["set_dock_visibility"]}},"deny-supports-multiple-windows":{"identifier":"deny-supports-multiple-windows","description":"Denies the supports_multiple_windows command without any pre-configured scope.","commands":{"allow":[],"deny":["supports_multiple_windows"]}},"deny-tauri-version":{"identifier":"deny-tauri-version","description":"Denies the tauri_version command without any pre-configured scope.","commands":{"allow":[],"deny":["tauri_version"]}},"deny-version":{"identifier":"deny-version","description":"Denies the version command without any pre-configured scope.","commands":{"allow":[],"deny":["version"]}}},"permission_sets":{},"global_scope_schema":null},"core:event":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-listen","allow-unlisten","allow-emit","allow-emit-to"]},"permissions":{"allow-emit":{"identifier":"allow-emit","description":"Enables the emit command without any pre-configured scope.","commands":{"allow":["emit"],"deny":[]}},"allow-emit-to":{"identifier":"allow-emit-to","description":"Enables the emit_to command without any pre-configured scope.","commands":{"allow":["emit_to"],"deny":[]}},"allow-listen":{"identifier":"allow-listen","description":"Enables the listen command without any pre-configured scope.","commands":{"allow":["listen"],"deny":[]}},"allow-unlisten":{"identifier":"allow-unlisten","description":"Enables the unlisten command without any pre-configured scope.","commands":{"allow":["unlisten"],"deny":[]}},"deny-emit":{"identifier":"deny-emit","description":"Denies the emit command without any pre-configured scope.","commands":{"allow":[],"deny":["emit"]}},"deny-emit-to":{"identifier":"deny-emit-to","description":"Denies the emit_to command without any pre-configured scope.","commands":{"allow":[],"deny":["emit_to"]}},"deny-listen":{"identifier":"deny-listen","description":"Denies the listen command without any pre-configured scope.","commands":{"allow":[],"deny":["listen"]}},"deny-unlisten":{"identifier":"deny-unlisten","description":"Denies the unlisten command without any pre-configured scope.","commands":{"allow":[],"deny":["unlisten"]}}},"permission_sets":{},"global_scope_schema":null},"core:image":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-new","allow-from-bytes","allow-from-path","allow-rgba","allow-size"]},"permissions":{"allow-from-bytes":{"identifier":"allow-from-bytes","description":"Enables the from_bytes command without any pre-configured scope.","commands":{"allow":["from_bytes"],"deny":[]}},"allow-from-path":{"identifier":"allow-from-path","description":"Enables the from_path command without any pre-configured scope.","commands":{"allow":["from_path"],"deny":[]}},"allow-new":{"identifier":"allow-new","description":"Enables the new command without any pre-configured scope.","commands":{"allow":["new"],"deny":[]}},"allow-rgba":{"identifier":"allow-rgba","description":"Enables the rgba command without any pre-configured scope.","commands":{"allow":["rgba"],"deny":[]}},"allow-size":{"identifier":"allow-size","description":"Enables the size command without any pre-configured scope.","commands":{"allow":["size"],"deny":[]}},"deny-from-bytes":{"identifier":"deny-from-bytes","description":"Denies the from_bytes command without any pre-configured scope.","commands":{"allow":[],"deny":["from_bytes"]}},"deny-from-path":{"identifier":"deny-from-path","description":"Denies the from_path command without any pre-configured scope.","commands":{"allow":[],"deny":["from_path"]}},"deny-new":{"identifier":"deny-new","description":"Denies the new command without any pre-configured scope.","commands":{"allow":[],"deny":["new"]}},"deny-rgba":{"identifier":"deny-rgba","description":"Denies the rgba command without any pre-configured scope.","commands":{"allow":[],"deny":["rgba"]}},"deny-size":{"identifier":"deny-size","description":"Denies the size command without any pre-configured scope.","commands":{"allow":[],"deny":["size"]}}},"permission_sets":{},"global_scope_schema":null},"core:menu":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-new","allow-append","allow-prepend","allow-insert","allow-remove","allow-remove-at","allow-items","allow-get","allow-popup","allow-create-default","allow-set-as-app-menu","allow-set-as-window-menu","allow-text","allow-set-text","allow-is-enabled","allow-set-enabled","allow-set-accelerator","allow-set-as-windows-menu-for-nsapp","allow-set-as-help-menu-for-nsapp","allow-is-checked","allow-set-checked","allow-set-icon"]},"permissions":{"allow-append":{"identifier":"allow-append","description":"Enables the append command without any pre-configured scope.","commands":{"allow":["append"],"deny":[]}},"allow-create-default":{"identifier":"allow-create-default","description":"Enables the create_default command without any pre-configured scope.","commands":{"allow":["create_default"],"deny":[]}},"allow-get":{"identifier":"allow-get","description":"Enables the get command without any pre-configured scope.","commands":{"allow":["get"],"deny":[]}},"allow-insert":{"identifier":"allow-insert","description":"Enables the insert command without any pre-configured scope.","commands":{"allow":["insert"],"deny":[]}},"allow-is-checked":{"identifier":"allow-is-checked","description":"Enables the is_checked command without any pre-configured scope.","commands":{"allow":["is_checked"],"deny":[]}},"allow-is-enabled":{"identifier":"allow-is-enabled","description":"Enables the is_enabled command without any pre-configured scope.","commands":{"allow":["is_enabled"],"deny":[]}},"allow-items":{"identifier":"allow-items","description":"Enables the items command without any pre-configured scope.","commands":{"allow":["items"],"deny":[]}},"allow-new":{"identifier":"allow-new","description":"Enables the new command without any pre-configured scope.","commands":{"allow":["new"],"deny":[]}},"allow-popup":{"identifier":"allow-popup","description":"Enables the popup command without any pre-configured scope.","commands":{"allow":["popup"],"deny":[]}},"allow-prepend":{"identifier":"allow-prepend","description":"Enables the prepend command without any pre-configured scope.","commands":{"allow":["prepend"],"deny":[]}},"allow-remove":{"identifier":"allow-remove","description":"Enables the remove command without any pre-configured scope.","commands":{"allow":["remove"],"deny":[]}},"allow-remove-at":{"identifier":"allow-remove-at","description":"Enables the remove_at command without any pre-configured scope.","commands":{"allow":["remove_at"],"deny":[]}},"allow-set-accelerator":{"identifier":"allow-set-accelerator","description":"Enables the set_accelerator command without any pre-configured scope.","commands":{"allow":["set_accelerator"],"deny":[]}},"allow-set-as-app-menu":{"identifier":"allow-set-as-app-menu","description":"Enables the set_as_app_menu command without any pre-configured scope.","commands":{"allow":["set_as_app_menu"],"deny":[]}},"allow-set-as-help-menu-for-nsapp":{"identifier":"allow-set-as-help-menu-for-nsapp","description":"Enables the set_as_help_menu_for_nsapp command without any pre-configured scope.","commands":{"allow":["set_as_help_menu_for_nsapp"],"deny":[]}},"allow-set-as-window-menu":{"identifier":"allow-set-as-window-menu","description":"Enables the set_as_window_menu command without any pre-configured scope.","commands":{"allow":["set_as_window_menu"],"deny":[]}},"allow-set-as-windows-menu-for-nsapp":{"identifier":"allow-set-as-windows-menu-for-nsapp","description":"Enables the set_as_windows_menu_for_nsapp command without any pre-configured scope.","commands":{"allow":["set_as_windows_menu_for_nsapp"],"deny":[]}},"allow-set-checked":{"identifier":"allow-set-checked","description":"Enables the set_checked command without any pre-configured scope.","commands":{"allow":["set_checked"],"deny":[]}},"allow-set-enabled":{"identifier":"allow-set-enabled","description":"Enables the set_enabled command without any pre-configured scope.","commands":{"allow":["set_enabled"],"deny":[]}},"allow-set-icon":{"identifier":"allow-set-icon","description":"Enables the set_icon command without any pre-configured scope.","commands":{"allow":["set_icon"],"deny":[]}},"allow-set-text":{"identifier":"allow-set-text","description":"Enables the set_text command without any pre-configured scope.","commands":{"allow":["set_text"],"deny":[]}},"allow-text":{"identifier":"allow-text","description":"Enables the text command without any pre-configured scope.","commands":{"allow":["text"],"deny":[]}},"deny-append":{"identifier":"deny-append","description":"Denies the append command without any pre-configured scope.","commands":{"allow":[],"deny":["append"]}},"deny-create-default":{"identifier":"deny-create-default","description":"Denies the create_default command without any pre-configured scope.","commands":{"allow":[],"deny":["create_default"]}},"deny-get":{"identifier":"deny-get","description":"Denies the get command without any pre-configured scope.","commands":{"allow":[],"deny":["get"]}},"deny-insert":{"identifier":"deny-insert","description":"Denies the insert command without any pre-configured scope.","commands":{"allow":[],"deny":["insert"]}},"deny-is-checked":{"identifier":"deny-is-checked","description":"Denies the is_checked command without any pre-configured scope.","commands":{"allow":[],"deny":["is_checked"]}},"deny-is-enabled":{"identifier":"deny-is-enabled","description":"Denies the is_enabled command without any pre-configured scope.","commands":{"allow":[],"deny":["is_enabled"]}},"deny-items":{"identifier":"deny-items","description":"Denies the items command without any pre-configured scope.","commands":{"allow":[],"deny":["items"]}},"deny-new":{"identifier":"deny-new","description":"Denies the new command without any pre-configured scope.","commands":{"allow":[],"deny":["new"]}},"deny-popup":{"identifier":"deny-popup","description":"Denies the popup command without any pre-configured scope.","commands":{"allow":[],"deny":["popup"]}},"deny-prepend":{"identifier":"deny-prepend","description":"Denies the prepend command without any pre-configured scope.","commands":{"allow":[],"deny":["prepend"]}},"deny-remove":{"identifier":"deny-remove","description":"Denies the remove command without any pre-configured scope.","commands":{"allow":[],"deny":["remove"]}},"deny-remove-at":{"identifier":"deny-remove-at","description":"Denies the remove_at command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_at"]}},"deny-set-accelerator":{"identifier":"deny-set-accelerator","description":"Denies the set_accelerator command without any pre-configured scope.","commands":{"allow":[],"deny":["set_accelerator"]}},"deny-set-as-app-menu":{"identifier":"deny-set-as-app-menu","description":"Denies the set_as_app_menu command without any pre-configured scope.","commands":{"allow":[],"deny":["set_as_app_menu"]}},"deny-set-as-help-menu-for-nsapp":{"identifier":"deny-set-as-help-menu-for-nsapp","description":"Denies the set_as_help_menu_for_nsapp command without any pre-configured scope.","commands":{"allow":[],"deny":["set_as_help_menu_for_nsapp"]}},"deny-set-as-window-menu":{"identifier":"deny-set-as-window-menu","description":"Denies the set_as_window_menu command without any pre-configured scope.","commands":{"allow":[],"deny":["set_as_window_menu"]}},"deny-set-as-windows-menu-for-nsapp":{"identifier":"deny-set-as-windows-menu-for-nsapp","description":"Denies the set_as_windows_menu_for_nsapp command without any pre-configured scope.","commands":{"allow":[],"deny":["set_as_windows_menu_for_nsapp"]}},"deny-set-checked":{"identifier":"deny-set-checked","description":"Denies the set_checked command without any pre-configured scope.","commands":{"allow":[],"deny":["set_checked"]}},"deny-set-enabled":{"identifier":"deny-set-enabled","description":"Denies the set_enabled command without any pre-configured scope.","commands":{"allow":[],"deny":["set_enabled"]}},"deny-set-icon":{"identifier":"deny-set-icon","description":"Denies the set_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["set_icon"]}},"deny-set-text":{"identifier":"deny-set-text","description":"Denies the set_text command without any pre-configured scope.","commands":{"allow":[],"deny":["set_text"]}},"deny-text":{"identifier":"deny-text","description":"Denies the text command without any pre-configured scope.","commands":{"allow":[],"deny":["text"]}}},"permission_sets":{},"global_scope_schema":null},"core:path":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-resolve-directory","allow-resolve","allow-normalize","allow-join","allow-dirname","allow-extname","allow-basename","allow-is-absolute"]},"permissions":{"allow-basename":{"identifier":"allow-basename","description":"Enables the basename command without any pre-configured scope.","commands":{"allow":["basename"],"deny":[]}},"allow-dirname":{"identifier":"allow-dirname","description":"Enables the dirname command without any pre-configured scope.","commands":{"allow":["dirname"],"deny":[]}},"allow-extname":{"identifier":"allow-extname","description":"Enables the extname command without any pre-configured scope.","commands":{"allow":["extname"],"deny":[]}},"allow-is-absolute":{"identifier":"allow-is-absolute","description":"Enables the is_absolute command without any pre-configured scope.","commands":{"allow":["is_absolute"],"deny":[]}},"allow-join":{"identifier":"allow-join","description":"Enables the join command without any pre-configured scope.","commands":{"allow":["join"],"deny":[]}},"allow-normalize":{"identifier":"allow-normalize","description":"Enables the normalize command without any pre-configured scope.","commands":{"allow":["normalize"],"deny":[]}},"allow-resolve":{"identifier":"allow-resolve","description":"Enables the resolve command without any pre-configured scope.","commands":{"allow":["resolve"],"deny":[]}},"allow-resolve-directory":{"identifier":"allow-resolve-directory","description":"Enables the resolve_directory command without any pre-configured scope.","commands":{"allow":["resolve_directory"],"deny":[]}},"deny-basename":{"identifier":"deny-basename","description":"Denies the basename command without any pre-configured scope.","commands":{"allow":[],"deny":["basename"]}},"deny-dirname":{"identifier":"deny-dirname","description":"Denies the dirname command without any pre-configured scope.","commands":{"allow":[],"deny":["dirname"]}},"deny-extname":{"identifier":"deny-extname","description":"Denies the extname command without any pre-configured scope.","commands":{"allow":[],"deny":["extname"]}},"deny-is-absolute":{"identifier":"deny-is-absolute","description":"Denies the is_absolute command without any pre-configured scope.","commands":{"allow":[],"deny":["is_absolute"]}},"deny-join":{"identifier":"deny-join","description":"Denies the join command without any pre-configured scope.","commands":{"allow":[],"deny":["join"]}},"deny-normalize":{"identifier":"deny-normalize","description":"Denies the normalize command without any pre-configured scope.","commands":{"allow":[],"deny":["normalize"]}},"deny-resolve":{"identifier":"deny-resolve","description":"Denies the resolve command without any pre-configured scope.","commands":{"allow":[],"deny":["resolve"]}},"deny-resolve-directory":{"identifier":"deny-resolve-directory","description":"Denies the resolve_directory command without any pre-configured scope.","commands":{"allow":[],"deny":["resolve_directory"]}}},"permission_sets":{},"global_scope_schema":null},"core:resources":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-close"]},"permissions":{"allow-close":{"identifier":"allow-close","description":"Enables the close command without any pre-configured scope.","commands":{"allow":["close"],"deny":[]}},"deny-close":{"identifier":"deny-close","description":"Denies the close command without any pre-configured scope.","commands":{"allow":[],"deny":["close"]}}},"permission_sets":{},"global_scope_schema":null},"core:tray":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-new","allow-get-by-id","allow-remove-by-id","allow-set-icon","allow-set-menu","allow-set-tooltip","allow-set-title","allow-set-visible","allow-set-temp-dir-path","allow-set-icon-as-template","allow-set-icon-with-as-template","allow-set-show-menu-on-left-click"]},"permissions":{"allow-get-by-id":{"identifier":"allow-get-by-id","description":"Enables the get_by_id command without any pre-configured scope.","commands":{"allow":["get_by_id"],"deny":[]}},"allow-new":{"identifier":"allow-new","description":"Enables the new command without any pre-configured scope.","commands":{"allow":["new"],"deny":[]}},"allow-remove-by-id":{"identifier":"allow-remove-by-id","description":"Enables the remove_by_id command without any pre-configured scope.","commands":{"allow":["remove_by_id"],"deny":[]}},"allow-set-icon":{"identifier":"allow-set-icon","description":"Enables the set_icon command without any pre-configured scope.","commands":{"allow":["set_icon"],"deny":[]}},"allow-set-icon-as-template":{"identifier":"allow-set-icon-as-template","description":"Enables the set_icon_as_template command without any pre-configured scope.","commands":{"allow":["set_icon_as_template"],"deny":[]}},"allow-set-icon-with-as-template":{"identifier":"allow-set-icon-with-as-template","description":"Enables the set_icon_with_as_template command without any pre-configured scope.","commands":{"allow":["set_icon_with_as_template"],"deny":[]}},"allow-set-menu":{"identifier":"allow-set-menu","description":"Enables the set_menu command without any pre-configured scope.","commands":{"allow":["set_menu"],"deny":[]}},"allow-set-show-menu-on-left-click":{"identifier":"allow-set-show-menu-on-left-click","description":"Enables the set_show_menu_on_left_click command without any pre-configured scope.","commands":{"allow":["set_show_menu_on_left_click"],"deny":[]}},"allow-set-temp-dir-path":{"identifier":"allow-set-temp-dir-path","description":"Enables the set_temp_dir_path command without any pre-configured scope.","commands":{"allow":["set_temp_dir_path"],"deny":[]}},"allow-set-title":{"identifier":"allow-set-title","description":"Enables the set_title command without any pre-configured scope.","commands":{"allow":["set_title"],"deny":[]}},"allow-set-tooltip":{"identifier":"allow-set-tooltip","description":"Enables the set_tooltip command without any pre-configured scope.","commands":{"allow":["set_tooltip"],"deny":[]}},"allow-set-visible":{"identifier":"allow-set-visible","description":"Enables the set_visible command without any pre-configured scope.","commands":{"allow":["set_visible"],"deny":[]}},"deny-get-by-id":{"identifier":"deny-get-by-id","description":"Denies the get_by_id command without any pre-configured scope.","commands":{"allow":[],"deny":["get_by_id"]}},"deny-new":{"identifier":"deny-new","description":"Denies the new command without any pre-configured scope.","commands":{"allow":[],"deny":["new"]}},"deny-remove-by-id":{"identifier":"deny-remove-by-id","description":"Denies the remove_by_id command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_by_id"]}},"deny-set-icon":{"identifier":"deny-set-icon","description":"Denies the set_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["set_icon"]}},"deny-set-icon-as-template":{"identifier":"deny-set-icon-as-template","description":"Denies the set_icon_as_template command without any pre-configured scope.","commands":{"allow":[],"deny":["set_icon_as_template"]}},"deny-set-icon-with-as-template":{"identifier":"deny-set-icon-with-as-template","description":"Denies the set_icon_with_as_template command without any pre-configured scope.","commands":{"allow":[],"deny":["set_icon_with_as_template"]}},"deny-set-menu":{"identifier":"deny-set-menu","description":"Denies the set_menu command without any pre-configured scope.","commands":{"allow":[],"deny":["set_menu"]}},"deny-set-show-menu-on-left-click":{"identifier":"deny-set-show-menu-on-left-click","description":"Denies the set_show_menu_on_left_click command without any pre-configured scope.","commands":{"allow":[],"deny":["set_show_menu_on_left_click"]}},"deny-set-temp-dir-path":{"identifier":"deny-set-temp-dir-path","description":"Denies the set_temp_dir_path command without any pre-configured scope.","commands":{"allow":[],"deny":["set_temp_dir_path"]}},"deny-set-title":{"identifier":"deny-set-title","description":"Denies the set_title command without any pre-configured scope.","commands":{"allow":[],"deny":["set_title"]}},"deny-set-tooltip":{"identifier":"deny-set-tooltip","description":"Denies the set_tooltip command without any pre-configured scope.","commands":{"allow":[],"deny":["set_tooltip"]}},"deny-set-visible":{"identifier":"deny-set-visible","description":"Denies the set_visible command without any pre-configured scope.","commands":{"allow":[],"deny":["set_visible"]}}},"permission_sets":{},"global_scope_schema":null},"core:webview":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin.","permissions":["allow-get-all-webviews","allow-webview-position","allow-webview-size","allow-internal-toggle-devtools"]},"permissions":{"allow-clear-all-browsing-data":{"identifier":"allow-clear-all-browsing-data","description":"Enables the clear_all_browsing_data command without any pre-configured scope.","commands":{"allow":["clear_all_browsing_data"],"deny":[]}},"allow-create-webview":{"identifier":"allow-create-webview","description":"Enables the create_webview command without any pre-configured scope.","commands":{"allow":["create_webview"],"deny":[]}},"allow-create-webview-window":{"identifier":"allow-create-webview-window","description":"Enables the create_webview_window command without any pre-configured scope.","commands":{"allow":["create_webview_window"],"deny":[]}},"allow-get-all-webviews":{"identifier":"allow-get-all-webviews","description":"Enables the get_all_webviews command without any pre-configured scope.","commands":{"allow":["get_all_webviews"],"deny":[]}},"allow-internal-toggle-devtools":{"identifier":"allow-internal-toggle-devtools","description":"Enables the internal_toggle_devtools command without any pre-configured scope.","commands":{"allow":["internal_toggle_devtools"],"deny":[]}},"allow-print":{"identifier":"allow-print","description":"Enables the print command without any pre-configured scope.","commands":{"allow":["print"],"deny":[]}},"allow-reparent":{"identifier":"allow-reparent","description":"Enables the reparent command without any pre-configured scope.","commands":{"allow":["reparent"],"deny":[]}},"allow-set-webview-auto-resize":{"identifier":"allow-set-webview-auto-resize","description":"Enables the set_webview_auto_resize command without any pre-configured scope.","commands":{"allow":["set_webview_auto_resize"],"deny":[]}},"allow-set-webview-background-color":{"identifier":"allow-set-webview-background-color","description":"Enables the set_webview_background_color command without any pre-configured scope.","commands":{"allow":["set_webview_background_color"],"deny":[]}},"allow-set-webview-focus":{"identifier":"allow-set-webview-focus","description":"Enables the set_webview_focus command without any pre-configured scope.","commands":{"allow":["set_webview_focus"],"deny":[]}},"allow-set-webview-position":{"identifier":"allow-set-webview-position","description":"Enables the set_webview_position command without any pre-configured scope.","commands":{"allow":["set_webview_position"],"deny":[]}},"allow-set-webview-size":{"identifier":"allow-set-webview-size","description":"Enables the set_webview_size command without any pre-configured scope.","commands":{"allow":["set_webview_size"],"deny":[]}},"allow-set-webview-zoom":{"identifier":"allow-set-webview-zoom","description":"Enables the set_webview_zoom command without any pre-configured scope.","commands":{"allow":["set_webview_zoom"],"deny":[]}},"allow-webview-close":{"identifier":"allow-webview-close","description":"Enables the webview_close command without any pre-configured scope.","commands":{"allow":["webview_close"],"deny":[]}},"allow-webview-hide":{"identifier":"allow-webview-hide","description":"Enables the webview_hide command without any pre-configured scope.","commands":{"allow":["webview_hide"],"deny":[]}},"allow-webview-position":{"identifier":"allow-webview-position","description":"Enables the webview_position command without any pre-configured scope.","commands":{"allow":["webview_position"],"deny":[]}},"allow-webview-show":{"identifier":"allow-webview-show","description":"Enables the webview_show command without any pre-configured scope.","commands":{"allow":["webview_show"],"deny":[]}},"allow-webview-size":{"identifier":"allow-webview-size","description":"Enables the webview_size command without any pre-configured scope.","commands":{"allow":["webview_size"],"deny":[]}},"deny-clear-all-browsing-data":{"identifier":"deny-clear-all-browsing-data","description":"Denies the clear_all_browsing_data command without any pre-configured scope.","commands":{"allow":[],"deny":["clear_all_browsing_data"]}},"deny-create-webview":{"identifier":"deny-create-webview","description":"Denies the create_webview command without any pre-configured scope.","commands":{"allow":[],"deny":["create_webview"]}},"deny-create-webview-window":{"identifier":"deny-create-webview-window","description":"Denies the create_webview_window command without any pre-configured scope.","commands":{"allow":[],"deny":["create_webview_window"]}},"deny-get-all-webviews":{"identifier":"deny-get-all-webviews","description":"Denies the get_all_webviews command without any pre-configured scope.","commands":{"allow":[],"deny":["get_all_webviews"]}},"deny-internal-toggle-devtools":{"identifier":"deny-internal-toggle-devtools","description":"Denies the internal_toggle_devtools command without any pre-configured scope.","commands":{"allow":[],"deny":["internal_toggle_devtools"]}},"deny-print":{"identifier":"deny-print","description":"Denies the print command without any pre-configured scope.","commands":{"allow":[],"deny":["print"]}},"deny-reparent":{"identifier":"deny-reparent","description":"Denies the reparent command without any pre-configured scope.","commands":{"allow":[],"deny":["reparent"]}},"deny-set-webview-auto-resize":{"identifier":"deny-set-webview-auto-resize","description":"Denies the set_webview_auto_resize command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_auto_resize"]}},"deny-set-webview-background-color":{"identifier":"deny-set-webview-background-color","description":"Denies the set_webview_background_color command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_background_color"]}},"deny-set-webview-focus":{"identifier":"deny-set-webview-focus","description":"Denies the set_webview_focus command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_focus"]}},"deny-set-webview-position":{"identifier":"deny-set-webview-position","description":"Denies the set_webview_position command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_position"]}},"deny-set-webview-size":{"identifier":"deny-set-webview-size","description":"Denies the set_webview_size command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_size"]}},"deny-set-webview-zoom":{"identifier":"deny-set-webview-zoom","description":"Denies the set_webview_zoom command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_zoom"]}},"deny-webview-close":{"identifier":"deny-webview-close","description":"Denies the webview_close command without any pre-configured scope.","commands":{"allow":[],"deny":["webview_close"]}},"deny-webview-hide":{"identifier":"deny-webview-hide","description":"Denies the webview_hide command without any pre-configured scope.","commands":{"allow":[],"deny":["webview_hide"]}},"deny-webview-position":{"identifier":"deny-webview-position","description":"Denies the webview_position command without any pre-configured scope.","commands":{"allow":[],"deny":["webview_position"]}},"deny-webview-show":{"identifier":"deny-webview-show","description":"Denies the webview_show command without any pre-configured scope.","commands":{"allow":[],"deny":["webview_show"]}},"deny-webview-size":{"identifier":"deny-webview-size","description":"Denies the webview_size command without any pre-configured scope.","commands":{"allow":[],"deny":["webview_size"]}}},"permission_sets":{},"global_scope_schema":null},"core:window":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin.","permissions":["allow-get-all-windows","allow-scale-factor","allow-inner-position","allow-outer-position","allow-inner-size","allow-outer-size","allow-is-fullscreen","allow-is-minimized","allow-is-maximized","allow-is-focused","allow-is-decorated","allow-is-resizable","allow-is-maximizable","allow-is-minimizable","allow-is-closable","allow-is-visible","allow-is-enabled","allow-title","allow-current-monitor","allow-primary-monitor","allow-monitor-from-point","allow-available-monitors","allow-cursor-position","allow-theme","allow-is-always-on-top","allow-activity-name","allow-scene-identifier","allow-internal-toggle-maximize"]},"permissions":{"allow-activity-name":{"identifier":"allow-activity-name","description":"Enables the activity_name command without any pre-configured scope.","commands":{"allow":["activity_name"],"deny":[]}},"allow-available-monitors":{"identifier":"allow-available-monitors","description":"Enables the available_monitors command without any pre-configured scope.","commands":{"allow":["available_monitors"],"deny":[]}},"allow-center":{"identifier":"allow-center","description":"Enables the center command without any pre-configured scope.","commands":{"allow":["center"],"deny":[]}},"allow-close":{"identifier":"allow-close","description":"Enables the close command without any pre-configured scope.","commands":{"allow":["close"],"deny":[]}},"allow-create":{"identifier":"allow-create","description":"Enables the create command without any pre-configured scope.","commands":{"allow":["create"],"deny":[]}},"allow-current-monitor":{"identifier":"allow-current-monitor","description":"Enables the current_monitor command without any pre-configured scope.","commands":{"allow":["current_monitor"],"deny":[]}},"allow-cursor-position":{"identifier":"allow-cursor-position","description":"Enables the cursor_position command without any pre-configured scope.","commands":{"allow":["cursor_position"],"deny":[]}},"allow-destroy":{"identifier":"allow-destroy","description":"Enables the destroy command without any pre-configured scope.","commands":{"allow":["destroy"],"deny":[]}},"allow-get-all-windows":{"identifier":"allow-get-all-windows","description":"Enables the get_all_windows command without any pre-configured scope.","commands":{"allow":["get_all_windows"],"deny":[]}},"allow-hide":{"identifier":"allow-hide","description":"Enables the hide command without any pre-configured scope.","commands":{"allow":["hide"],"deny":[]}},"allow-inner-position":{"identifier":"allow-inner-position","description":"Enables the inner_position command without any pre-configured scope.","commands":{"allow":["inner_position"],"deny":[]}},"allow-inner-size":{"identifier":"allow-inner-size","description":"Enables the inner_size command without any pre-configured scope.","commands":{"allow":["inner_size"],"deny":[]}},"allow-internal-toggle-maximize":{"identifier":"allow-internal-toggle-maximize","description":"Enables the internal_toggle_maximize command without any pre-configured scope.","commands":{"allow":["internal_toggle_maximize"],"deny":[]}},"allow-is-always-on-top":{"identifier":"allow-is-always-on-top","description":"Enables the is_always_on_top command without any pre-configured scope.","commands":{"allow":["is_always_on_top"],"deny":[]}},"allow-is-closable":{"identifier":"allow-is-closable","description":"Enables the is_closable command without any pre-configured scope.","commands":{"allow":["is_closable"],"deny":[]}},"allow-is-decorated":{"identifier":"allow-is-decorated","description":"Enables the is_decorated command without any pre-configured scope.","commands":{"allow":["is_decorated"],"deny":[]}},"allow-is-enabled":{"identifier":"allow-is-enabled","description":"Enables the is_enabled command without any pre-configured scope.","commands":{"allow":["is_enabled"],"deny":[]}},"allow-is-focused":{"identifier":"allow-is-focused","description":"Enables the is_focused command without any pre-configured scope.","commands":{"allow":["is_focused"],"deny":[]}},"allow-is-fullscreen":{"identifier":"allow-is-fullscreen","description":"Enables the is_fullscreen command without any pre-configured scope.","commands":{"allow":["is_fullscreen"],"deny":[]}},"allow-is-maximizable":{"identifier":"allow-is-maximizable","description":"Enables the is_maximizable command without any pre-configured scope.","commands":{"allow":["is_maximizable"],"deny":[]}},"allow-is-maximized":{"identifier":"allow-is-maximized","description":"Enables the is_maximized command without any pre-configured scope.","commands":{"allow":["is_maximized"],"deny":[]}},"allow-is-minimizable":{"identifier":"allow-is-minimizable","description":"Enables the is_minimizable command without any pre-configured scope.","commands":{"allow":["is_minimizable"],"deny":[]}},"allow-is-minimized":{"identifier":"allow-is-minimized","description":"Enables the is_minimized command without any pre-configured scope.","commands":{"allow":["is_minimized"],"deny":[]}},"allow-is-resizable":{"identifier":"allow-is-resizable","description":"Enables the is_resizable command without any pre-configured scope.","commands":{"allow":["is_resizable"],"deny":[]}},"allow-is-visible":{"identifier":"allow-is-visible","description":"Enables the is_visible command without any pre-configured scope.","commands":{"allow":["is_visible"],"deny":[]}},"allow-maximize":{"identifier":"allow-maximize","description":"Enables the maximize command without any pre-configured scope.","commands":{"allow":["maximize"],"deny":[]}},"allow-minimize":{"identifier":"allow-minimize","description":"Enables the minimize command without any pre-configured scope.","commands":{"allow":["minimize"],"deny":[]}},"allow-monitor-from-point":{"identifier":"allow-monitor-from-point","description":"Enables the monitor_from_point command without any pre-configured scope.","commands":{"allow":["monitor_from_point"],"deny":[]}},"allow-outer-position":{"identifier":"allow-outer-position","description":"Enables the outer_position command without any pre-configured scope.","commands":{"allow":["outer_position"],"deny":[]}},"allow-outer-size":{"identifier":"allow-outer-size","description":"Enables the outer_size command without any pre-configured scope.","commands":{"allow":["outer_size"],"deny":[]}},"allow-primary-monitor":{"identifier":"allow-primary-monitor","description":"Enables the primary_monitor command without any pre-configured scope.","commands":{"allow":["primary_monitor"],"deny":[]}},"allow-request-user-attention":{"identifier":"allow-request-user-attention","description":"Enables the request_user_attention command without any pre-configured scope.","commands":{"allow":["request_user_attention"],"deny":[]}},"allow-scale-factor":{"identifier":"allow-scale-factor","description":"Enables the scale_factor command without any pre-configured scope.","commands":{"allow":["scale_factor"],"deny":[]}},"allow-scene-identifier":{"identifier":"allow-scene-identifier","description":"Enables the scene_identifier command without any pre-configured scope.","commands":{"allow":["scene_identifier"],"deny":[]}},"allow-set-always-on-bottom":{"identifier":"allow-set-always-on-bottom","description":"Enables the set_always_on_bottom command without any pre-configured scope.","commands":{"allow":["set_always_on_bottom"],"deny":[]}},"allow-set-always-on-top":{"identifier":"allow-set-always-on-top","description":"Enables the set_always_on_top command without any pre-configured scope.","commands":{"allow":["set_always_on_top"],"deny":[]}},"allow-set-background-color":{"identifier":"allow-set-background-color","description":"Enables the set_background_color command without any pre-configured scope.","commands":{"allow":["set_background_color"],"deny":[]}},"allow-set-badge-count":{"identifier":"allow-set-badge-count","description":"Enables the set_badge_count command without any pre-configured scope.","commands":{"allow":["set_badge_count"],"deny":[]}},"allow-set-badge-label":{"identifier":"allow-set-badge-label","description":"Enables the set_badge_label command without any pre-configured scope.","commands":{"allow":["set_badge_label"],"deny":[]}},"allow-set-closable":{"identifier":"allow-set-closable","description":"Enables the set_closable command without any pre-configured scope.","commands":{"allow":["set_closable"],"deny":[]}},"allow-set-content-protected":{"identifier":"allow-set-content-protected","description":"Enables the set_content_protected command without any pre-configured scope.","commands":{"allow":["set_content_protected"],"deny":[]}},"allow-set-cursor-grab":{"identifier":"allow-set-cursor-grab","description":"Enables the set_cursor_grab command without any pre-configured scope.","commands":{"allow":["set_cursor_grab"],"deny":[]}},"allow-set-cursor-icon":{"identifier":"allow-set-cursor-icon","description":"Enables the set_cursor_icon command without any pre-configured scope.","commands":{"allow":["set_cursor_icon"],"deny":[]}},"allow-set-cursor-position":{"identifier":"allow-set-cursor-position","description":"Enables the set_cursor_position command without any pre-configured scope.","commands":{"allow":["set_cursor_position"],"deny":[]}},"allow-set-cursor-visible":{"identifier":"allow-set-cursor-visible","description":"Enables the set_cursor_visible command without any pre-configured scope.","commands":{"allow":["set_cursor_visible"],"deny":[]}},"allow-set-decorations":{"identifier":"allow-set-decorations","description":"Enables the set_decorations command without any pre-configured scope.","commands":{"allow":["set_decorations"],"deny":[]}},"allow-set-effects":{"identifier":"allow-set-effects","description":"Enables the set_effects command without any pre-configured scope.","commands":{"allow":["set_effects"],"deny":[]}},"allow-set-enabled":{"identifier":"allow-set-enabled","description":"Enables the set_enabled command without any pre-configured scope.","commands":{"allow":["set_enabled"],"deny":[]}},"allow-set-focus":{"identifier":"allow-set-focus","description":"Enables the set_focus command without any pre-configured scope.","commands":{"allow":["set_focus"],"deny":[]}},"allow-set-focusable":{"identifier":"allow-set-focusable","description":"Enables the set_focusable command without any pre-configured scope.","commands":{"allow":["set_focusable"],"deny":[]}},"allow-set-fullscreen":{"identifier":"allow-set-fullscreen","description":"Enables the set_fullscreen command without any pre-configured scope.","commands":{"allow":["set_fullscreen"],"deny":[]}},"allow-set-fullscreen-on-monitor":{"identifier":"allow-set-fullscreen-on-monitor","description":"Enables the set_fullscreen_on_monitor command without any pre-configured scope.","commands":{"allow":["set_fullscreen_on_monitor"],"deny":[]}},"allow-set-icon":{"identifier":"allow-set-icon","description":"Enables the set_icon command without any pre-configured scope.","commands":{"allow":["set_icon"],"deny":[]}},"allow-set-ignore-cursor-events":{"identifier":"allow-set-ignore-cursor-events","description":"Enables the set_ignore_cursor_events command without any pre-configured scope.","commands":{"allow":["set_ignore_cursor_events"],"deny":[]}},"allow-set-max-size":{"identifier":"allow-set-max-size","description":"Enables the set_max_size command without any pre-configured scope.","commands":{"allow":["set_max_size"],"deny":[]}},"allow-set-maximizable":{"identifier":"allow-set-maximizable","description":"Enables the set_maximizable command without any pre-configured scope.","commands":{"allow":["set_maximizable"],"deny":[]}},"allow-set-min-size":{"identifier":"allow-set-min-size","description":"Enables the set_min_size command without any pre-configured scope.","commands":{"allow":["set_min_size"],"deny":[]}},"allow-set-minimizable":{"identifier":"allow-set-minimizable","description":"Enables the set_minimizable command without any pre-configured scope.","commands":{"allow":["set_minimizable"],"deny":[]}},"allow-set-overlay-icon":{"identifier":"allow-set-overlay-icon","description":"Enables the set_overlay_icon command without any pre-configured scope.","commands":{"allow":["set_overlay_icon"],"deny":[]}},"allow-set-position":{"identifier":"allow-set-position","description":"Enables the set_position command without any pre-configured scope.","commands":{"allow":["set_position"],"deny":[]}},"allow-set-progress-bar":{"identifier":"allow-set-progress-bar","description":"Enables the set_progress_bar command without any pre-configured scope.","commands":{"allow":["set_progress_bar"],"deny":[]}},"allow-set-resizable":{"identifier":"allow-set-resizable","description":"Enables the set_resizable command without any pre-configured scope.","commands":{"allow":["set_resizable"],"deny":[]}},"allow-set-shadow":{"identifier":"allow-set-shadow","description":"Enables the set_shadow command without any pre-configured scope.","commands":{"allow":["set_shadow"],"deny":[]}},"allow-set-simple-fullscreen":{"identifier":"allow-set-simple-fullscreen","description":"Enables the set_simple_fullscreen command without any pre-configured scope.","commands":{"allow":["set_simple_fullscreen"],"deny":[]}},"allow-set-size":{"identifier":"allow-set-size","description":"Enables the set_size command without any pre-configured scope.","commands":{"allow":["set_size"],"deny":[]}},"allow-set-size-constraints":{"identifier":"allow-set-size-constraints","description":"Enables the set_size_constraints command without any pre-configured scope.","commands":{"allow":["set_size_constraints"],"deny":[]}},"allow-set-skip-taskbar":{"identifier":"allow-set-skip-taskbar","description":"Enables the set_skip_taskbar command without any pre-configured scope.","commands":{"allow":["set_skip_taskbar"],"deny":[]}},"allow-set-theme":{"identifier":"allow-set-theme","description":"Enables the set_theme command without any pre-configured scope.","commands":{"allow":["set_theme"],"deny":[]}},"allow-set-title":{"identifier":"allow-set-title","description":"Enables the set_title command without any pre-configured scope.","commands":{"allow":["set_title"],"deny":[]}},"allow-set-title-bar-style":{"identifier":"allow-set-title-bar-style","description":"Enables the set_title_bar_style command without any pre-configured scope.","commands":{"allow":["set_title_bar_style"],"deny":[]}},"allow-set-visible-on-all-workspaces":{"identifier":"allow-set-visible-on-all-workspaces","description":"Enables the set_visible_on_all_workspaces command without any pre-configured scope.","commands":{"allow":["set_visible_on_all_workspaces"],"deny":[]}},"allow-show":{"identifier":"allow-show","description":"Enables the show command without any pre-configured scope.","commands":{"allow":["show"],"deny":[]}},"allow-start-dragging":{"identifier":"allow-start-dragging","description":"Enables the start_dragging command without any pre-configured scope.","commands":{"allow":["start_dragging"],"deny":[]}},"allow-start-resize-dragging":{"identifier":"allow-start-resize-dragging","description":"Enables the start_resize_dragging command without any pre-configured scope.","commands":{"allow":["start_resize_dragging"],"deny":[]}},"allow-theme":{"identifier":"allow-theme","description":"Enables the theme command without any pre-configured scope.","commands":{"allow":["theme"],"deny":[]}},"allow-title":{"identifier":"allow-title","description":"Enables the title command without any pre-configured scope.","commands":{"allow":["title"],"deny":[]}},"allow-toggle-maximize":{"identifier":"allow-toggle-maximize","description":"Enables the toggle_maximize command without any pre-configured scope.","commands":{"allow":["toggle_maximize"],"deny":[]}},"allow-unmaximize":{"identifier":"allow-unmaximize","description":"Enables the unmaximize command without any pre-configured scope.","commands":{"allow":["unmaximize"],"deny":[]}},"allow-unminimize":{"identifier":"allow-unminimize","description":"Enables the unminimize command without any pre-configured scope.","commands":{"allow":["unminimize"],"deny":[]}},"deny-activity-name":{"identifier":"deny-activity-name","description":"Denies the activity_name command without any pre-configured scope.","commands":{"allow":[],"deny":["activity_name"]}},"deny-available-monitors":{"identifier":"deny-available-monitors","description":"Denies the available_monitors command without any pre-configured scope.","commands":{"allow":[],"deny":["available_monitors"]}},"deny-center":{"identifier":"deny-center","description":"Denies the center command without any pre-configured scope.","commands":{"allow":[],"deny":["center"]}},"deny-close":{"identifier":"deny-close","description":"Denies the close command without any pre-configured scope.","commands":{"allow":[],"deny":["close"]}},"deny-create":{"identifier":"deny-create","description":"Denies the create command without any pre-configured scope.","commands":{"allow":[],"deny":["create"]}},"deny-current-monitor":{"identifier":"deny-current-monitor","description":"Denies the current_monitor command without any pre-configured scope.","commands":{"allow":[],"deny":["current_monitor"]}},"deny-cursor-position":{"identifier":"deny-cursor-position","description":"Denies the cursor_position command without any pre-configured scope.","commands":{"allow":[],"deny":["cursor_position"]}},"deny-destroy":{"identifier":"deny-destroy","description":"Denies the destroy command without any pre-configured scope.","commands":{"allow":[],"deny":["destroy"]}},"deny-get-all-windows":{"identifier":"deny-get-all-windows","description":"Denies the get_all_windows command without any pre-configured scope.","commands":{"allow":[],"deny":["get_all_windows"]}},"deny-hide":{"identifier":"deny-hide","description":"Denies the hide command without any pre-configured scope.","commands":{"allow":[],"deny":["hide"]}},"deny-inner-position":{"identifier":"deny-inner-position","description":"Denies the inner_position command without any pre-configured scope.","commands":{"allow":[],"deny":["inner_position"]}},"deny-inner-size":{"identifier":"deny-inner-size","description":"Denies the inner_size command without any pre-configured scope.","commands":{"allow":[],"deny":["inner_size"]}},"deny-internal-toggle-maximize":{"identifier":"deny-internal-toggle-maximize","description":"Denies the internal_toggle_maximize command without any pre-configured scope.","commands":{"allow":[],"deny":["internal_toggle_maximize"]}},"deny-is-always-on-top":{"identifier":"deny-is-always-on-top","description":"Denies the is_always_on_top command without any pre-configured scope.","commands":{"allow":[],"deny":["is_always_on_top"]}},"deny-is-closable":{"identifier":"deny-is-closable","description":"Denies the is_closable command without any pre-configured scope.","commands":{"allow":[],"deny":["is_closable"]}},"deny-is-decorated":{"identifier":"deny-is-decorated","description":"Denies the is_decorated command without any pre-configured scope.","commands":{"allow":[],"deny":["is_decorated"]}},"deny-is-enabled":{"identifier":"deny-is-enabled","description":"Denies the is_enabled command without any pre-configured scope.","commands":{"allow":[],"deny":["is_enabled"]}},"deny-is-focused":{"identifier":"deny-is-focused","description":"Denies the is_focused command without any pre-configured scope.","commands":{"allow":[],"deny":["is_focused"]}},"deny-is-fullscreen":{"identifier":"deny-is-fullscreen","description":"Denies the is_fullscreen command without any pre-configured scope.","commands":{"allow":[],"deny":["is_fullscreen"]}},"deny-is-maximizable":{"identifier":"deny-is-maximizable","description":"Denies the is_maximizable command without any pre-configured scope.","commands":{"allow":[],"deny":["is_maximizable"]}},"deny-is-maximized":{"identifier":"deny-is-maximized","description":"Denies the is_maximized command without any pre-configured scope.","commands":{"allow":[],"deny":["is_maximized"]}},"deny-is-minimizable":{"identifier":"deny-is-minimizable","description":"Denies the is_minimizable command without any pre-configured scope.","commands":{"allow":[],"deny":["is_minimizable"]}},"deny-is-minimized":{"identifier":"deny-is-minimized","description":"Denies the is_minimized command without any pre-configured scope.","commands":{"allow":[],"deny":["is_minimized"]}},"deny-is-resizable":{"identifier":"deny-is-resizable","description":"Denies the is_resizable command without any pre-configured scope.","commands":{"allow":[],"deny":["is_resizable"]}},"deny-is-visible":{"identifier":"deny-is-visible","description":"Denies the is_visible command without any pre-configured scope.","commands":{"allow":[],"deny":["is_visible"]}},"deny-maximize":{"identifier":"deny-maximize","description":"Denies the maximize command without any pre-configured scope.","commands":{"allow":[],"deny":["maximize"]}},"deny-minimize":{"identifier":"deny-minimize","description":"Denies the minimize command without any pre-configured scope.","commands":{"allow":[],"deny":["minimize"]}},"deny-monitor-from-point":{"identifier":"deny-monitor-from-point","description":"Denies the monitor_from_point command without any pre-configured scope.","commands":{"allow":[],"deny":["monitor_from_point"]}},"deny-outer-position":{"identifier":"deny-outer-position","description":"Denies the outer_position command without any pre-configured scope.","commands":{"allow":[],"deny":["outer_position"]}},"deny-outer-size":{"identifier":"deny-outer-size","description":"Denies the outer_size command without any pre-configured scope.","commands":{"allow":[],"deny":["outer_size"]}},"deny-primary-monitor":{"identifier":"deny-primary-monitor","description":"Denies the primary_monitor command without any pre-configured scope.","commands":{"allow":[],"deny":["primary_monitor"]}},"deny-request-user-attention":{"identifier":"deny-request-user-attention","description":"Denies the request_user_attention command without any pre-configured scope.","commands":{"allow":[],"deny":["request_user_attention"]}},"deny-scale-factor":{"identifier":"deny-scale-factor","description":"Denies the scale_factor command without any pre-configured scope.","commands":{"allow":[],"deny":["scale_factor"]}},"deny-scene-identifier":{"identifier":"deny-scene-identifier","description":"Denies the scene_identifier command without any pre-configured scope.","commands":{"allow":[],"deny":["scene_identifier"]}},"deny-set-always-on-bottom":{"identifier":"deny-set-always-on-bottom","description":"Denies the set_always_on_bottom command without any pre-configured scope.","commands":{"allow":[],"deny":["set_always_on_bottom"]}},"deny-set-always-on-top":{"identifier":"deny-set-always-on-top","description":"Denies the set_always_on_top command without any pre-configured scope.","commands":{"allow":[],"deny":["set_always_on_top"]}},"deny-set-background-color":{"identifier":"deny-set-background-color","description":"Denies the set_background_color command without any pre-configured scope.","commands":{"allow":[],"deny":["set_background_color"]}},"deny-set-badge-count":{"identifier":"deny-set-badge-count","description":"Denies the set_badge_count command without any pre-configured scope.","commands":{"allow":[],"deny":["set_badge_count"]}},"deny-set-badge-label":{"identifier":"deny-set-badge-label","description":"Denies the set_badge_label command without any pre-configured scope.","commands":{"allow":[],"deny":["set_badge_label"]}},"deny-set-closable":{"identifier":"deny-set-closable","description":"Denies the set_closable command without any pre-configured scope.","commands":{"allow":[],"deny":["set_closable"]}},"deny-set-content-protected":{"identifier":"deny-set-content-protected","description":"Denies the set_content_protected command without any pre-configured scope.","commands":{"allow":[],"deny":["set_content_protected"]}},"deny-set-cursor-grab":{"identifier":"deny-set-cursor-grab","description":"Denies the set_cursor_grab command without any pre-configured scope.","commands":{"allow":[],"deny":["set_cursor_grab"]}},"deny-set-cursor-icon":{"identifier":"deny-set-cursor-icon","description":"Denies the set_cursor_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["set_cursor_icon"]}},"deny-set-cursor-position":{"identifier":"deny-set-cursor-position","description":"Denies the set_cursor_position command without any pre-configured scope.","commands":{"allow":[],"deny":["set_cursor_position"]}},"deny-set-cursor-visible":{"identifier":"deny-set-cursor-visible","description":"Denies the set_cursor_visible command without any pre-configured scope.","commands":{"allow":[],"deny":["set_cursor_visible"]}},"deny-set-decorations":{"identifier":"deny-set-decorations","description":"Denies the set_decorations command without any pre-configured scope.","commands":{"allow":[],"deny":["set_decorations"]}},"deny-set-effects":{"identifier":"deny-set-effects","description":"Denies the set_effects command without any pre-configured scope.","commands":{"allow":[],"deny":["set_effects"]}},"deny-set-enabled":{"identifier":"deny-set-enabled","description":"Denies the set_enabled command without any pre-configured scope.","commands":{"allow":[],"deny":["set_enabled"]}},"deny-set-focus":{"identifier":"deny-set-focus","description":"Denies the set_focus command without any pre-configured scope.","commands":{"allow":[],"deny":["set_focus"]}},"deny-set-focusable":{"identifier":"deny-set-focusable","description":"Denies the set_focusable command without any pre-configured scope.","commands":{"allow":[],"deny":["set_focusable"]}},"deny-set-fullscreen":{"identifier":"deny-set-fullscreen","description":"Denies the set_fullscreen command without any pre-configured scope.","commands":{"allow":[],"deny":["set_fullscreen"]}},"deny-set-fullscreen-on-monitor":{"identifier":"deny-set-fullscreen-on-monitor","description":"Denies the set_fullscreen_on_monitor command without any pre-configured scope.","commands":{"allow":[],"deny":["set_fullscreen_on_monitor"]}},"deny-set-icon":{"identifier":"deny-set-icon","description":"Denies the set_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["set_icon"]}},"deny-set-ignore-cursor-events":{"identifier":"deny-set-ignore-cursor-events","description":"Denies the set_ignore_cursor_events command without any pre-configured scope.","commands":{"allow":[],"deny":["set_ignore_cursor_events"]}},"deny-set-max-size":{"identifier":"deny-set-max-size","description":"Denies the set_max_size command without any pre-configured scope.","commands":{"allow":[],"deny":["set_max_size"]}},"deny-set-maximizable":{"identifier":"deny-set-maximizable","description":"Denies the set_maximizable command without any pre-configured scope.","commands":{"allow":[],"deny":["set_maximizable"]}},"deny-set-min-size":{"identifier":"deny-set-min-size","description":"Denies the set_min_size command without any pre-configured scope.","commands":{"allow":[],"deny":["set_min_size"]}},"deny-set-minimizable":{"identifier":"deny-set-minimizable","description":"Denies the set_minimizable command without any pre-configured scope.","commands":{"allow":[],"deny":["set_minimizable"]}},"deny-set-overlay-icon":{"identifier":"deny-set-overlay-icon","description":"Denies the set_overlay_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["set_overlay_icon"]}},"deny-set-position":{"identifier":"deny-set-position","description":"Denies the set_position command without any pre-configured scope.","commands":{"allow":[],"deny":["set_position"]}},"deny-set-progress-bar":{"identifier":"deny-set-progress-bar","description":"Denies the set_progress_bar command without any pre-configured scope.","commands":{"allow":[],"deny":["set_progress_bar"]}},"deny-set-resizable":{"identifier":"deny-set-resizable","description":"Denies the set_resizable command without any pre-configured scope.","commands":{"allow":[],"deny":["set_resizable"]}},"deny-set-shadow":{"identifier":"deny-set-shadow","description":"Denies the set_shadow command without any pre-configured scope.","commands":{"allow":[],"deny":["set_shadow"]}},"deny-set-simple-fullscreen":{"identifier":"deny-set-simple-fullscreen","description":"Denies the set_simple_fullscreen command without any pre-configured scope.","commands":{"allow":[],"deny":["set_simple_fullscreen"]}},"deny-set-size":{"identifier":"deny-set-size","description":"Denies the set_size command without any pre-configured scope.","commands":{"allow":[],"deny":["set_size"]}},"deny-set-size-constraints":{"identifier":"deny-set-size-constraints","description":"Denies the set_size_constraints command without any pre-configured scope.","commands":{"allow":[],"deny":["set_size_constraints"]}},"deny-set-skip-taskbar":{"identifier":"deny-set-skip-taskbar","description":"Denies the set_skip_taskbar command without any pre-configured scope.","commands":{"allow":[],"deny":["set_skip_taskbar"]}},"deny-set-theme":{"identifier":"deny-set-theme","description":"Denies the set_theme command without any pre-configured scope.","commands":{"allow":[],"deny":["set_theme"]}},"deny-set-title":{"identifier":"deny-set-title","description":"Denies the set_title command without any pre-configured scope.","commands":{"allow":[],"deny":["set_title"]}},"deny-set-title-bar-style":{"identifier":"deny-set-title-bar-style","description":"Denies the set_title_bar_style command without any pre-configured scope.","commands":{"allow":[],"deny":["set_title_bar_style"]}},"deny-set-visible-on-all-workspaces":{"identifier":"deny-set-visible-on-all-workspaces","description":"Denies the set_visible_on_all_workspaces command without any pre-configured scope.","commands":{"allow":[],"deny":["set_visible_on_all_workspaces"]}},"deny-show":{"identifier":"deny-show","description":"Denies the show command without any pre-configured scope.","commands":{"allow":[],"deny":["show"]}},"deny-start-dragging":{"identifier":"deny-start-dragging","description":"Denies the start_dragging command without any pre-configured scope.","commands":{"allow":[],"deny":["start_dragging"]}},"deny-start-resize-dragging":{"identifier":"deny-start-resize-dragging","description":"Denies the start_resize_dragging command without any pre-configured scope.","commands":{"allow":[],"deny":["start_resize_dragging"]}},"deny-theme":{"identifier":"deny-theme","description":"Denies the theme command without any pre-configured scope.","commands":{"allow":[],"deny":["theme"]}},"deny-title":{"identifier":"deny-title","description":"Denies the title command without any pre-configured scope.","commands":{"allow":[],"deny":["title"]}},"deny-toggle-maximize":{"identifier":"deny-toggle-maximize","description":"Denies the toggle_maximize command without any pre-configured scope.","commands":{"allow":[],"deny":["toggle_maximize"]}},"deny-unmaximize":{"identifier":"deny-unmaximize","description":"Denies the unmaximize command without any pre-configured scope.","commands":{"allow":[],"deny":["unmaximize"]}},"deny-unminimize":{"identifier":"deny-unminimize","description":"Denies the unminimize command without any pre-configured scope.","commands":{"allow":[],"deny":["unminimize"]}}},"permission_sets":{},"global_scope_schema":null}} \ No newline at end of file +{"core":{"default_permission":{"identifier":"default","description":"Default core plugins set.","permissions":["core:path:default","core:event:default","core:window:default","core:webview:default","core:app:default","core:image:default","core:resources:default","core:menu:default","core:tray:default"]},"permissions":{},"permission_sets":{},"global_scope_schema":null},"core:app":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin.","permissions":["allow-version","allow-name","allow-tauri-version","allow-identifier","allow-bundle-type","allow-register-listener","allow-remove-listener","allow-supports-multiple-windows"]},"permissions":{"allow-app-hide":{"identifier":"allow-app-hide","description":"Enables the app_hide command without any pre-configured scope.","commands":{"allow":["app_hide"],"deny":[]}},"allow-app-show":{"identifier":"allow-app-show","description":"Enables the app_show command without any pre-configured scope.","commands":{"allow":["app_show"],"deny":[]}},"allow-bundle-type":{"identifier":"allow-bundle-type","description":"Enables the bundle_type command without any pre-configured scope.","commands":{"allow":["bundle_type"],"deny":[]}},"allow-default-window-icon":{"identifier":"allow-default-window-icon","description":"Enables the default_window_icon command without any pre-configured scope.","commands":{"allow":["default_window_icon"],"deny":[]}},"allow-exit":{"identifier":"allow-exit","description":"Enables the exit command without any pre-configured scope.","commands":{"allow":["exit"],"deny":[]}},"allow-fetch-data-store-identifiers":{"identifier":"allow-fetch-data-store-identifiers","description":"Enables the fetch_data_store_identifiers command without any pre-configured scope.","commands":{"allow":["fetch_data_store_identifiers"],"deny":[]}},"allow-identifier":{"identifier":"allow-identifier","description":"Enables the identifier command without any pre-configured scope.","commands":{"allow":["identifier"],"deny":[]}},"allow-name":{"identifier":"allow-name","description":"Enables the name command without any pre-configured scope.","commands":{"allow":["name"],"deny":[]}},"allow-register-listener":{"identifier":"allow-register-listener","description":"Enables the register_listener command without any pre-configured scope.","commands":{"allow":["register_listener"],"deny":[]}},"allow-remove-data-store":{"identifier":"allow-remove-data-store","description":"Enables the remove_data_store command without any pre-configured scope.","commands":{"allow":["remove_data_store"],"deny":[]}},"allow-remove-listener":{"identifier":"allow-remove-listener","description":"Enables the remove_listener command without any pre-configured scope.","commands":{"allow":["remove_listener"],"deny":[]}},"allow-set-app-theme":{"identifier":"allow-set-app-theme","description":"Enables the set_app_theme command without any pre-configured scope.","commands":{"allow":["set_app_theme"],"deny":[]}},"allow-set-dock-visibility":{"identifier":"allow-set-dock-visibility","description":"Enables the set_dock_visibility command without any pre-configured scope.","commands":{"allow":["set_dock_visibility"],"deny":[]}},"allow-supports-multiple-windows":{"identifier":"allow-supports-multiple-windows","description":"Enables the supports_multiple_windows command without any pre-configured scope.","commands":{"allow":["supports_multiple_windows"],"deny":[]}},"allow-tauri-version":{"identifier":"allow-tauri-version","description":"Enables the tauri_version command without any pre-configured scope.","commands":{"allow":["tauri_version"],"deny":[]}},"allow-version":{"identifier":"allow-version","description":"Enables the version command without any pre-configured scope.","commands":{"allow":["version"],"deny":[]}},"deny-app-hide":{"identifier":"deny-app-hide","description":"Denies the app_hide command without any pre-configured scope.","commands":{"allow":[],"deny":["app_hide"]}},"deny-app-show":{"identifier":"deny-app-show","description":"Denies the app_show command without any pre-configured scope.","commands":{"allow":[],"deny":["app_show"]}},"deny-bundle-type":{"identifier":"deny-bundle-type","description":"Denies the bundle_type command without any pre-configured scope.","commands":{"allow":[],"deny":["bundle_type"]}},"deny-default-window-icon":{"identifier":"deny-default-window-icon","description":"Denies the default_window_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["default_window_icon"]}},"deny-exit":{"identifier":"deny-exit","description":"Denies the exit command without any pre-configured scope.","commands":{"allow":[],"deny":["exit"]}},"deny-fetch-data-store-identifiers":{"identifier":"deny-fetch-data-store-identifiers","description":"Denies the fetch_data_store_identifiers command without any pre-configured scope.","commands":{"allow":[],"deny":["fetch_data_store_identifiers"]}},"deny-identifier":{"identifier":"deny-identifier","description":"Denies the identifier command without any pre-configured scope.","commands":{"allow":[],"deny":["identifier"]}},"deny-name":{"identifier":"deny-name","description":"Denies the name command without any pre-configured scope.","commands":{"allow":[],"deny":["name"]}},"deny-register-listener":{"identifier":"deny-register-listener","description":"Denies the register_listener command without any pre-configured scope.","commands":{"allow":[],"deny":["register_listener"]}},"deny-remove-data-store":{"identifier":"deny-remove-data-store","description":"Denies the remove_data_store command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_data_store"]}},"deny-remove-listener":{"identifier":"deny-remove-listener","description":"Denies the remove_listener command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_listener"]}},"deny-set-app-theme":{"identifier":"deny-set-app-theme","description":"Denies the set_app_theme command without any pre-configured scope.","commands":{"allow":[],"deny":["set_app_theme"]}},"deny-set-dock-visibility":{"identifier":"deny-set-dock-visibility","description":"Denies the set_dock_visibility command without any pre-configured scope.","commands":{"allow":[],"deny":["set_dock_visibility"]}},"deny-supports-multiple-windows":{"identifier":"deny-supports-multiple-windows","description":"Denies the supports_multiple_windows command without any pre-configured scope.","commands":{"allow":[],"deny":["supports_multiple_windows"]}},"deny-tauri-version":{"identifier":"deny-tauri-version","description":"Denies the tauri_version command without any pre-configured scope.","commands":{"allow":[],"deny":["tauri_version"]}},"deny-version":{"identifier":"deny-version","description":"Denies the version command without any pre-configured scope.","commands":{"allow":[],"deny":["version"]}}},"permission_sets":{},"global_scope_schema":null},"core:event":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-listen","allow-unlisten","allow-emit","allow-emit-to"]},"permissions":{"allow-emit":{"identifier":"allow-emit","description":"Enables the emit command without any pre-configured scope.","commands":{"allow":["emit"],"deny":[]}},"allow-emit-to":{"identifier":"allow-emit-to","description":"Enables the emit_to command without any pre-configured scope.","commands":{"allow":["emit_to"],"deny":[]}},"allow-listen":{"identifier":"allow-listen","description":"Enables the listen command without any pre-configured scope.","commands":{"allow":["listen"],"deny":[]}},"allow-unlisten":{"identifier":"allow-unlisten","description":"Enables the unlisten command without any pre-configured scope.","commands":{"allow":["unlisten"],"deny":[]}},"deny-emit":{"identifier":"deny-emit","description":"Denies the emit command without any pre-configured scope.","commands":{"allow":[],"deny":["emit"]}},"deny-emit-to":{"identifier":"deny-emit-to","description":"Denies the emit_to command without any pre-configured scope.","commands":{"allow":[],"deny":["emit_to"]}},"deny-listen":{"identifier":"deny-listen","description":"Denies the listen command without any pre-configured scope.","commands":{"allow":[],"deny":["listen"]}},"deny-unlisten":{"identifier":"deny-unlisten","description":"Denies the unlisten command without any pre-configured scope.","commands":{"allow":[],"deny":["unlisten"]}}},"permission_sets":{},"global_scope_schema":null},"core:image":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-new","allow-from-bytes","allow-from-path","allow-rgba","allow-size"]},"permissions":{"allow-from-bytes":{"identifier":"allow-from-bytes","description":"Enables the from_bytes command without any pre-configured scope.","commands":{"allow":["from_bytes"],"deny":[]}},"allow-from-path":{"identifier":"allow-from-path","description":"Enables the from_path command without any pre-configured scope.","commands":{"allow":["from_path"],"deny":[]}},"allow-new":{"identifier":"allow-new","description":"Enables the new command without any pre-configured scope.","commands":{"allow":["new"],"deny":[]}},"allow-rgba":{"identifier":"allow-rgba","description":"Enables the rgba command without any pre-configured scope.","commands":{"allow":["rgba"],"deny":[]}},"allow-size":{"identifier":"allow-size","description":"Enables the size command without any pre-configured scope.","commands":{"allow":["size"],"deny":[]}},"deny-from-bytes":{"identifier":"deny-from-bytes","description":"Denies the from_bytes command without any pre-configured scope.","commands":{"allow":[],"deny":["from_bytes"]}},"deny-from-path":{"identifier":"deny-from-path","description":"Denies the from_path command without any pre-configured scope.","commands":{"allow":[],"deny":["from_path"]}},"deny-new":{"identifier":"deny-new","description":"Denies the new command without any pre-configured scope.","commands":{"allow":[],"deny":["new"]}},"deny-rgba":{"identifier":"deny-rgba","description":"Denies the rgba command without any pre-configured scope.","commands":{"allow":[],"deny":["rgba"]}},"deny-size":{"identifier":"deny-size","description":"Denies the size command without any pre-configured scope.","commands":{"allow":[],"deny":["size"]}}},"permission_sets":{},"global_scope_schema":null},"core:menu":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-new","allow-append","allow-prepend","allow-insert","allow-remove","allow-remove-at","allow-items","allow-get","allow-popup","allow-create-default","allow-set-as-app-menu","allow-set-as-window-menu","allow-text","allow-set-text","allow-is-enabled","allow-set-enabled","allow-set-accelerator","allow-set-as-windows-menu-for-nsapp","allow-set-as-help-menu-for-nsapp","allow-is-checked","allow-set-checked","allow-set-icon"]},"permissions":{"allow-append":{"identifier":"allow-append","description":"Enables the append command without any pre-configured scope.","commands":{"allow":["append"],"deny":[]}},"allow-create-default":{"identifier":"allow-create-default","description":"Enables the create_default command without any pre-configured scope.","commands":{"allow":["create_default"],"deny":[]}},"allow-get":{"identifier":"allow-get","description":"Enables the get command without any pre-configured scope.","commands":{"allow":["get"],"deny":[]}},"allow-insert":{"identifier":"allow-insert","description":"Enables the insert command without any pre-configured scope.","commands":{"allow":["insert"],"deny":[]}},"allow-is-checked":{"identifier":"allow-is-checked","description":"Enables the is_checked command without any pre-configured scope.","commands":{"allow":["is_checked"],"deny":[]}},"allow-is-enabled":{"identifier":"allow-is-enabled","description":"Enables the is_enabled command without any pre-configured scope.","commands":{"allow":["is_enabled"],"deny":[]}},"allow-items":{"identifier":"allow-items","description":"Enables the items command without any pre-configured scope.","commands":{"allow":["items"],"deny":[]}},"allow-new":{"identifier":"allow-new","description":"Enables the new command without any pre-configured scope.","commands":{"allow":["new"],"deny":[]}},"allow-popup":{"identifier":"allow-popup","description":"Enables the popup command without any pre-configured scope.","commands":{"allow":["popup"],"deny":[]}},"allow-prepend":{"identifier":"allow-prepend","description":"Enables the prepend command without any pre-configured scope.","commands":{"allow":["prepend"],"deny":[]}},"allow-remove":{"identifier":"allow-remove","description":"Enables the remove command without any pre-configured scope.","commands":{"allow":["remove"],"deny":[]}},"allow-remove-at":{"identifier":"allow-remove-at","description":"Enables the remove_at command without any pre-configured scope.","commands":{"allow":["remove_at"],"deny":[]}},"allow-set-accelerator":{"identifier":"allow-set-accelerator","description":"Enables the set_accelerator command without any pre-configured scope.","commands":{"allow":["set_accelerator"],"deny":[]}},"allow-set-as-app-menu":{"identifier":"allow-set-as-app-menu","description":"Enables the set_as_app_menu command without any pre-configured scope.","commands":{"allow":["set_as_app_menu"],"deny":[]}},"allow-set-as-help-menu-for-nsapp":{"identifier":"allow-set-as-help-menu-for-nsapp","description":"Enables the set_as_help_menu_for_nsapp command without any pre-configured scope.","commands":{"allow":["set_as_help_menu_for_nsapp"],"deny":[]}},"allow-set-as-window-menu":{"identifier":"allow-set-as-window-menu","description":"Enables the set_as_window_menu command without any pre-configured scope.","commands":{"allow":["set_as_window_menu"],"deny":[]}},"allow-set-as-windows-menu-for-nsapp":{"identifier":"allow-set-as-windows-menu-for-nsapp","description":"Enables the set_as_windows_menu_for_nsapp command without any pre-configured scope.","commands":{"allow":["set_as_windows_menu_for_nsapp"],"deny":[]}},"allow-set-checked":{"identifier":"allow-set-checked","description":"Enables the set_checked command without any pre-configured scope.","commands":{"allow":["set_checked"],"deny":[]}},"allow-set-enabled":{"identifier":"allow-set-enabled","description":"Enables the set_enabled command without any pre-configured scope.","commands":{"allow":["set_enabled"],"deny":[]}},"allow-set-icon":{"identifier":"allow-set-icon","description":"Enables the set_icon command without any pre-configured scope.","commands":{"allow":["set_icon"],"deny":[]}},"allow-set-text":{"identifier":"allow-set-text","description":"Enables the set_text command without any pre-configured scope.","commands":{"allow":["set_text"],"deny":[]}},"allow-text":{"identifier":"allow-text","description":"Enables the text command without any pre-configured scope.","commands":{"allow":["text"],"deny":[]}},"deny-append":{"identifier":"deny-append","description":"Denies the append command without any pre-configured scope.","commands":{"allow":[],"deny":["append"]}},"deny-create-default":{"identifier":"deny-create-default","description":"Denies the create_default command without any pre-configured scope.","commands":{"allow":[],"deny":["create_default"]}},"deny-get":{"identifier":"deny-get","description":"Denies the get command without any pre-configured scope.","commands":{"allow":[],"deny":["get"]}},"deny-insert":{"identifier":"deny-insert","description":"Denies the insert command without any pre-configured scope.","commands":{"allow":[],"deny":["insert"]}},"deny-is-checked":{"identifier":"deny-is-checked","description":"Denies the is_checked command without any pre-configured scope.","commands":{"allow":[],"deny":["is_checked"]}},"deny-is-enabled":{"identifier":"deny-is-enabled","description":"Denies the is_enabled command without any pre-configured scope.","commands":{"allow":[],"deny":["is_enabled"]}},"deny-items":{"identifier":"deny-items","description":"Denies the items command without any pre-configured scope.","commands":{"allow":[],"deny":["items"]}},"deny-new":{"identifier":"deny-new","description":"Denies the new command without any pre-configured scope.","commands":{"allow":[],"deny":["new"]}},"deny-popup":{"identifier":"deny-popup","description":"Denies the popup command without any pre-configured scope.","commands":{"allow":[],"deny":["popup"]}},"deny-prepend":{"identifier":"deny-prepend","description":"Denies the prepend command without any pre-configured scope.","commands":{"allow":[],"deny":["prepend"]}},"deny-remove":{"identifier":"deny-remove","description":"Denies the remove command without any pre-configured scope.","commands":{"allow":[],"deny":["remove"]}},"deny-remove-at":{"identifier":"deny-remove-at","description":"Denies the remove_at command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_at"]}},"deny-set-accelerator":{"identifier":"deny-set-accelerator","description":"Denies the set_accelerator command without any pre-configured scope.","commands":{"allow":[],"deny":["set_accelerator"]}},"deny-set-as-app-menu":{"identifier":"deny-set-as-app-menu","description":"Denies the set_as_app_menu command without any pre-configured scope.","commands":{"allow":[],"deny":["set_as_app_menu"]}},"deny-set-as-help-menu-for-nsapp":{"identifier":"deny-set-as-help-menu-for-nsapp","description":"Denies the set_as_help_menu_for_nsapp command without any pre-configured scope.","commands":{"allow":[],"deny":["set_as_help_menu_for_nsapp"]}},"deny-set-as-window-menu":{"identifier":"deny-set-as-window-menu","description":"Denies the set_as_window_menu command without any pre-configured scope.","commands":{"allow":[],"deny":["set_as_window_menu"]}},"deny-set-as-windows-menu-for-nsapp":{"identifier":"deny-set-as-windows-menu-for-nsapp","description":"Denies the set_as_windows_menu_for_nsapp command without any pre-configured scope.","commands":{"allow":[],"deny":["set_as_windows_menu_for_nsapp"]}},"deny-set-checked":{"identifier":"deny-set-checked","description":"Denies the set_checked command without any pre-configured scope.","commands":{"allow":[],"deny":["set_checked"]}},"deny-set-enabled":{"identifier":"deny-set-enabled","description":"Denies the set_enabled command without any pre-configured scope.","commands":{"allow":[],"deny":["set_enabled"]}},"deny-set-icon":{"identifier":"deny-set-icon","description":"Denies the set_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["set_icon"]}},"deny-set-text":{"identifier":"deny-set-text","description":"Denies the set_text command without any pre-configured scope.","commands":{"allow":[],"deny":["set_text"]}},"deny-text":{"identifier":"deny-text","description":"Denies the text command without any pre-configured scope.","commands":{"allow":[],"deny":["text"]}}},"permission_sets":{},"global_scope_schema":null},"core:path":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-resolve-directory","allow-resolve","allow-normalize","allow-join","allow-dirname","allow-extname","allow-basename","allow-is-absolute"]},"permissions":{"allow-basename":{"identifier":"allow-basename","description":"Enables the basename command without any pre-configured scope.","commands":{"allow":["basename"],"deny":[]}},"allow-dirname":{"identifier":"allow-dirname","description":"Enables the dirname command without any pre-configured scope.","commands":{"allow":["dirname"],"deny":[]}},"allow-extname":{"identifier":"allow-extname","description":"Enables the extname command without any pre-configured scope.","commands":{"allow":["extname"],"deny":[]}},"allow-is-absolute":{"identifier":"allow-is-absolute","description":"Enables the is_absolute command without any pre-configured scope.","commands":{"allow":["is_absolute"],"deny":[]}},"allow-join":{"identifier":"allow-join","description":"Enables the join command without any pre-configured scope.","commands":{"allow":["join"],"deny":[]}},"allow-normalize":{"identifier":"allow-normalize","description":"Enables the normalize command without any pre-configured scope.","commands":{"allow":["normalize"],"deny":[]}},"allow-resolve":{"identifier":"allow-resolve","description":"Enables the resolve command without any pre-configured scope.","commands":{"allow":["resolve"],"deny":[]}},"allow-resolve-directory":{"identifier":"allow-resolve-directory","description":"Enables the resolve_directory command without any pre-configured scope.","commands":{"allow":["resolve_directory"],"deny":[]}},"deny-basename":{"identifier":"deny-basename","description":"Denies the basename command without any pre-configured scope.","commands":{"allow":[],"deny":["basename"]}},"deny-dirname":{"identifier":"deny-dirname","description":"Denies the dirname command without any pre-configured scope.","commands":{"allow":[],"deny":["dirname"]}},"deny-extname":{"identifier":"deny-extname","description":"Denies the extname command without any pre-configured scope.","commands":{"allow":[],"deny":["extname"]}},"deny-is-absolute":{"identifier":"deny-is-absolute","description":"Denies the is_absolute command without any pre-configured scope.","commands":{"allow":[],"deny":["is_absolute"]}},"deny-join":{"identifier":"deny-join","description":"Denies the join command without any pre-configured scope.","commands":{"allow":[],"deny":["join"]}},"deny-normalize":{"identifier":"deny-normalize","description":"Denies the normalize command without any pre-configured scope.","commands":{"allow":[],"deny":["normalize"]}},"deny-resolve":{"identifier":"deny-resolve","description":"Denies the resolve command without any pre-configured scope.","commands":{"allow":[],"deny":["resolve"]}},"deny-resolve-directory":{"identifier":"deny-resolve-directory","description":"Denies the resolve_directory command without any pre-configured scope.","commands":{"allow":[],"deny":["resolve_directory"]}}},"permission_sets":{},"global_scope_schema":null},"core:resources":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-close"]},"permissions":{"allow-close":{"identifier":"allow-close","description":"Enables the close command without any pre-configured scope.","commands":{"allow":["close"],"deny":[]}},"deny-close":{"identifier":"deny-close","description":"Denies the close command without any pre-configured scope.","commands":{"allow":[],"deny":["close"]}}},"permission_sets":{},"global_scope_schema":null},"core:tray":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-new","allow-get-by-id","allow-remove-by-id","allow-set-icon","allow-set-menu","allow-set-tooltip","allow-set-title","allow-set-visible","allow-set-temp-dir-path","allow-set-icon-as-template","allow-set-icon-with-as-template","allow-set-show-menu-on-left-click"]},"permissions":{"allow-get-by-id":{"identifier":"allow-get-by-id","description":"Enables the get_by_id command without any pre-configured scope.","commands":{"allow":["get_by_id"],"deny":[]}},"allow-new":{"identifier":"allow-new","description":"Enables the new command without any pre-configured scope.","commands":{"allow":["new"],"deny":[]}},"allow-remove-by-id":{"identifier":"allow-remove-by-id","description":"Enables the remove_by_id command without any pre-configured scope.","commands":{"allow":["remove_by_id"],"deny":[]}},"allow-set-icon":{"identifier":"allow-set-icon","description":"Enables the set_icon command without any pre-configured scope.","commands":{"allow":["set_icon"],"deny":[]}},"allow-set-icon-as-template":{"identifier":"allow-set-icon-as-template","description":"Enables the set_icon_as_template command without any pre-configured scope.","commands":{"allow":["set_icon_as_template"],"deny":[]}},"allow-set-icon-with-as-template":{"identifier":"allow-set-icon-with-as-template","description":"Enables the set_icon_with_as_template command without any pre-configured scope.","commands":{"allow":["set_icon_with_as_template"],"deny":[]}},"allow-set-menu":{"identifier":"allow-set-menu","description":"Enables the set_menu command without any pre-configured scope.","commands":{"allow":["set_menu"],"deny":[]}},"allow-set-show-menu-on-left-click":{"identifier":"allow-set-show-menu-on-left-click","description":"Enables the set_show_menu_on_left_click command without any pre-configured scope.","commands":{"allow":["set_show_menu_on_left_click"],"deny":[]}},"allow-set-temp-dir-path":{"identifier":"allow-set-temp-dir-path","description":"Enables the set_temp_dir_path command without any pre-configured scope.","commands":{"allow":["set_temp_dir_path"],"deny":[]}},"allow-set-title":{"identifier":"allow-set-title","description":"Enables the set_title command without any pre-configured scope.","commands":{"allow":["set_title"],"deny":[]}},"allow-set-tooltip":{"identifier":"allow-set-tooltip","description":"Enables the set_tooltip command without any pre-configured scope.","commands":{"allow":["set_tooltip"],"deny":[]}},"allow-set-visible":{"identifier":"allow-set-visible","description":"Enables the set_visible command without any pre-configured scope.","commands":{"allow":["set_visible"],"deny":[]}},"deny-get-by-id":{"identifier":"deny-get-by-id","description":"Denies the get_by_id command without any pre-configured scope.","commands":{"allow":[],"deny":["get_by_id"]}},"deny-new":{"identifier":"deny-new","description":"Denies the new command without any pre-configured scope.","commands":{"allow":[],"deny":["new"]}},"deny-remove-by-id":{"identifier":"deny-remove-by-id","description":"Denies the remove_by_id command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_by_id"]}},"deny-set-icon":{"identifier":"deny-set-icon","description":"Denies the set_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["set_icon"]}},"deny-set-icon-as-template":{"identifier":"deny-set-icon-as-template","description":"Denies the set_icon_as_template command without any pre-configured scope.","commands":{"allow":[],"deny":["set_icon_as_template"]}},"deny-set-icon-with-as-template":{"identifier":"deny-set-icon-with-as-template","description":"Denies the set_icon_with_as_template command without any pre-configured scope.","commands":{"allow":[],"deny":["set_icon_with_as_template"]}},"deny-set-menu":{"identifier":"deny-set-menu","description":"Denies the set_menu command without any pre-configured scope.","commands":{"allow":[],"deny":["set_menu"]}},"deny-set-show-menu-on-left-click":{"identifier":"deny-set-show-menu-on-left-click","description":"Denies the set_show_menu_on_left_click command without any pre-configured scope.","commands":{"allow":[],"deny":["set_show_menu_on_left_click"]}},"deny-set-temp-dir-path":{"identifier":"deny-set-temp-dir-path","description":"Denies the set_temp_dir_path command without any pre-configured scope.","commands":{"allow":[],"deny":["set_temp_dir_path"]}},"deny-set-title":{"identifier":"deny-set-title","description":"Denies the set_title command without any pre-configured scope.","commands":{"allow":[],"deny":["set_title"]}},"deny-set-tooltip":{"identifier":"deny-set-tooltip","description":"Denies the set_tooltip command without any pre-configured scope.","commands":{"allow":[],"deny":["set_tooltip"]}},"deny-set-visible":{"identifier":"deny-set-visible","description":"Denies the set_visible command without any pre-configured scope.","commands":{"allow":[],"deny":["set_visible"]}}},"permission_sets":{},"global_scope_schema":null},"core:webview":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin.","permissions":["allow-get-all-webviews","allow-webview-position","allow-webview-size","allow-internal-toggle-devtools"]},"permissions":{"allow-clear-all-browsing-data":{"identifier":"allow-clear-all-browsing-data","description":"Enables the clear_all_browsing_data command without any pre-configured scope.","commands":{"allow":["clear_all_browsing_data"],"deny":[]}},"allow-create-webview":{"identifier":"allow-create-webview","description":"Enables the create_webview command without any pre-configured scope.","commands":{"allow":["create_webview"],"deny":[]}},"allow-create-webview-window":{"identifier":"allow-create-webview-window","description":"Enables the create_webview_window command without any pre-configured scope.","commands":{"allow":["create_webview_window"],"deny":[]}},"allow-get-all-webviews":{"identifier":"allow-get-all-webviews","description":"Enables the get_all_webviews command without any pre-configured scope.","commands":{"allow":["get_all_webviews"],"deny":[]}},"allow-internal-toggle-devtools":{"identifier":"allow-internal-toggle-devtools","description":"Enables the internal_toggle_devtools command without any pre-configured scope.","commands":{"allow":["internal_toggle_devtools"],"deny":[]}},"allow-print":{"identifier":"allow-print","description":"Enables the print command without any pre-configured scope.","commands":{"allow":["print"],"deny":[]}},"allow-reparent":{"identifier":"allow-reparent","description":"Enables the reparent command without any pre-configured scope.","commands":{"allow":["reparent"],"deny":[]}},"allow-set-webview-auto-resize":{"identifier":"allow-set-webview-auto-resize","description":"Enables the set_webview_auto_resize command without any pre-configured scope.","commands":{"allow":["set_webview_auto_resize"],"deny":[]}},"allow-set-webview-background-color":{"identifier":"allow-set-webview-background-color","description":"Enables the set_webview_background_color command without any pre-configured scope.","commands":{"allow":["set_webview_background_color"],"deny":[]}},"allow-set-webview-focus":{"identifier":"allow-set-webview-focus","description":"Enables the set_webview_focus command without any pre-configured scope.","commands":{"allow":["set_webview_focus"],"deny":[]}},"allow-set-webview-position":{"identifier":"allow-set-webview-position","description":"Enables the set_webview_position command without any pre-configured scope.","commands":{"allow":["set_webview_position"],"deny":[]}},"allow-set-webview-size":{"identifier":"allow-set-webview-size","description":"Enables the set_webview_size command without any pre-configured scope.","commands":{"allow":["set_webview_size"],"deny":[]}},"allow-set-webview-zoom":{"identifier":"allow-set-webview-zoom","description":"Enables the set_webview_zoom command without any pre-configured scope.","commands":{"allow":["set_webview_zoom"],"deny":[]}},"allow-webview-close":{"identifier":"allow-webview-close","description":"Enables the webview_close command without any pre-configured scope.","commands":{"allow":["webview_close"],"deny":[]}},"allow-webview-hide":{"identifier":"allow-webview-hide","description":"Enables the webview_hide command without any pre-configured scope.","commands":{"allow":["webview_hide"],"deny":[]}},"allow-webview-position":{"identifier":"allow-webview-position","description":"Enables the webview_position command without any pre-configured scope.","commands":{"allow":["webview_position"],"deny":[]}},"allow-webview-show":{"identifier":"allow-webview-show","description":"Enables the webview_show command without any pre-configured scope.","commands":{"allow":["webview_show"],"deny":[]}},"allow-webview-size":{"identifier":"allow-webview-size","description":"Enables the webview_size command without any pre-configured scope.","commands":{"allow":["webview_size"],"deny":[]}},"deny-clear-all-browsing-data":{"identifier":"deny-clear-all-browsing-data","description":"Denies the clear_all_browsing_data command without any pre-configured scope.","commands":{"allow":[],"deny":["clear_all_browsing_data"]}},"deny-create-webview":{"identifier":"deny-create-webview","description":"Denies the create_webview command without any pre-configured scope.","commands":{"allow":[],"deny":["create_webview"]}},"deny-create-webview-window":{"identifier":"deny-create-webview-window","description":"Denies the create_webview_window command without any pre-configured scope.","commands":{"allow":[],"deny":["create_webview_window"]}},"deny-get-all-webviews":{"identifier":"deny-get-all-webviews","description":"Denies the get_all_webviews command without any pre-configured scope.","commands":{"allow":[],"deny":["get_all_webviews"]}},"deny-internal-toggle-devtools":{"identifier":"deny-internal-toggle-devtools","description":"Denies the internal_toggle_devtools command without any pre-configured scope.","commands":{"allow":[],"deny":["internal_toggle_devtools"]}},"deny-print":{"identifier":"deny-print","description":"Denies the print command without any pre-configured scope.","commands":{"allow":[],"deny":["print"]}},"deny-reparent":{"identifier":"deny-reparent","description":"Denies the reparent command without any pre-configured scope.","commands":{"allow":[],"deny":["reparent"]}},"deny-set-webview-auto-resize":{"identifier":"deny-set-webview-auto-resize","description":"Denies the set_webview_auto_resize command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_auto_resize"]}},"deny-set-webview-background-color":{"identifier":"deny-set-webview-background-color","description":"Denies the set_webview_background_color command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_background_color"]}},"deny-set-webview-focus":{"identifier":"deny-set-webview-focus","description":"Denies the set_webview_focus command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_focus"]}},"deny-set-webview-position":{"identifier":"deny-set-webview-position","description":"Denies the set_webview_position command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_position"]}},"deny-set-webview-size":{"identifier":"deny-set-webview-size","description":"Denies the set_webview_size command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_size"]}},"deny-set-webview-zoom":{"identifier":"deny-set-webview-zoom","description":"Denies the set_webview_zoom command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_zoom"]}},"deny-webview-close":{"identifier":"deny-webview-close","description":"Denies the webview_close command without any pre-configured scope.","commands":{"allow":[],"deny":["webview_close"]}},"deny-webview-hide":{"identifier":"deny-webview-hide","description":"Denies the webview_hide command without any pre-configured scope.","commands":{"allow":[],"deny":["webview_hide"]}},"deny-webview-position":{"identifier":"deny-webview-position","description":"Denies the webview_position command without any pre-configured scope.","commands":{"allow":[],"deny":["webview_position"]}},"deny-webview-show":{"identifier":"deny-webview-show","description":"Denies the webview_show command without any pre-configured scope.","commands":{"allow":[],"deny":["webview_show"]}},"deny-webview-size":{"identifier":"deny-webview-size","description":"Denies the webview_size command without any pre-configured scope.","commands":{"allow":[],"deny":["webview_size"]}}},"permission_sets":{},"global_scope_schema":null},"core:window":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin.","permissions":["allow-get-all-windows","allow-scale-factor","allow-inner-position","allow-outer-position","allow-inner-size","allow-outer-size","allow-is-fullscreen","allow-is-minimized","allow-is-maximized","allow-is-focused","allow-is-decorated","allow-is-resizable","allow-is-maximizable","allow-is-minimizable","allow-is-closable","allow-is-visible","allow-is-enabled","allow-title","allow-current-monitor","allow-primary-monitor","allow-monitor-from-point","allow-available-monitors","allow-cursor-position","allow-theme","allow-is-always-on-top","allow-activity-name","allow-scene-identifier","allow-internal-toggle-maximize"]},"permissions":{"allow-activity-name":{"identifier":"allow-activity-name","description":"Enables the activity_name command without any pre-configured scope.","commands":{"allow":["activity_name"],"deny":[]}},"allow-available-monitors":{"identifier":"allow-available-monitors","description":"Enables the available_monitors command without any pre-configured scope.","commands":{"allow":["available_monitors"],"deny":[]}},"allow-center":{"identifier":"allow-center","description":"Enables the center command without any pre-configured scope.","commands":{"allow":["center"],"deny":[]}},"allow-close":{"identifier":"allow-close","description":"Enables the close command without any pre-configured scope.","commands":{"allow":["close"],"deny":[]}},"allow-create":{"identifier":"allow-create","description":"Enables the create command without any pre-configured scope.","commands":{"allow":["create"],"deny":[]}},"allow-current-monitor":{"identifier":"allow-current-monitor","description":"Enables the current_monitor command without any pre-configured scope.","commands":{"allow":["current_monitor"],"deny":[]}},"allow-cursor-position":{"identifier":"allow-cursor-position","description":"Enables the cursor_position command without any pre-configured scope.","commands":{"allow":["cursor_position"],"deny":[]}},"allow-destroy":{"identifier":"allow-destroy","description":"Enables the destroy command without any pre-configured scope.","commands":{"allow":["destroy"],"deny":[]}},"allow-get-all-windows":{"identifier":"allow-get-all-windows","description":"Enables the get_all_windows command without any pre-configured scope.","commands":{"allow":["get_all_windows"],"deny":[]}},"allow-hide":{"identifier":"allow-hide","description":"Enables the hide command without any pre-configured scope.","commands":{"allow":["hide"],"deny":[]}},"allow-inner-position":{"identifier":"allow-inner-position","description":"Enables the inner_position command without any pre-configured scope.","commands":{"allow":["inner_position"],"deny":[]}},"allow-inner-size":{"identifier":"allow-inner-size","description":"Enables the inner_size command without any pre-configured scope.","commands":{"allow":["inner_size"],"deny":[]}},"allow-internal-toggle-maximize":{"identifier":"allow-internal-toggle-maximize","description":"Enables the internal_toggle_maximize command without any pre-configured scope.","commands":{"allow":["internal_toggle_maximize"],"deny":[]}},"allow-is-always-on-top":{"identifier":"allow-is-always-on-top","description":"Enables the is_always_on_top command without any pre-configured scope.","commands":{"allow":["is_always_on_top"],"deny":[]}},"allow-is-closable":{"identifier":"allow-is-closable","description":"Enables the is_closable command without any pre-configured scope.","commands":{"allow":["is_closable"],"deny":[]}},"allow-is-decorated":{"identifier":"allow-is-decorated","description":"Enables the is_decorated command without any pre-configured scope.","commands":{"allow":["is_decorated"],"deny":[]}},"allow-is-enabled":{"identifier":"allow-is-enabled","description":"Enables the is_enabled command without any pre-configured scope.","commands":{"allow":["is_enabled"],"deny":[]}},"allow-is-focused":{"identifier":"allow-is-focused","description":"Enables the is_focused command without any pre-configured scope.","commands":{"allow":["is_focused"],"deny":[]}},"allow-is-fullscreen":{"identifier":"allow-is-fullscreen","description":"Enables the is_fullscreen command without any pre-configured scope.","commands":{"allow":["is_fullscreen"],"deny":[]}},"allow-is-maximizable":{"identifier":"allow-is-maximizable","description":"Enables the is_maximizable command without any pre-configured scope.","commands":{"allow":["is_maximizable"],"deny":[]}},"allow-is-maximized":{"identifier":"allow-is-maximized","description":"Enables the is_maximized command without any pre-configured scope.","commands":{"allow":["is_maximized"],"deny":[]}},"allow-is-minimizable":{"identifier":"allow-is-minimizable","description":"Enables the is_minimizable command without any pre-configured scope.","commands":{"allow":["is_minimizable"],"deny":[]}},"allow-is-minimized":{"identifier":"allow-is-minimized","description":"Enables the is_minimized command without any pre-configured scope.","commands":{"allow":["is_minimized"],"deny":[]}},"allow-is-resizable":{"identifier":"allow-is-resizable","description":"Enables the is_resizable command without any pre-configured scope.","commands":{"allow":["is_resizable"],"deny":[]}},"allow-is-visible":{"identifier":"allow-is-visible","description":"Enables the is_visible command without any pre-configured scope.","commands":{"allow":["is_visible"],"deny":[]}},"allow-maximize":{"identifier":"allow-maximize","description":"Enables the maximize command without any pre-configured scope.","commands":{"allow":["maximize"],"deny":[]}},"allow-minimize":{"identifier":"allow-minimize","description":"Enables the minimize command without any pre-configured scope.","commands":{"allow":["minimize"],"deny":[]}},"allow-monitor-from-point":{"identifier":"allow-monitor-from-point","description":"Enables the monitor_from_point command without any pre-configured scope.","commands":{"allow":["monitor_from_point"],"deny":[]}},"allow-outer-position":{"identifier":"allow-outer-position","description":"Enables the outer_position command without any pre-configured scope.","commands":{"allow":["outer_position"],"deny":[]}},"allow-outer-size":{"identifier":"allow-outer-size","description":"Enables the outer_size command without any pre-configured scope.","commands":{"allow":["outer_size"],"deny":[]}},"allow-primary-monitor":{"identifier":"allow-primary-monitor","description":"Enables the primary_monitor command without any pre-configured scope.","commands":{"allow":["primary_monitor"],"deny":[]}},"allow-request-user-attention":{"identifier":"allow-request-user-attention","description":"Enables the request_user_attention command without any pre-configured scope.","commands":{"allow":["request_user_attention"],"deny":[]}},"allow-scale-factor":{"identifier":"allow-scale-factor","description":"Enables the scale_factor command without any pre-configured scope.","commands":{"allow":["scale_factor"],"deny":[]}},"allow-scene-identifier":{"identifier":"allow-scene-identifier","description":"Enables the scene_identifier command without any pre-configured scope.","commands":{"allow":["scene_identifier"],"deny":[]}},"allow-set-always-on-bottom":{"identifier":"allow-set-always-on-bottom","description":"Enables the set_always_on_bottom command without any pre-configured scope.","commands":{"allow":["set_always_on_bottom"],"deny":[]}},"allow-set-always-on-top":{"identifier":"allow-set-always-on-top","description":"Enables the set_always_on_top command without any pre-configured scope.","commands":{"allow":["set_always_on_top"],"deny":[]}},"allow-set-background-color":{"identifier":"allow-set-background-color","description":"Enables the set_background_color command without any pre-configured scope.","commands":{"allow":["set_background_color"],"deny":[]}},"allow-set-badge-count":{"identifier":"allow-set-badge-count","description":"Enables the set_badge_count command without any pre-configured scope.","commands":{"allow":["set_badge_count"],"deny":[]}},"allow-set-badge-label":{"identifier":"allow-set-badge-label","description":"Enables the set_badge_label command without any pre-configured scope.","commands":{"allow":["set_badge_label"],"deny":[]}},"allow-set-closable":{"identifier":"allow-set-closable","description":"Enables the set_closable command without any pre-configured scope.","commands":{"allow":["set_closable"],"deny":[]}},"allow-set-content-protected":{"identifier":"allow-set-content-protected","description":"Enables the set_content_protected command without any pre-configured scope.","commands":{"allow":["set_content_protected"],"deny":[]}},"allow-set-cursor-grab":{"identifier":"allow-set-cursor-grab","description":"Enables the set_cursor_grab command without any pre-configured scope.","commands":{"allow":["set_cursor_grab"],"deny":[]}},"allow-set-cursor-icon":{"identifier":"allow-set-cursor-icon","description":"Enables the set_cursor_icon command without any pre-configured scope.","commands":{"allow":["set_cursor_icon"],"deny":[]}},"allow-set-cursor-position":{"identifier":"allow-set-cursor-position","description":"Enables the set_cursor_position command without any pre-configured scope.","commands":{"allow":["set_cursor_position"],"deny":[]}},"allow-set-cursor-visible":{"identifier":"allow-set-cursor-visible","description":"Enables the set_cursor_visible command without any pre-configured scope.","commands":{"allow":["set_cursor_visible"],"deny":[]}},"allow-set-decorations":{"identifier":"allow-set-decorations","description":"Enables the set_decorations command without any pre-configured scope.","commands":{"allow":["set_decorations"],"deny":[]}},"allow-set-effects":{"identifier":"allow-set-effects","description":"Enables the set_effects command without any pre-configured scope.","commands":{"allow":["set_effects"],"deny":[]}},"allow-set-enabled":{"identifier":"allow-set-enabled","description":"Enables the set_enabled command without any pre-configured scope.","commands":{"allow":["set_enabled"],"deny":[]}},"allow-set-focus":{"identifier":"allow-set-focus","description":"Enables the set_focus command without any pre-configured scope.","commands":{"allow":["set_focus"],"deny":[]}},"allow-set-focusable":{"identifier":"allow-set-focusable","description":"Enables the set_focusable command without any pre-configured scope.","commands":{"allow":["set_focusable"],"deny":[]}},"allow-set-fullscreen":{"identifier":"allow-set-fullscreen","description":"Enables the set_fullscreen command without any pre-configured scope.","commands":{"allow":["set_fullscreen"],"deny":[]}},"allow-set-fullscreen-on-monitor":{"identifier":"allow-set-fullscreen-on-monitor","description":"Enables the set_fullscreen_on_monitor command without any pre-configured scope.","commands":{"allow":["set_fullscreen_on_monitor"],"deny":[]}},"allow-set-icon":{"identifier":"allow-set-icon","description":"Enables the set_icon command without any pre-configured scope.","commands":{"allow":["set_icon"],"deny":[]}},"allow-set-ignore-cursor-events":{"identifier":"allow-set-ignore-cursor-events","description":"Enables the set_ignore_cursor_events command without any pre-configured scope.","commands":{"allow":["set_ignore_cursor_events"],"deny":[]}},"allow-set-max-size":{"identifier":"allow-set-max-size","description":"Enables the set_max_size command without any pre-configured scope.","commands":{"allow":["set_max_size"],"deny":[]}},"allow-set-maximizable":{"identifier":"allow-set-maximizable","description":"Enables the set_maximizable command without any pre-configured scope.","commands":{"allow":["set_maximizable"],"deny":[]}},"allow-set-min-size":{"identifier":"allow-set-min-size","description":"Enables the set_min_size command without any pre-configured scope.","commands":{"allow":["set_min_size"],"deny":[]}},"allow-set-minimizable":{"identifier":"allow-set-minimizable","description":"Enables the set_minimizable command without any pre-configured scope.","commands":{"allow":["set_minimizable"],"deny":[]}},"allow-set-overlay-icon":{"identifier":"allow-set-overlay-icon","description":"Enables the set_overlay_icon command without any pre-configured scope.","commands":{"allow":["set_overlay_icon"],"deny":[]}},"allow-set-position":{"identifier":"allow-set-position","description":"Enables the set_position command without any pre-configured scope.","commands":{"allow":["set_position"],"deny":[]}},"allow-set-progress-bar":{"identifier":"allow-set-progress-bar","description":"Enables the set_progress_bar command without any pre-configured scope.","commands":{"allow":["set_progress_bar"],"deny":[]}},"allow-set-resizable":{"identifier":"allow-set-resizable","description":"Enables the set_resizable command without any pre-configured scope.","commands":{"allow":["set_resizable"],"deny":[]}},"allow-set-shadow":{"identifier":"allow-set-shadow","description":"Enables the set_shadow command without any pre-configured scope.","commands":{"allow":["set_shadow"],"deny":[]}},"allow-set-simple-fullscreen":{"identifier":"allow-set-simple-fullscreen","description":"Enables the set_simple_fullscreen command without any pre-configured scope.","commands":{"allow":["set_simple_fullscreen"],"deny":[]}},"allow-set-size":{"identifier":"allow-set-size","description":"Enables the set_size command without any pre-configured scope.","commands":{"allow":["set_size"],"deny":[]}},"allow-set-size-constraints":{"identifier":"allow-set-size-constraints","description":"Enables the set_size_constraints command without any pre-configured scope.","commands":{"allow":["set_size_constraints"],"deny":[]}},"allow-set-skip-taskbar":{"identifier":"allow-set-skip-taskbar","description":"Enables the set_skip_taskbar command without any pre-configured scope.","commands":{"allow":["set_skip_taskbar"],"deny":[]}},"allow-set-theme":{"identifier":"allow-set-theme","description":"Enables the set_theme command without any pre-configured scope.","commands":{"allow":["set_theme"],"deny":[]}},"allow-set-title":{"identifier":"allow-set-title","description":"Enables the set_title command without any pre-configured scope.","commands":{"allow":["set_title"],"deny":[]}},"allow-set-title-bar-style":{"identifier":"allow-set-title-bar-style","description":"Enables the set_title_bar_style command without any pre-configured scope.","commands":{"allow":["set_title_bar_style"],"deny":[]}},"allow-set-visible-on-all-workspaces":{"identifier":"allow-set-visible-on-all-workspaces","description":"Enables the set_visible_on_all_workspaces command without any pre-configured scope.","commands":{"allow":["set_visible_on_all_workspaces"],"deny":[]}},"allow-show":{"identifier":"allow-show","description":"Enables the show command without any pre-configured scope.","commands":{"allow":["show"],"deny":[]}},"allow-start-dragging":{"identifier":"allow-start-dragging","description":"Enables the start_dragging command without any pre-configured scope.","commands":{"allow":["start_dragging"],"deny":[]}},"allow-start-resize-dragging":{"identifier":"allow-start-resize-dragging","description":"Enables the start_resize_dragging command without any pre-configured scope.","commands":{"allow":["start_resize_dragging"],"deny":[]}},"allow-theme":{"identifier":"allow-theme","description":"Enables the theme command without any pre-configured scope.","commands":{"allow":["theme"],"deny":[]}},"allow-title":{"identifier":"allow-title","description":"Enables the title command without any pre-configured scope.","commands":{"allow":["title"],"deny":[]}},"allow-toggle-maximize":{"identifier":"allow-toggle-maximize","description":"Enables the toggle_maximize command without any pre-configured scope.","commands":{"allow":["toggle_maximize"],"deny":[]}},"allow-unmaximize":{"identifier":"allow-unmaximize","description":"Enables the unmaximize command without any pre-configured scope.","commands":{"allow":["unmaximize"],"deny":[]}},"allow-unminimize":{"identifier":"allow-unminimize","description":"Enables the unminimize command without any pre-configured scope.","commands":{"allow":["unminimize"],"deny":[]}},"deny-activity-name":{"identifier":"deny-activity-name","description":"Denies the activity_name command without any pre-configured scope.","commands":{"allow":[],"deny":["activity_name"]}},"deny-available-monitors":{"identifier":"deny-available-monitors","description":"Denies the available_monitors command without any pre-configured scope.","commands":{"allow":[],"deny":["available_monitors"]}},"deny-center":{"identifier":"deny-center","description":"Denies the center command without any pre-configured scope.","commands":{"allow":[],"deny":["center"]}},"deny-close":{"identifier":"deny-close","description":"Denies the close command without any pre-configured scope.","commands":{"allow":[],"deny":["close"]}},"deny-create":{"identifier":"deny-create","description":"Denies the create command without any pre-configured scope.","commands":{"allow":[],"deny":["create"]}},"deny-current-monitor":{"identifier":"deny-current-monitor","description":"Denies the current_monitor command without any pre-configured scope.","commands":{"allow":[],"deny":["current_monitor"]}},"deny-cursor-position":{"identifier":"deny-cursor-position","description":"Denies the cursor_position command without any pre-configured scope.","commands":{"allow":[],"deny":["cursor_position"]}},"deny-destroy":{"identifier":"deny-destroy","description":"Denies the destroy command without any pre-configured scope.","commands":{"allow":[],"deny":["destroy"]}},"deny-get-all-windows":{"identifier":"deny-get-all-windows","description":"Denies the get_all_windows command without any pre-configured scope.","commands":{"allow":[],"deny":["get_all_windows"]}},"deny-hide":{"identifier":"deny-hide","description":"Denies the hide command without any pre-configured scope.","commands":{"allow":[],"deny":["hide"]}},"deny-inner-position":{"identifier":"deny-inner-position","description":"Denies the inner_position command without any pre-configured scope.","commands":{"allow":[],"deny":["inner_position"]}},"deny-inner-size":{"identifier":"deny-inner-size","description":"Denies the inner_size command without any pre-configured scope.","commands":{"allow":[],"deny":["inner_size"]}},"deny-internal-toggle-maximize":{"identifier":"deny-internal-toggle-maximize","description":"Denies the internal_toggle_maximize command without any pre-configured scope.","commands":{"allow":[],"deny":["internal_toggle_maximize"]}},"deny-is-always-on-top":{"identifier":"deny-is-always-on-top","description":"Denies the is_always_on_top command without any pre-configured scope.","commands":{"allow":[],"deny":["is_always_on_top"]}},"deny-is-closable":{"identifier":"deny-is-closable","description":"Denies the is_closable command without any pre-configured scope.","commands":{"allow":[],"deny":["is_closable"]}},"deny-is-decorated":{"identifier":"deny-is-decorated","description":"Denies the is_decorated command without any pre-configured scope.","commands":{"allow":[],"deny":["is_decorated"]}},"deny-is-enabled":{"identifier":"deny-is-enabled","description":"Denies the is_enabled command without any pre-configured scope.","commands":{"allow":[],"deny":["is_enabled"]}},"deny-is-focused":{"identifier":"deny-is-focused","description":"Denies the is_focused command without any pre-configured scope.","commands":{"allow":[],"deny":["is_focused"]}},"deny-is-fullscreen":{"identifier":"deny-is-fullscreen","description":"Denies the is_fullscreen command without any pre-configured scope.","commands":{"allow":[],"deny":["is_fullscreen"]}},"deny-is-maximizable":{"identifier":"deny-is-maximizable","description":"Denies the is_maximizable command without any pre-configured scope.","commands":{"allow":[],"deny":["is_maximizable"]}},"deny-is-maximized":{"identifier":"deny-is-maximized","description":"Denies the is_maximized command without any pre-configured scope.","commands":{"allow":[],"deny":["is_maximized"]}},"deny-is-minimizable":{"identifier":"deny-is-minimizable","description":"Denies the is_minimizable command without any pre-configured scope.","commands":{"allow":[],"deny":["is_minimizable"]}},"deny-is-minimized":{"identifier":"deny-is-minimized","description":"Denies the is_minimized command without any pre-configured scope.","commands":{"allow":[],"deny":["is_minimized"]}},"deny-is-resizable":{"identifier":"deny-is-resizable","description":"Denies the is_resizable command without any pre-configured scope.","commands":{"allow":[],"deny":["is_resizable"]}},"deny-is-visible":{"identifier":"deny-is-visible","description":"Denies the is_visible command without any pre-configured scope.","commands":{"allow":[],"deny":["is_visible"]}},"deny-maximize":{"identifier":"deny-maximize","description":"Denies the maximize command without any pre-configured scope.","commands":{"allow":[],"deny":["maximize"]}},"deny-minimize":{"identifier":"deny-minimize","description":"Denies the minimize command without any pre-configured scope.","commands":{"allow":[],"deny":["minimize"]}},"deny-monitor-from-point":{"identifier":"deny-monitor-from-point","description":"Denies the monitor_from_point command without any pre-configured scope.","commands":{"allow":[],"deny":["monitor_from_point"]}},"deny-outer-position":{"identifier":"deny-outer-position","description":"Denies the outer_position command without any pre-configured scope.","commands":{"allow":[],"deny":["outer_position"]}},"deny-outer-size":{"identifier":"deny-outer-size","description":"Denies the outer_size command without any pre-configured scope.","commands":{"allow":[],"deny":["outer_size"]}},"deny-primary-monitor":{"identifier":"deny-primary-monitor","description":"Denies the primary_monitor command without any pre-configured scope.","commands":{"allow":[],"deny":["primary_monitor"]}},"deny-request-user-attention":{"identifier":"deny-request-user-attention","description":"Denies the request_user_attention command without any pre-configured scope.","commands":{"allow":[],"deny":["request_user_attention"]}},"deny-scale-factor":{"identifier":"deny-scale-factor","description":"Denies the scale_factor command without any pre-configured scope.","commands":{"allow":[],"deny":["scale_factor"]}},"deny-scene-identifier":{"identifier":"deny-scene-identifier","description":"Denies the scene_identifier command without any pre-configured scope.","commands":{"allow":[],"deny":["scene_identifier"]}},"deny-set-always-on-bottom":{"identifier":"deny-set-always-on-bottom","description":"Denies the set_always_on_bottom command without any pre-configured scope.","commands":{"allow":[],"deny":["set_always_on_bottom"]}},"deny-set-always-on-top":{"identifier":"deny-set-always-on-top","description":"Denies the set_always_on_top command without any pre-configured scope.","commands":{"allow":[],"deny":["set_always_on_top"]}},"deny-set-background-color":{"identifier":"deny-set-background-color","description":"Denies the set_background_color command without any pre-configured scope.","commands":{"allow":[],"deny":["set_background_color"]}},"deny-set-badge-count":{"identifier":"deny-set-badge-count","description":"Denies the set_badge_count command without any pre-configured scope.","commands":{"allow":[],"deny":["set_badge_count"]}},"deny-set-badge-label":{"identifier":"deny-set-badge-label","description":"Denies the set_badge_label command without any pre-configured scope.","commands":{"allow":[],"deny":["set_badge_label"]}},"deny-set-closable":{"identifier":"deny-set-closable","description":"Denies the set_closable command without any pre-configured scope.","commands":{"allow":[],"deny":["set_closable"]}},"deny-set-content-protected":{"identifier":"deny-set-content-protected","description":"Denies the set_content_protected command without any pre-configured scope.","commands":{"allow":[],"deny":["set_content_protected"]}},"deny-set-cursor-grab":{"identifier":"deny-set-cursor-grab","description":"Denies the set_cursor_grab command without any pre-configured scope.","commands":{"allow":[],"deny":["set_cursor_grab"]}},"deny-set-cursor-icon":{"identifier":"deny-set-cursor-icon","description":"Denies the set_cursor_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["set_cursor_icon"]}},"deny-set-cursor-position":{"identifier":"deny-set-cursor-position","description":"Denies the set_cursor_position command without any pre-configured scope.","commands":{"allow":[],"deny":["set_cursor_position"]}},"deny-set-cursor-visible":{"identifier":"deny-set-cursor-visible","description":"Denies the set_cursor_visible command without any pre-configured scope.","commands":{"allow":[],"deny":["set_cursor_visible"]}},"deny-set-decorations":{"identifier":"deny-set-decorations","description":"Denies the set_decorations command without any pre-configured scope.","commands":{"allow":[],"deny":["set_decorations"]}},"deny-set-effects":{"identifier":"deny-set-effects","description":"Denies the set_effects command without any pre-configured scope.","commands":{"allow":[],"deny":["set_effects"]}},"deny-set-enabled":{"identifier":"deny-set-enabled","description":"Denies the set_enabled command without any pre-configured scope.","commands":{"allow":[],"deny":["set_enabled"]}},"deny-set-focus":{"identifier":"deny-set-focus","description":"Denies the set_focus command without any pre-configured scope.","commands":{"allow":[],"deny":["set_focus"]}},"deny-set-focusable":{"identifier":"deny-set-focusable","description":"Denies the set_focusable command without any pre-configured scope.","commands":{"allow":[],"deny":["set_focusable"]}},"deny-set-fullscreen":{"identifier":"deny-set-fullscreen","description":"Denies the set_fullscreen command without any pre-configured scope.","commands":{"allow":[],"deny":["set_fullscreen"]}},"deny-set-fullscreen-on-monitor":{"identifier":"deny-set-fullscreen-on-monitor","description":"Denies the set_fullscreen_on_monitor command without any pre-configured scope.","commands":{"allow":[],"deny":["set_fullscreen_on_monitor"]}},"deny-set-icon":{"identifier":"deny-set-icon","description":"Denies the set_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["set_icon"]}},"deny-set-ignore-cursor-events":{"identifier":"deny-set-ignore-cursor-events","description":"Denies the set_ignore_cursor_events command without any pre-configured scope.","commands":{"allow":[],"deny":["set_ignore_cursor_events"]}},"deny-set-max-size":{"identifier":"deny-set-max-size","description":"Denies the set_max_size command without any pre-configured scope.","commands":{"allow":[],"deny":["set_max_size"]}},"deny-set-maximizable":{"identifier":"deny-set-maximizable","description":"Denies the set_maximizable command without any pre-configured scope.","commands":{"allow":[],"deny":["set_maximizable"]}},"deny-set-min-size":{"identifier":"deny-set-min-size","description":"Denies the set_min_size command without any pre-configured scope.","commands":{"allow":[],"deny":["set_min_size"]}},"deny-set-minimizable":{"identifier":"deny-set-minimizable","description":"Denies the set_minimizable command without any pre-configured scope.","commands":{"allow":[],"deny":["set_minimizable"]}},"deny-set-overlay-icon":{"identifier":"deny-set-overlay-icon","description":"Denies the set_overlay_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["set_overlay_icon"]}},"deny-set-position":{"identifier":"deny-set-position","description":"Denies the set_position command without any pre-configured scope.","commands":{"allow":[],"deny":["set_position"]}},"deny-set-progress-bar":{"identifier":"deny-set-progress-bar","description":"Denies the set_progress_bar command without any pre-configured scope.","commands":{"allow":[],"deny":["set_progress_bar"]}},"deny-set-resizable":{"identifier":"deny-set-resizable","description":"Denies the set_resizable command without any pre-configured scope.","commands":{"allow":[],"deny":["set_resizable"]}},"deny-set-shadow":{"identifier":"deny-set-shadow","description":"Denies the set_shadow command without any pre-configured scope.","commands":{"allow":[],"deny":["set_shadow"]}},"deny-set-simple-fullscreen":{"identifier":"deny-set-simple-fullscreen","description":"Denies the set_simple_fullscreen command without any pre-configured scope.","commands":{"allow":[],"deny":["set_simple_fullscreen"]}},"deny-set-size":{"identifier":"deny-set-size","description":"Denies the set_size command without any pre-configured scope.","commands":{"allow":[],"deny":["set_size"]}},"deny-set-size-constraints":{"identifier":"deny-set-size-constraints","description":"Denies the set_size_constraints command without any pre-configured scope.","commands":{"allow":[],"deny":["set_size_constraints"]}},"deny-set-skip-taskbar":{"identifier":"deny-set-skip-taskbar","description":"Denies the set_skip_taskbar command without any pre-configured scope.","commands":{"allow":[],"deny":["set_skip_taskbar"]}},"deny-set-theme":{"identifier":"deny-set-theme","description":"Denies the set_theme command without any pre-configured scope.","commands":{"allow":[],"deny":["set_theme"]}},"deny-set-title":{"identifier":"deny-set-title","description":"Denies the set_title command without any pre-configured scope.","commands":{"allow":[],"deny":["set_title"]}},"deny-set-title-bar-style":{"identifier":"deny-set-title-bar-style","description":"Denies the set_title_bar_style command without any pre-configured scope.","commands":{"allow":[],"deny":["set_title_bar_style"]}},"deny-set-visible-on-all-workspaces":{"identifier":"deny-set-visible-on-all-workspaces","description":"Denies the set_visible_on_all_workspaces command without any pre-configured scope.","commands":{"allow":[],"deny":["set_visible_on_all_workspaces"]}},"deny-show":{"identifier":"deny-show","description":"Denies the show command without any pre-configured scope.","commands":{"allow":[],"deny":["show"]}},"deny-start-dragging":{"identifier":"deny-start-dragging","description":"Denies the start_dragging command without any pre-configured scope.","commands":{"allow":[],"deny":["start_dragging"]}},"deny-start-resize-dragging":{"identifier":"deny-start-resize-dragging","description":"Denies the start_resize_dragging command without any pre-configured scope.","commands":{"allow":[],"deny":["start_resize_dragging"]}},"deny-theme":{"identifier":"deny-theme","description":"Denies the theme command without any pre-configured scope.","commands":{"allow":[],"deny":["theme"]}},"deny-title":{"identifier":"deny-title","description":"Denies the title command without any pre-configured scope.","commands":{"allow":[],"deny":["title"]}},"deny-toggle-maximize":{"identifier":"deny-toggle-maximize","description":"Denies the toggle_maximize command without any pre-configured scope.","commands":{"allow":[],"deny":["toggle_maximize"]}},"deny-unmaximize":{"identifier":"deny-unmaximize","description":"Denies the unmaximize command without any pre-configured scope.","commands":{"allow":[],"deny":["unmaximize"]}},"deny-unminimize":{"identifier":"deny-unminimize","description":"Denies the unminimize command without any pre-configured scope.","commands":{"allow":[],"deny":["unminimize"]}}},"permission_sets":{},"global_scope_schema":null},"dialog":{"default_permission":{"identifier":"default","description":"This permission set configures the types of dialogs\navailable from the dialog plugin.\n\n#### Granted Permissions\n\nAll dialog types are enabled.\n\n\n","permissions":["allow-message","allow-save","allow-open"]},"permissions":{"allow-ask":{"identifier":"allow-ask","description":"Enables the ask command without any pre-configured scope. (**DEPRECATED**: This is now an alias to `allow-message` and will be removed in v3)","commands":{"allow":["message"],"deny":[]}},"allow-confirm":{"identifier":"allow-confirm","description":"Enables the confirm command without any pre-configured scope. (**DEPRECATED**: This is now an alias to `allow-message` and will be removed in v3)","commands":{"allow":["message"],"deny":[]}},"allow-message":{"identifier":"allow-message","description":"Enables the message command without any pre-configured scope.","commands":{"allow":["message"],"deny":[]}},"allow-open":{"identifier":"allow-open","description":"Enables the open command without any pre-configured scope.","commands":{"allow":["open"],"deny":[]}},"allow-save":{"identifier":"allow-save","description":"Enables the save command without any pre-configured scope.","commands":{"allow":["save"],"deny":[]}},"deny-ask":{"identifier":"deny-ask","description":"Denies the ask command without any pre-configured scope. (**DEPRECATED**: This is now an alias to `deny-message` and will be removed in v3)","commands":{"allow":[],"deny":["message"]}},"deny-confirm":{"identifier":"deny-confirm","description":"Denies the confirm command without any pre-configured scope. (**DEPRECATED**: This is now an alias to `deny-message` and will be removed in v3)","commands":{"allow":[],"deny":["message"]}},"deny-message":{"identifier":"deny-message","description":"Denies the message command without any pre-configured scope.","commands":{"allow":[],"deny":["message"]}},"deny-open":{"identifier":"deny-open","description":"Denies the open command without any pre-configured scope.","commands":{"allow":[],"deny":["open"]}},"deny-save":{"identifier":"deny-save","description":"Denies the save command without any pre-configured scope.","commands":{"allow":[],"deny":["save"]}}},"permission_sets":{},"global_scope_schema":null}} \ No newline at end of file diff --git a/crates/app/gen/schemas/capabilities.json b/crates/app/gen/schemas/capabilities.json index 1204659ad..5f94b7ef2 100644 --- a/crates/app/gen/schemas/capabilities.json +++ b/crates/app/gen/schemas/capabilities.json @@ -1 +1 @@ -{"default":{"identifier":"default","description":"Default desktop capabilities","local":true,"windows":["main"],"permissions":["core:default","core:event:default","core:window:default","core:window:allow-minimize","core:window:allow-toggle-maximize","core:window:allow-close","core:window:allow-start-dragging","core:window:allow-is-maximized"]}} \ No newline at end of file +{"default":{"identifier":"default","description":"Default desktop capabilities","local":true,"windows":["main"],"permissions":["core:default","core:event:default","core:window:default","core:window:allow-minimize","core:window:allow-toggle-maximize","core:window:allow-close","core:window:allow-start-dragging","core:window:allow-is-maximized","dialog:allow-open"]}} \ No newline at end of file diff --git a/crates/app/gen/schemas/desktop-schema.json b/crates/app/gen/schemas/desktop-schema.json index 1ef122518..2471a5c9f 100644 --- a/crates/app/gen/schemas/desktop-schema.json +++ b/crates/app/gen/schemas/desktop-schema.json @@ -2215,6 +2215,72 @@ "type": "string", "const": "core:window:deny-unminimize", "markdownDescription": "Denies the unminimize command without any pre-configured scope." + }, + { + "description": "This permission set configures the types of dialogs\navailable from the dialog plugin.\n\n#### Granted Permissions\n\nAll dialog types are enabled.\n\n\n\n#### This default permission set includes:\n\n- `allow-message`\n- `allow-save`\n- `allow-open`", + "type": "string", + "const": "dialog:default", + "markdownDescription": "This permission set configures the types of dialogs\navailable from the dialog plugin.\n\n#### Granted Permissions\n\nAll dialog types are enabled.\n\n\n\n#### This default permission set includes:\n\n- `allow-message`\n- `allow-save`\n- `allow-open`" + }, + { + "description": "Enables the ask command without any pre-configured scope. (**DEPRECATED**: This is now an alias to `allow-message` and will be removed in v3)", + "type": "string", + "const": "dialog:allow-ask", + "markdownDescription": "Enables the ask command without any pre-configured scope. (**DEPRECATED**: This is now an alias to `allow-message` and will be removed in v3)" + }, + { + "description": "Enables the confirm command without any pre-configured scope. (**DEPRECATED**: This is now an alias to `allow-message` and will be removed in v3)", + "type": "string", + "const": "dialog:allow-confirm", + "markdownDescription": "Enables the confirm command without any pre-configured scope. (**DEPRECATED**: This is now an alias to `allow-message` and will be removed in v3)" + }, + { + "description": "Enables the message command without any pre-configured scope.", + "type": "string", + "const": "dialog:allow-message", + "markdownDescription": "Enables the message command without any pre-configured scope." + }, + { + "description": "Enables the open command without any pre-configured scope.", + "type": "string", + "const": "dialog:allow-open", + "markdownDescription": "Enables the open command without any pre-configured scope." + }, + { + "description": "Enables the save command without any pre-configured scope.", + "type": "string", + "const": "dialog:allow-save", + "markdownDescription": "Enables the save command without any pre-configured scope." + }, + { + "description": "Denies the ask command without any pre-configured scope. (**DEPRECATED**: This is now an alias to `deny-message` and will be removed in v3)", + "type": "string", + "const": "dialog:deny-ask", + "markdownDescription": "Denies the ask command without any pre-configured scope. (**DEPRECATED**: This is now an alias to `deny-message` and will be removed in v3)" + }, + { + "description": "Denies the confirm command without any pre-configured scope. (**DEPRECATED**: This is now an alias to `deny-message` and will be removed in v3)", + "type": "string", + "const": "dialog:deny-confirm", + "markdownDescription": "Denies the confirm command without any pre-configured scope. (**DEPRECATED**: This is now an alias to `deny-message` and will be removed in v3)" + }, + { + "description": "Denies the message command without any pre-configured scope.", + "type": "string", + "const": "dialog:deny-message", + "markdownDescription": "Denies the message command without any pre-configured scope." + }, + { + "description": "Denies the open command without any pre-configured scope.", + "type": "string", + "const": "dialog:deny-open", + "markdownDescription": "Denies the open command without any pre-configured scope." + }, + { + "description": "Denies the save command without any pre-configured scope.", + "type": "string", + "const": "dialog:deny-save", + "markdownDescription": "Denies the save command without any pre-configured scope." } ] }, diff --git a/crates/app/gen/schemas/linux-schema.json b/crates/app/gen/schemas/linux-schema.json index 1ef122518..2471a5c9f 100644 --- a/crates/app/gen/schemas/linux-schema.json +++ b/crates/app/gen/schemas/linux-schema.json @@ -2215,6 +2215,72 @@ "type": "string", "const": "core:window:deny-unminimize", "markdownDescription": "Denies the unminimize command without any pre-configured scope." + }, + { + "description": "This permission set configures the types of dialogs\navailable from the dialog plugin.\n\n#### Granted Permissions\n\nAll dialog types are enabled.\n\n\n\n#### This default permission set includes:\n\n- `allow-message`\n- `allow-save`\n- `allow-open`", + "type": "string", + "const": "dialog:default", + "markdownDescription": "This permission set configures the types of dialogs\navailable from the dialog plugin.\n\n#### Granted Permissions\n\nAll dialog types are enabled.\n\n\n\n#### This default permission set includes:\n\n- `allow-message`\n- `allow-save`\n- `allow-open`" + }, + { + "description": "Enables the ask command without any pre-configured scope. (**DEPRECATED**: This is now an alias to `allow-message` and will be removed in v3)", + "type": "string", + "const": "dialog:allow-ask", + "markdownDescription": "Enables the ask command without any pre-configured scope. (**DEPRECATED**: This is now an alias to `allow-message` and will be removed in v3)" + }, + { + "description": "Enables the confirm command without any pre-configured scope. (**DEPRECATED**: This is now an alias to `allow-message` and will be removed in v3)", + "type": "string", + "const": "dialog:allow-confirm", + "markdownDescription": "Enables the confirm command without any pre-configured scope. (**DEPRECATED**: This is now an alias to `allow-message` and will be removed in v3)" + }, + { + "description": "Enables the message command without any pre-configured scope.", + "type": "string", + "const": "dialog:allow-message", + "markdownDescription": "Enables the message command without any pre-configured scope." + }, + { + "description": "Enables the open command without any pre-configured scope.", + "type": "string", + "const": "dialog:allow-open", + "markdownDescription": "Enables the open command without any pre-configured scope." + }, + { + "description": "Enables the save command without any pre-configured scope.", + "type": "string", + "const": "dialog:allow-save", + "markdownDescription": "Enables the save command without any pre-configured scope." + }, + { + "description": "Denies the ask command without any pre-configured scope. (**DEPRECATED**: This is now an alias to `deny-message` and will be removed in v3)", + "type": "string", + "const": "dialog:deny-ask", + "markdownDescription": "Denies the ask command without any pre-configured scope. (**DEPRECATED**: This is now an alias to `deny-message` and will be removed in v3)" + }, + { + "description": "Denies the confirm command without any pre-configured scope. (**DEPRECATED**: This is now an alias to `deny-message` and will be removed in v3)", + "type": "string", + "const": "dialog:deny-confirm", + "markdownDescription": "Denies the confirm command without any pre-configured scope. (**DEPRECATED**: This is now an alias to `deny-message` and will be removed in v3)" + }, + { + "description": "Denies the message command without any pre-configured scope.", + "type": "string", + "const": "dialog:deny-message", + "markdownDescription": "Denies the message command without any pre-configured scope." + }, + { + "description": "Denies the open command without any pre-configured scope.", + "type": "string", + "const": "dialog:deny-open", + "markdownDescription": "Denies the open command without any pre-configured scope." + }, + { + "description": "Denies the save command without any pre-configured scope.", + "type": "string", + "const": "dialog:deny-save", + "markdownDescription": "Denies the save command without any pre-configured scope." } ] }, diff --git a/crates/app/src/commands.rs b/crates/app/src/commands.rs index 8b61d184a..29b22f172 100644 --- a/crates/app/src/commands.rs +++ b/crates/app/src/commands.rs @@ -1,4 +1,6 @@ +use std::collections::BTreeSet; use std::sync::Arc; +use std::sync::atomic::{AtomicU64, Ordering}; use crate::engine::Engine; use gamenode_core::{AppPreferencePatch, Locale, Snapshot, WindowGeometry}; @@ -302,7 +304,7 @@ pub async fn dispatch_auth( engine: tauri::State<'_, Engine>, input: gamenode_core::Input, ) -> Result<(), String> { - engine.dispatch(input); + engine.dispatch_on_worker(input).await; Ok(()) } @@ -418,87 +420,1572 @@ pub async fn open_entry( Ok(()) } +/// Approves the currently displayed detected target after worker-side host validation. +#[tauri::command] +pub async fn review_detected_target( + engine: tauri::State<'_, Engine>, + entry_key: String, + expected_revision: u64, +) -> Result<(), String> { + engine + .review_detected_target(entry_key, expected_revision) + .await +} + +/// Lists the active profile's custom recipes for the selected matched game. +#[tauri::command] +pub async fn launch_recipe_choices( + engine: tauri::State<'_, Engine>, + entry_key: String, +) -> Result { + engine.launch_recipe_choices(entry_key).await +} + +/// Makes one authenticated plugin recipe the explicit launch choice for this library entry. +#[tauri::command] +pub async fn select_launch_recipe( + engine: tauri::State<'_, Engine>, + entry_key: String, + plugin_id: String, + publisher_fingerprint: String, + recipe_id: String, + recipe_revision: u64, + expected_target_revision: u64, +) -> Result<(), String> { + engine + .select_launch_recipe( + entry_key, + plugin_id, + publisher_fingerprint, + recipe_id, + recipe_revision, + expected_target_revision, + ) + .await +} + +/// Explicitly returns this library entry to its detected default launch target. +#[tauri::command] +pub async fn use_detected_default( + engine: tauri::State<'_, Engine>, + entry_key: String, + expected_target_revision: u64, +) -> Result<(), String> { + engine + .use_detected_default(entry_key, expected_target_revision) + .await +} + +/// Opens a native picker to repair a missing detected executable. Selecting a file is explicit +/// approval for the replacement target; validation and persistence run on a worker. +#[tauri::command] +pub async fn repair_detected_target( + engine: tauri::State<'_, Engine>, + entry_key: String, + expected_revision: u64, +) -> Result<(), String> { + engine + .repair_detected_target(entry_key, expected_revision) + .await +} + #[tauri::command] pub async fn launch_selected( engine: tauri::State<'_, Engine>, - kind: gamenode_core::library::LaunchKind, + kind: gamenode_core::library::LaunchKind, +) -> Result<(), String> { + let snapshot = engine.snapshot(); + if let Some(library) = &snapshot.library + && library.selected.len() == 1 + { + let key = library.selected[0].clone(); + engine.open_entry(key, kind); + } + Ok(()) +} + +#[tauri::command] +pub async fn start_extension_action( + engine: tauri::State<'_, Engine>, + entry_key: String, + plugin_id: String, + operation: String, +) -> Result<(), String> { + let operation = match operation.as_str() { + "play" => crate::plugin_host::intents::Operation::Launch, + "install" => crate::plugin_host::intents::Operation::Install, + _ => return Err("unsupported extension action".to_owned()), + }; + engine + .start_extension_action(&entry_key, &plugin_id, operation) + .await + .map_err(|status| status.message().to_owned()) +} + +#[tauri::command] +pub async fn available_plugin_extensions( + engine: tauri::State<'_, Engine>, + operation: String, +) -> Result, String> { + let operation = match operation.as_str() { + "play" => crate::plugin_host::intents::Operation::Launch, + "install" => crate::plugin_host::intents::Operation::Install, + _ => return Err("unsupported extension action".to_owned()), + }; + engine + .available_extensions(operation) + .await + .map_err(|status| status.message().to_owned()) +} + +#[tauri::command] +pub async fn dismiss_launch(engine: tauri::State<'_, Engine>) -> Result<(), String> { + engine.dismiss_launch(); + Ok(()) +} + +#[tauri::command] +pub async fn rescan_library(engine: tauri::State<'_, Engine>) -> Result<(), String> { + engine.rescan(); + Ok(()) +} + +/// Opens a GameNode website page in the default browser (D14). The browser work runs on a +/// blocking worker; a typed error keeps the UI copy localized. +#[tauri::command] +pub async fn open_gamenode_page( + engine: tauri::State<'_, Engine>, + page: crate::engine::GameNodePage, +) -> Result<(), crate::engine::GameNodePageError> { + engine.open_gamenode_page(page).await +} + +/// Opens one of the fixed GameNode website links (About footer, Account › Abrir perfil). The UI +/// passes an enum, never a URL; `profile` needs a verified session. +#[tauri::command] +pub async fn open_gamenode_link( + engine: tauri::State<'_, Engine>, + kind: crate::engine::GameNodeLink, +) -> Result<(), crate::engine::GameNodePageError> { + engine.open_gamenode_link(kind).await +} + +/// Cached cover file names for the signed-out screen's mural; empty when the cache has none. +#[tauri::command] +pub async fn sign_in_cover_wall(engine: tauri::State<'_, Engine>) -> Result, String> { + Ok(engine.inner().clone().sign_in_cover_wall().await) +} + +#[tauri::command] +pub async fn remove_entry( + engine: tauri::State<'_, Engine>, + key: String, + allow_rediscovery: bool, +) -> Result<(), String> { + engine.remove_entry(key, allow_rediscovery); + Ok(()) +} + +// --------------------------------------------------------------------------- +// Store Account Commands +// --------------------------------------------------------------------------- + +/// Returns trusted packaged plugin metadata. Executable inspection runs off the async worker. +#[tauri::command] +pub async fn plugin_inventory( + engine: tauri::State<'_, Engine>, + updates: tauri::State<'_, crate::plugin_host::updates::PluginUpdateService>, +) -> Result, String> { + let engine = engine.inner().clone(); + let (mut inventory, runtime_inventory) = tokio::task::spawn_blocking(move || { + let bundled = crate::plugin_host::inventory(|id| { + let (_, connected) = engine.provider_health(id); + (engine.provider_availability(id), connected) + }); + (bundled, engine.managed_plugin_inventory()) + }) + .await + .map_err(|_| "plugin inventory worker failed".to_owned())?; + let mut managed = updates.managed_inventory().await?; + for plugin in &mut managed { + if let Some(runtime) = runtime_inventory + .iter() + .find(|runtime| runtime.plugin_id == plugin.plugin_id) + { + plugin.status.clone_from(&runtime.status); + plugin.session.clone_from(&runtime.session); + if runtime.enabled.is_some() { + plugin.enabled = runtime.enabled; + } + if runtime.runtime_available.is_some() { + plugin.runtime_available = runtime.runtime_available; + } + } + } + inventory.extend(managed); + inventory.sort_by(|left, right| left.plugin_id.cmp(&right.plugin_id)); + Ok(inventory) +} + +#[tauri::command] +pub async fn plugin_import_review( + updates: tauri::State<'_, crate::plugin_host::updates::PluginUpdateService>, + archive_path: String, +) -> Result { + updates.import_review(archive_path.into()).await +} + +#[tauri::command] +pub async fn plugin_import_confirm_publisher( + updates: tauri::State<'_, crate::plugin_host::updates::PluginUpdateService>, + token: String, + confirmed_fingerprint: String, +) -> Result { + updates + .import_confirm_publisher(&token, &confirmed_fingerprint) + .await +} + +#[tauri::command] +pub async fn plugin_import_install( + updates: tauri::State<'_, crate::plugin_host::updates::PluginUpdateService>, + engine: tauri::State<'_, Engine>, + token: String, + native_code_consent: bool, + denied_permission_ids: Vec, +) -> Result { + let outcome = updates + .import_install(&token, native_code_consent, &denied_permission_ids) + .await?; + register_installed_library_provider(&updates, &engine, &outcome.plugin_id).await; + Ok(outcome) +} + +/// Makes a just-accepted provider package part of the running library without a restart. +/// Registry and package reads stay on blocking workers; only the provider-list update and the +/// scan request touch engine state. +async fn register_installed_library_provider( + updates: &crate::plugin_host::updates::PluginUpdateService, + engine: &Engine, + plugin_id: &str, +) { + match updates.library_provider(plugin_id).await { + Ok(Some(provider)) => engine.add_library_provider(provider), + Ok(None) => {} + Err(error) => { + tracing::warn!(%error, %plugin_id, "could not add an imported provider to the library"); + } + } +} + +#[tauri::command] +pub async fn plugin_import_license_text( + updates: tauri::State<'_, crate::plugin_host::updates::PluginUpdateService>, + token: String, + file: String, +) -> Result { + updates.import_license_text(&token, &file).await +} + +#[tauri::command] +pub async fn plugin_bundle_import_review( + updates: tauri::State<'_, crate::plugin_host::updates::PluginUpdateService>, + archive_path: String, +) -> Result { + updates.bundle_import_review(archive_path.into()).await +} + +#[tauri::command] +pub async fn plugin_bundle_import_confirm_publisher( + updates: tauri::State<'_, crate::plugin_host::updates::PluginUpdateService>, + token: String, + confirmed_fingerprint: String, +) -> Result { + updates + .bundle_import_confirm_publisher(&token, &confirmed_fingerprint) + .await +} + +#[tauri::command] +pub async fn plugin_bundle_import_install( + updates: tauri::State<'_, crate::plugin_host::updates::PluginUpdateService>, + engine: tauri::State<'_, Engine>, + token: String, + native_code_consent: bool, + component_denied_permissions: Vec< + crate::plugin_host::updates::BundleComponentDeniedPermissions, + >, +) -> Result { + let outcome = updates + .bundle_import_install(&token, native_code_consent, &component_denied_permissions) + .await?; + for component in &outcome.components { + if component.kind == "provider" && component.active { + register_installed_library_provider(&updates, &engine, &component.plugin_id).await; + } + } + Ok(outcome) +} + +#[tauri::command] +pub async fn plugin_bundle_permissions_replace( + updates: tauri::State<'_, crate::plugin_host::updates::PluginUpdateService>, + submissions: Vec, +) -> Result { + updates.apply_bundle_permissions(submissions).await +} + +#[tauri::command] +pub async fn plugin_bundle_update_check( + updates: tauri::State<'_, crate::plugin_host::updates::PluginUpdateService>, +) -> Result, String> { + updates.check_bundle_updates().await +} + +#[tauri::command] +pub async fn plugin_bundle_update_available( + updates: tauri::State<'_, crate::plugin_host::updates::PluginUpdateService>, +) -> Result, String> { + Ok(updates.bundle_update_available()) +} + +#[tauri::command] +pub async fn plugin_bundle_update_review( + updates: tauri::State<'_, crate::plugin_host::updates::PluginUpdateService>, + bundle_id: String, + version: String, +) -> Result { + updates.review_bundle_update(&bundle_id, &version).await +} + +#[tauri::command] +pub async fn plugin_bundle_update_approve( + updates: tauri::State<'_, crate::plugin_host::updates::PluginUpdateService>, + engine: tauri::State<'_, Engine>, + bundle_id: String, + version: String, +) -> Result { + let outcome = updates.approve_bundle_update(&bundle_id, &version).await?; + // The activated component may expose different records; refresh them in the same session. + engine.rescan(); + Ok(outcome) +} + +#[tauri::command] +pub async fn plugin_bundle_update_decline( + updates: tauri::State<'_, crate::plugin_host::updates::PluginUpdateService>, + bundle_id: String, +) -> Result<(), String> { + updates.decline_bundle_update(&bundle_id).await; + Ok(()) +} + +#[tauri::command] +pub async fn plugin_bundle_rollback_available( + updates: tauri::State<'_, crate::plugin_host::updates::PluginUpdateService>, +) -> Result, String> { + updates.available_bundle_rollbacks().await +} + +#[tauri::command] +pub async fn plugin_bundle_rollback_review( + updates: tauri::State<'_, crate::plugin_host::updates::PluginUpdateService>, + bundle_id: String, + version: String, +) -> Result { + updates.review_bundle_rollback(&bundle_id, &version).await +} + +#[tauri::command] +pub async fn plugin_bundle_rollback_approve( + updates: tauri::State<'_, crate::plugin_host::updates::PluginUpdateService>, + engine: tauri::State<'_, Engine>, + bundle_id: String, + version: String, + confirmed: bool, +) -> Result { + let outcome = updates + .approve_bundle_rollback(&bundle_id, &version, confirmed) + .await?; + engine.rescan(); + Ok(outcome) +} + +#[tauri::command] +pub async fn plugin_permission_snapshot( + updates: tauri::State<'_, crate::plugin_host::updates::PluginUpdateService>, + plugin_id: String, + expected_account_id: String, +) -> Result { + let snapshot = updates + .permission_snapshot(plugin_id) + .await + .map_err(|error| error.message().to_owned())?; + if snapshot.profile_id + != crate::plugin_host::profile::profile_id_for_account(&expected_account_id) + { + return Err("plugin profile changed while reading permissions".into()); + } + Ok(snapshot) +} + +#[tauri::command] +pub async fn plugin_permissions_replace( + updates: tauri::State<'_, crate::plugin_host::updates::PluginUpdateService>, + plugin_id: String, + expected_profile_id: String, + expected_publisher_fingerprint: String, + expected_revision: u64, + decisions: Vec, +) -> Result { + updates + .replace_permissions( + plugin_id, + expected_profile_id, + expected_publisher_fingerprint, + expected_revision, + decisions, + ) + .await + .map_err(|error| error.message().to_owned()) +} + +#[derive(Clone, Debug, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SharedDataCatalogRecord { + pub source_plugin_id: String, + pub source_publisher_fingerprint: String, + pub dataset_id: String, + pub class: String, + pub category: Option, + pub record_id: String, + pub fields: Vec, +} + +#[derive(Clone, Debug, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SharedDataSourcePolicy { + pub source_plugin_id: String, + pub source_publisher_fingerprint: String, + pub dataset_id: String, + pub class: String, + pub fields: Vec, + pub history: bool, + pub live: bool, +} + +#[derive(Clone, Debug, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PluginSharedDataSnapshot { + pub plugin_id: String, + pub publisher_fingerprint: String, + pub profile_id: String, + pub policy_revision: u64, + pub common_categories: Vec, + pub selected_record_ids: Vec, + pub catalog: Vec, + pub source_policies: Vec, +} + +#[derive(Clone, Debug, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct SharedDataSourcePolicyDecision { + pub source_plugin_id: String, + pub source_publisher_fingerprint: String, + pub dataset_id: String, + pub class: String, + pub fields: BTreeSet, + pub history: bool, + pub live: bool, +} + +#[derive(Clone, Debug, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct PluginSharedDataPolicyUpdate { + pub profile_id: String, + pub expected_publisher_fingerprint: String, + pub expected_revision: u64, + pub common_categories: Vec, + pub selected_record_ids: Vec, + pub source_policies: Vec, +} + +fn common_data_category_name( + category: gamenode_plugin_protocol::proto::CommonDataCategory, +) -> String { + use gamenode_plugin_protocol::proto::CommonDataCategory as C; + match category { + C::GamePaths => "gamePaths", + C::GamePerformanceHistory => "gamePerformanceHistory", + C::RuntimeCatalog => "runtimeCatalog", + C::ContentAvailability => "contentAvailability", + C::LibraryRoots => "libraryRoots", + C::SaveProfiles => "saveProfiles", + C::Unspecified => "unspecified", + } + .to_owned() +} + +fn common_data_category( + value: &str, +) -> Result { + use gamenode_plugin_protocol::proto::CommonDataCategory as C; + match value { + "gamePaths" => Ok(C::GamePaths), + "gamePerformanceHistory" => Ok(C::GamePerformanceHistory), + "runtimeCatalog" => Ok(C::RuntimeCatalog), + "contentAvailability" => Ok(C::ContentAvailability), + "libraryRoots" => Ok(C::LibraryRoots), + "saveProfiles" => Ok(C::SaveProfiles), + _ => Err("unknown shared-data category".into()), + } +} + +fn sharing_class_name(class: crate::plugin_host::sharing_policy::SharingClass) -> String { + match class { + crate::plugin_host::sharing_policy::SharingClass::Common => "common", + crate::plugin_host::sharing_policy::SharingClass::Sensitive => "sensitive", + crate::plugin_host::sharing_policy::SharingClass::Custom => "custom", + } + .to_owned() +} + +fn sharing_class(value: &str) -> Result { + use crate::plugin_host::sharing_policy::SharingClass as C; + match value { + "sensitive" => Ok(C::Sensitive), + "custom" => Ok(C::Custom), + _ => Err("only sensitive and custom datasets use source-recipient review".into()), + } +} + +fn unix_timestamp() -> Result { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_err(|_| "system clock is before Unix epoch".to_owned())? + .as_secs() + .try_into() + .map_err(|_| "system time is outside supported range".to_owned()) +} + +#[tauri::command] +pub async fn plugin_shared_data_snapshot( + lifecycle: tauri::State<'_, Arc>, + policies: tauri::State<'_, Arc>, + broker: tauri::State<'_, Arc>, + plugin_id: String, + expected_profile_id: String, +) -> Result { + let identity = lifecycle + .sharing_identity(plugin_id, &expected_profile_id) + .await + .map_err(|status| status.message().to_owned())?; + let policy_snapshot = read_shared_data_policy(policies.inner().clone(), &identity).await?; + let catalog = shared_data_catalog(broker.inner().clone(), &identity.profile_id).await?; + Ok(plugin_shared_data_snapshot_for( + identity, + policy_snapshot, + catalog, + )) +} + +async fn read_shared_data_policy( + policies: Arc, + identity: &crate::plugin_host::grants::PluginIdentity, +) -> Result { + let identity = identity.clone(); + tokio::task::spawn_blocking(move || policies.recipient_snapshot(&identity)) + .await + .map_err(|_| "shared-data permission worker failed".to_owned())? + .map_err(|error| error.to_string()) +} + +async fn shared_data_catalog( + broker: Arc, + profile_id: &str, +) -> Result, String> { + let now = unix_timestamp()?; + let profile_id = profile_id.to_owned(); + tokio::task::spawn_blocking(move || { + broker + .sharing_catalog(now) + .into_iter() + .filter(|record| record.owner.profile_id == profile_id) + .collect() + }) + .await + .map_err(|_| "shared-data catalog worker failed".to_owned()) +} + +fn plugin_shared_data_snapshot_for( + identity: crate::plugin_host::grants::PluginIdentity, + policy_snapshot: crate::plugin_host::sharing_policy::RecipientSharingSnapshot, + catalog: Vec, +) -> PluginSharedDataSnapshot { + let catalog = catalog + .into_iter() + .map(|record| SharedDataCatalogRecord { + source_plugin_id: record.owner.plugin_id, + source_publisher_fingerprint: record.owner.publisher_fingerprint, + dataset_id: record.dataset_id, + class: sharing_class_name(record.class), + category: record.category.map(common_data_category_name), + record_id: record.record_id, + fields: record.fields.into_iter().collect(), + }) + .collect(); + let source_policies = policy_snapshot + .source_recipient_policies + .into_iter() + .map(|policy| SharedDataSourcePolicy { + source_plugin_id: policy.source().plugin_id.clone(), + source_publisher_fingerprint: policy.source().publisher_fingerprint.clone(), + dataset_id: policy.dataset_id().to_owned(), + class: sharing_class_name(policy.class()), + fields: policy.fields().iter().cloned().collect(), + history: policy.allows_history(), + live: policy.allows_live(), + }) + .collect(); + PluginSharedDataSnapshot { + plugin_id: identity.plugin_id, + publisher_fingerprint: identity.publisher_fingerprint, + profile_id: identity.profile_id, + policy_revision: policy_snapshot.revision, + common_categories: policy_snapshot + .categories + .into_iter() + .map(common_data_category_name) + .collect(), + selected_record_ids: policy_snapshot.selected_record_ids.into_iter().collect(), + catalog, + source_policies, + } +} + +/// Logical durable-pool usage of one producer. Contains no physical path. +#[derive(Clone, Debug, serde::Serialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct PluginDurableUsage { + pub plugin_id: String, + pub profile_id: String, + pub record_count: u64, + pub logical_bytes: u64, + pub max_bytes: u64, + pub max_age_seconds: Option, + pub oldest_updated_at: Option, +} + +/// The outcome of deleting one producer's retained durable records. The plugin stays installed. +#[derive(Clone, Debug, serde::Serialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct PluginDurableDeletion { + pub plugin_id: String, + pub profile_id: String, + pub removed_records: u64, + pub reclaimed_bytes: u64, + pub usage: PluginDurableUsage, +} + +fn plugin_durable_usage_for( + plugin_id: &str, + profile_id: &str, + usage: Option, +) -> PluginDurableUsage { + let usage = usage.unwrap_or(gamenode_platform::plugin_shared_data::OwnerUsage { + records: 0, + logical_bytes: 0, + max_bytes: gamenode_platform::plugin_shared_data::MAX_OWNER_LOGICAL_BYTES, + max_age_seconds: None, + oldest_updated_at: None, + archived_records: 0, + archived_logical_bytes: 0, + protected_records: 0, + physical_bytes_estimate: 0, + }); + PluginDurableUsage { + plugin_id: plugin_id.to_owned(), + profile_id: profile_id.to_owned(), + record_count: usage.records, + logical_bytes: usage.logical_bytes, + max_bytes: usage.max_bytes, + max_age_seconds: usage.max_age_seconds, + oldest_updated_at: usage.oldest_updated_at, + } +} + +/// Reads the durable-pool usage of one producer on the blocking storage worker. Never creates +/// the pool file. +#[tauri::command] +pub async fn plugin_durable_usage( + lifecycle: tauri::State<'_, Arc>, + pool: tauri::State<'_, Arc>, + plugin_id: String, + expected_profile_id: String, +) -> Result { + let owner = lifecycle + .durable_owner(plugin_id.clone(), &expected_profile_id) + .await + .map_err(|status| status.message().to_owned())?; + let now = unix_timestamp()?; + let usage = pool + .usage(owner, now) + .await + .map_err(|status| status.message().to_owned())?; + Ok(plugin_durable_usage_for( + &plugin_id, + &expected_profile_id, + usage, + )) +} + +/// Rejects a host deletion that the user did not confirm in the settings surface. +fn durable_delete_confirmation(confirmed: bool) -> Result<(), String> { + if confirmed { + Ok(()) + } else { + Err("deleting retained shared data requires confirmation".into()) + } +} + +/// Deletes only this producer's retained durable records and reports the bytes actually +/// reclaimed. It never uninstalls the plugin and never touches another owner or private storage. +#[tauri::command] +pub async fn plugin_durable_delete( + lifecycle: tauri::State<'_, Arc>, + pool: tauri::State<'_, Arc>, + plugin_id: String, + expected_profile_id: String, + confirmed: bool, +) -> Result { + durable_delete_confirmation(confirmed)?; + let owner = lifecycle + .durable_owner(plugin_id.clone(), &expected_profile_id) + .await + .map_err(|status| status.message().to_owned())?; + let now = unix_timestamp()?; + let outcome = pool + .delete_owner(owner, now) + .await + .map_err(|status| status.message().to_owned())?; + let usage = pool + .usage(owner, now) + .await + .map_err(|status| status.message().to_owned())?; + Ok(PluginDurableDeletion { + plugin_id: plugin_id.clone(), + profile_id: expected_profile_id.clone(), + removed_records: outcome.map_or(0, |outcome| outcome.removed_records), + reclaimed_bytes: outcome.map_or(0, |outcome| outcome.reclaimed_bytes), + usage: plugin_durable_usage_for(&plugin_id, &expected_profile_id, usage), + }) +} + +#[tauri::command] +pub async fn plugin_shared_data_replace( + lifecycle: tauri::State<'_, Arc>, + policies: tauri::State<'_, Arc>, + broker: tauri::State<'_, Arc>, + plugin_id: String, + update: PluginSharedDataPolicyUpdate, +) -> Result { + let observation = lifecycle + .observe_sharing_identity(plugin_id, &update.profile_id) + .await + .map_err(|status| status.message().to_owned())?; + let identity = &observation.identity; + if identity.publisher_fingerprint != update.expected_publisher_fingerprint { + return Err("plugin publisher changed; reload and review shared-data permissions".into()); + } + let expected_revision = update.expected_revision; + let existing = read_shared_data_policy(policies.inner().clone(), identity).await?; + if existing.revision != expected_revision { + return Err("shared-data permissions changed; reload and try again".into()); + } + let catalog = shared_data_catalog(broker.inner().clone(), &identity.profile_id).await?; + let categories = update + .common_categories + .iter() + .map(|category| common_data_category(category)) + .collect::, _>>()?; + let grant = crate::plugin_host::sharing_policy::ActivationReadGrant::new( + categories, + update.selected_record_ids.clone(), + ) + .map_err(|error| error.to_string())?; + let available_common_records = catalog + .iter() + .filter(|record| record.class == crate::plugin_host::sharing_policy::SharingClass::Common) + .map(|record| record.record_id.as_str()) + .collect::>(); + if update.selected_record_ids.iter().any(|record_id| { + !available_common_records.contains(record_id.as_str()) + && !existing.selected_record_ids.contains(record_id) + }) { + return Err("selected record is not present in the host sharing catalog".into()); + } + let mut source_policies = Vec::new(); + let mut required_sources = Vec::new(); + for decision in update.source_policies { + let class = sharing_class(&decision.class)?; + let source = crate::plugin_host::grants::PluginIdentity { + plugin_id: decision.source_plugin_id, + publisher_fingerprint: decision.source_publisher_fingerprint, + profile_id: identity.profile_id.clone(), + }; + let existing_policy = existing.source_recipient_policies.iter().find(|policy| { + policy.source() == &source + && policy.dataset_id() == decision.dataset_id + && policy.class() == class + }); + if decision.fields.is_empty() { + if decision.history || decision.live { + return Err("history or live delivery requires at least one approved field".into()); + } + continue; + } + let available_fields = catalog + .iter() + .filter(|record| { + record.owner == source + && record.dataset_id == decision.dataset_id + && record.class == class + }) + .flat_map(|record| record.fields.iter().cloned()) + .collect::>(); + let within_previous_grant = existing_policy.is_some_and(|previous| { + decision.fields.is_subset(previous.fields()) + && (!decision.history || previous.allows_history()) + && (!decision.live || previous.allows_live()) + }); + let source_is_current = !available_fields.is_empty() + && lifecycle + .sharing_identity(source.plugin_id.clone(), &identity.profile_id) + .await + .is_ok_and(|current| current == source); + if source_is_current { + if !decision.fields.is_subset(&available_fields) { + return Err("sharing policy names fields not published by this dataset".into()); + } + if !within_previous_grant && !required_sources.contains(&source) { + required_sources.push(source.clone()); + } + } else if !within_previous_grant { + return Err(if available_fields.is_empty() { + "new sharing grants require a current verified source" + } else { + "source identity is no longer verified; reload and review shared-data permissions" + } + .into()); + } + source_policies.push( + crate::plugin_host::sharing_policy::SourceRecipientPolicy::new( + source, + identity.clone(), + class, + decision.dataset_id, + decision.fields, + decision.history, + decision.live, + ) + .map_err(|error| error.to_string())?, + ); + } + let identity = identity.clone(); + let saved = lifecycle + .replace_sharing_policy( + observation, + policies.inner().clone(), + expected_revision, + grant, + source_policies, + required_sources, + ) + .await + .map_err(|status| status.message().to_owned())?; + Ok(plugin_shared_data_snapshot_for(identity, saved, catalog)) +} + +#[tauri::command] +pub async fn plugin_enable( + lifecycle: tauri::State<'_, Arc>, + engine: tauri::State<'_, Engine>, + plugin_id: String, +) -> Result<(), String> { + lifecycle + .enable(plugin_id) + .await + .map_err(|error| error.message().to_owned())?; + // Enabling starts the supervised provider; scan it now so its games appear without the user + // having to press refresh and without a restart. + engine.rescan(); + Ok(()) +} + +#[tauri::command] +pub async fn plugin_disable( + lifecycle: tauri::State<'_, Arc>, + engine: tauri::State<'_, Engine>, + plugin_id: String, +) -> Result<(), String> { + lifecycle + .disable(plugin_id) + .await + .map_err(|error| error.message().to_owned())?; + // The cached entries stay; publish the new provider availability so the store and warnings + // reflect the stop immediately. + engine.publish_current(); + Ok(()) +} + +/// Uninstalls one plugin after applying the user's durable shared-data choice. Omitting +/// `deleteData` keeps the rows, which is the default uninstall choice. +#[tauri::command] +pub async fn plugin_remove( + lifecycle: tauri::State<'_, Arc>, + engine: tauri::State<'_, Engine>, + plugin_id: String, + delete_data: Option, +) -> Result { + use crate::plugin_host::runtime::DataRetention; + let retention = if delete_data.unwrap_or(false) { + DataRetention::Delete + } else { + DataRetention::Keep + }; + let outcome = lifecycle + .remove_with_retention(plugin_id.clone(), retention) + .await + .map_err(|error| error.message().to_owned())?; + // The store disappears from the running library now; its cached rows stay for a reinstall. + engine.remove_library_provider(&plugin_id); + Ok(outcome) +} + +/// Reuses a reinstall's archived durable records after a separate host review. The user must +/// confirm the reuse; a consumer or new package cannot call this on another producer's data. +#[tauri::command] +pub async fn plugin_durable_reuse( + lifecycle: tauri::State<'_, Arc>, + plugin_id: String, + expected_profile_id: String, + confirmed: bool, +) -> Result { + lifecycle + .reuse_archived_durable_data(plugin_id, &expected_profile_id, confirmed) + .await + .map_err(|error| error.message().to_owned()) +} + +/// Restores a reinstall's archived private persistence entries after a separate host review. The +/// user must confirm; an unconfirmed call changes nothing. Another profile or plugin is untouched. +#[tauri::command] +pub async fn plugin_private_reuse( + lifecycle: tauri::State<'_, Arc>, + plugin_id: String, + expected_profile_id: String, + confirmed: bool, +) -> Result { + lifecycle + .reuse_archived_private_data(plugin_id, &expected_profile_id, confirmed) + .await + .map_err(|error| error.message().to_owned()) +} + +/// Enumerates host-wide storage cleanup candidates for the active profile. This is host +/// administration: it is a Tauri command only, never a plugin RPC. +#[tauri::command] +pub async fn plugin_storage_cleanup_review( + lifecycle: tauri::State<'_, Arc>, +) -> Result { + lifecycle + .storage_cleanup_review() + .await + .map_err(|error| error.message().to_owned()) +} + +/// Host-only physical accounting of the active profile's plugin data. This is host +/// administration: it is a Tauri command only, never a plugin RPC, and no plugin reply ever +/// carries a physical path. +#[tauri::command] +pub async fn plugin_storage_locations( + lifecycle: tauri::State<'_, Arc>, +) -> Result { + lifecycle + .storage_locations() + .await + .map_err(|error| error.message().to_owned()) +} + +/// Applies one confirmed, single-use cleanup review. Only the selected owner candidates are +/// pruned; an unconfirmed or stale call changes nothing and needs a new review. +#[tauri::command] +pub async fn plugin_storage_cleanup_apply( + lifecycle: tauri::State<'_, Arc>, + token: String, + candidate_ids: Vec, + confirmed: bool, +) -> Result { + lifecycle + .storage_cleanup_apply(token, candidate_ids, confirmed) + .await + .map_err(|error| error.message().to_owned()) +} + +/// Uninstalls one bundle as one action: every component stops, its package and mapping are +/// removed, and one retention choice applies to private data for the signed-in account. A partial +/// failure is returned with the remaining components instead of a generic error. +#[tauri::command] +pub async fn plugin_bundle_uninstall( + lifecycle: tauri::State<'_, Arc>, + settings: tauri::State<'_, Arc>, + engine: tauri::State<'_, Engine>, + bundle_id: String, + delete_data: bool, +) -> Result { + let outcome = lifecycle + .remove_bundle(bundle_id, settings.bundle_store(), delete_data) + .await + .map_err(|error| error.to_string())?; + // Every provider component leaves the running library now; its cached rows stay for a + // later reinstall. Extensions are a no-op for the library. + for component in &outcome.removed { + engine.remove_library_provider(&component.plugin_id); + } + Ok(outcome) +} + +#[tauri::command] +pub async fn plugin_configuration_state( + updates: tauri::State<'_, crate::plugin_host::updates::PluginUpdateService>, + plugin_id: String, +) -> Result { + updates + .configuration_state(plugin_id) + .await + .map_err(|error| error.message().to_owned()) +} + +static NEXT_SETTINGS_FORM: AtomicU64 = AtomicU64::new(1); + +#[tauri::command] +pub async fn plugin_configuration_modes( + providers: tauri::State<'_, crate::plugin_host::provider::ProviderApi>, + provider_id: String, +) -> Result { + providers + .configuration_modes(&provider_id) + .map_err(|status| status.message().to_owned()) +} + +#[derive(Clone, Debug, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PluginConfigurationStatus { + pub status: &'static str, + pub window_id: Option, + pub message: Option, +} + +#[tauri::command] +pub async fn plugin_configuration_open( + providers: tauri::State<'_, crate::plugin_host::provider::ProviderApi>, + provider_id: String, + focus: bool, +) -> Result { + use gamenode_plugin_protocol::proto::ProviderOperation; + let operation = if focus { + ProviderOperation::ConfigurationFocus + } else { + ProviderOperation::ConfigurationOpen + }; + Ok(match providers.configure(&provider_id, operation).await { + Ok(completion) => match completion.result.configuration { + Some(result) if result.accepted => PluginConfigurationStatus { + status: if focus { "focused" } else { "open" }, + window_id: Some(result.window_id), + message: None, + }, + Some(result) => PluginConfigurationStatus { + status: "failed", + window_id: None, + message: Some(result.failure), + }, + None => PluginConfigurationStatus { + status: "failed", + window_id: None, + message: Some("plugin returned no configuration result".into()), + }, + }, + Err(status) => { + let code = status.code(); + PluginConfigurationStatus { + status: match code { + tonic::Code::DeadlineExceeded => "timedOut", + tonic::Code::PermissionDenied => "denied", + tonic::Code::Unavailable | tonic::Code::FailedPrecondition => "unavailable", + _ => "failed", + }, + window_id: None, + message: Some(status.message().to_owned()), + } + } + }) +} + +#[tauri::command] +pub async fn plugin_settings_describe( + providers: tauri::State<'_, crate::plugin_host::provider::ProviderApi>, + provider_id: String, +) -> Result { + use gamenode_plugin_protocol::settings::{Action, Request}; + let handle = format!( + "settings-form-{}", + NEXT_SETTINGS_FORM.fetch_add(1, Ordering::Relaxed) + ); + let context = providers + .settings_scope(&provider_id, handle) + .map_err(|status| status.message().to_owned())?; + complete_plugin_settings( + &providers, + Request { + context, + action: Action::DescribeRead, + }, + ) + .await +} + +#[tauri::command] +pub async fn plugin_settings_submit( + providers: tauri::State<'_, crate::plugin_host::provider::ProviderApi>, + context: gamenode_plugin_protocol::settings::Context, + schema_revision: String, + configuration_revision: String, + values: gamenode_plugin_protocol::settings::Values, +) -> Result { + use gamenode_plugin_protocol::settings::{Action, Request}; + complete_plugin_settings( + &providers, + Request { + context, + action: Action::Submit { + schema_revision, + configuration_revision, + values, + }, + }, + ) + .await +} + +#[tauri::command] +pub async fn plugin_settings_cancel( + providers: tauri::State<'_, crate::plugin_host::provider::ProviderApi>, + context: gamenode_plugin_protocol::settings::Context, +) -> Result { + use gamenode_plugin_protocol::settings::{Action, Request}; + complete_plugin_settings( + &providers, + Request { + context, + action: Action::Cancel, + }, + ) + .await +} + +async fn complete_plugin_settings( + providers: &crate::plugin_host::provider::ProviderApi, + request: gamenode_plugin_protocol::settings::Request, +) -> Result { + request + .validate() + .map_err(|_| "invalid plugin settings request".to_owned())?; + let completion = providers + .execute_settings(request.clone()) + .await + .map_err(|status| status.message().to_owned())?; + let reply: gamenode_plugin_protocol::settings::Reply = completion + .result + .settings + .ok_or_else(|| "plugin returned no settings response".to_owned())? + .try_into() + .map_err(|_| "plugin returned an invalid settings response".to_owned())?; + reply + .validate_for(&request) + .map_err(|_| "plugin settings response did not match the request".to_owned())?; + Ok(reply) +} + +#[tauri::command] +pub async fn plugin_playtime_inventory( + engine: tauri::State<'_, Engine>, + updates: tauri::State<'_, crate::plugin_host::updates::PluginUpdateService>, +) -> Result, String> { + let engine = engine.inner().clone(); + let mut plugins = updates.playtime_inventory().await?; + for plugin in &mut plugins { + plugin.accounting_enabled = engine + .plugin_playtime_accounting_enabled(plugin.plugin_id.clone()) + .await?; + } + Ok(plugins) +} + +#[tauri::command] +pub async fn plugin_playtime_set_accounting( + engine: tauri::State<'_, Engine>, + plugin_id: String, + enabled: bool, ) -> Result<(), String> { - let snapshot = engine.snapshot(); - if let Some(library) = &snapshot.library - && library.selected.len() == 1 + engine + .inner() + .set_plugin_playtime_accounting(plugin_id, enabled) + .await +} + +#[tauri::command] +pub async fn plugin_update_preferences( + updates: tauri::State<'_, crate::plugin_host::updates::PluginUpdateService>, +) -> Result { + Ok(updates.preferences()) +} + +#[tauri::command] +pub async fn plugin_update_available( + updates: tauri::State<'_, crate::plugin_host::updates::PluginUpdateService>, +) -> Result, String> { + Ok(updates.available_updates()) +} + +#[tauri::command] +pub async fn plugin_update_set_periodic_checks( + updates: tauri::State<'_, crate::plugin_host::updates::PluginUpdateService>, + enabled: bool, +) -> Result { + // Persisting this preference performs filesystem I/O. Keep it off Tauri's async command + // executor so a slow disk cannot block IPC handling or the UI runtime. + let updates = updates.inner().clone(); + tokio::task::spawn_blocking(move || updates.set_periodic_checks(enabled)) + .await + .map_err(|_| "plugin update preferences worker failed".to_owned())? +} + +#[tauri::command] +pub async fn plugin_update_check( + updates: tauri::State<'_, crate::plugin_host::updates::PluginUpdateService>, +) -> Result, String> { + updates.check_updates().await +} + +async fn add_extension_readiness_targets( + engine: &Engine, + mut review: crate::plugin_host::updates::UpdateReview, +) -> Result { + if let Some(targets) = &mut review.extension_targets { + let engine = engine.clone(); + *targets = tokio::task::spawn_blocking(move || engine.extension_readiness_choices()) + .await + .map_err(|_| "extension target lookup worker failed".to_owned())?; + } + Ok(review) +} + +#[tauri::command] +pub async fn plugin_update_review( + engine: tauri::State<'_, Engine>, + updates: tauri::State<'_, crate::plugin_host::updates::PluginUpdateService>, + plugin_id: String, + version: String, +) -> Result { + let review = updates.review(&plugin_id, &version).await?; + add_extension_readiness_targets(&engine, review).await +} + +#[tauri::command] +pub async fn plugin_rollback_available( + updates: tauri::State<'_, crate::plugin_host::updates::PluginUpdateService>, +) -> Result, String> { + updates.available_rollbacks().await +} + +#[tauri::command] +pub async fn plugin_rollback_review( + engine: tauri::State<'_, Engine>, + updates: tauri::State<'_, crate::plugin_host::updates::PluginUpdateService>, + plugin_id: String, + version: String, +) -> Result { + let review = updates.review_rollback(&plugin_id, &version).await?; + add_extension_readiness_targets(&engine, review).await +} + +#[tauri::command] +pub async fn plugin_update_retrust_publisher( + updates: tauri::State<'_, crate::plugin_host::updates::PluginUpdateService>, + plugin_id: String, + version: String, + fingerprint: String, +) -> Result<(), String> { + updates + .confirm_publisher_retrust(&plugin_id, &version, &fingerprint) + .await +} + +/// Resolving a readiness target takes the engine lock, so it runs on a blocking worker. +async fn resolve_extension_target( + engine: Engine, + selection: Option, +) -> Result, String> { + let Some(selection) = selection else { + return Ok(None); + }; + tokio::task::spawn_blocking(move || engine.resolve_extension_readiness(selection)) + .await + .map_err(|_| "extension target worker failed".to_owned())? + .map(Some) + .map_err(|error| error.message().to_owned()) +} + +#[tauri::command] +pub async fn plugin_rollback_approve( + engine: tauri::State<'_, Engine>, + updates: tauri::State<'_, crate::plugin_host::updates::PluginUpdateService>, + plugin_id: String, + version: String, + confirmed: bool, + target: Option, +) -> Result { + if !confirmed { + return Err("rollback requires explicit user confirmation".into()); + } + let target = resolve_extension_target(engine.inner().clone(), target).await?; + updates + .approve_rollback(&plugin_id, &version, confirmed, target) + .await +} + +#[tauri::command] +pub async fn plugin_update_approve( + engine: tauri::State<'_, Engine>, + updates: tauri::State<'_, crate::plugin_host::updates::PluginUpdateService>, + plugin_id: String, + version: String, + target: Option, +) -> Result { + let target = resolve_extension_target(engine.inner().clone(), target).await?; + updates.approve(&plugin_id, &version, target).await +} + +#[tauri::command] +pub async fn plugin_update_decline( + updates: tauri::State<'_, crate::plugin_host::updates::PluginUpdateService>, + plugin_id: String, +) -> Result<(), String> { + updates.decline(&plugin_id).await; + Ok(()) +} + +/// Delivers the user's answer to a plugin's confirmation. A late, repeated or unknown answer is +/// ignored: only a confirmation that is still waiting takes one. +#[tauri::command] +pub async fn plugin_confirmation_answer( + bridge: tauri::State<'_, Arc>, + id: String, + approved: bool, + remember: bool, +) -> Result<(), String> { + bridge.answer(&id, approved, remember); + Ok(()) +} + +/// Answers a pending folder-selection prompt. Empty paths and declines cancel the approval. +#[tauri::command] +pub async fn plugin_folder_selection_answer( + bridge: tauri::State<'_, Arc>, + id: String, + selected_root: Option, +) -> Result<(), String> { + if selected_root + .as_ref() + .is_some_and(|path| path.is_empty() || path.len() > 32 * 1024 || path.contains('\0')) { - let key = library.selected[0].clone(); - engine.open_entry(key, kind); + return Err("invalid folder selection".into()); } + bridge.answer_selection(&id, selected_root); Ok(()) } +/// Answers a pending folder-scope confirmation. A late or repeated response is ignored. #[tauri::command] -pub async fn dismiss_launch(engine: tauri::State<'_, Engine>) -> Result<(), String> { - engine.dismiss_launch(); +pub async fn plugin_folder_approval_answer( + bridge: tauri::State<'_, Arc>, + id: String, + approved: bool, +) -> Result<(), String> { + bridge.answer_confirmation(&id, approved); Ok(()) } +/// Answers a pending runtime picker. A null, empty or malformed selection declines it. #[tauri::command] -pub async fn rescan_library(engine: tauri::State<'_, Engine>) -> Result<(), String> { - engine.rescan(); +pub async fn plugin_runtime_selection_answer( + bridge: tauri::State<'_, Arc>, + id: String, + selected_executable: Option, +) -> Result<(), String> { + if selected_executable + .as_ref() + .is_some_and(|path| path.is_empty() || path.len() > 32 * 1024 || path.contains('\0')) + { + return Err("invalid runtime selection".into()); + } + bridge.answer(&id, selected_executable); Ok(()) } -/// Opens a GameNode website page in the default browser (D14). The browser work runs on a -/// blocking worker; a typed error keeps the UI copy localized. +/// Lists file and logical-library root approvals in one plugin's active account profile. #[tauri::command] -pub async fn open_gamenode_page( - engine: tauri::State<'_, Engine>, - page: crate::engine::GameNodePage, -) -> Result<(), crate::engine::GameNodePageError> { - engine.open_gamenode_page(page).await +pub async fn plugin_folder_approvals( + approvals: tauri::State<'_, Arc>, + plugin_id: String, + publisher_fingerprint: String, +) -> Result, String> { + approvals.list(&plugin_id, &publisher_fingerprint).await } -/// Opens one of the fixed GameNode website links (About footer, Account › Abrir perfil). The UI -/// passes an enum, never a URL; `profile` needs a verified session. +/// Revokes a folder approval or a standing logical-library root approval. #[tauri::command] -pub async fn open_gamenode_link( - engine: tauri::State<'_, Engine>, - kind: crate::engine::GameNodeLink, -) -> Result<(), crate::engine::GameNodePageError> { - engine.open_gamenode_link(kind).await +pub async fn plugin_folder_revoke( + approvals: tauri::State<'_, Arc>, + plugin_id: String, + publisher_fingerprint: String, + id: String, +) -> Result { + approvals + .revoke(&plugin_id, &publisher_fingerprint, &id) + .await } -/// Cached cover file names for the signed-out screen's mural; empty when the cache has none. +/// Opens the folder chooser and replaces an existing file approval with the newly confirmed root. #[tauri::command] -pub async fn sign_in_cover_wall(engine: tauri::State<'_, Engine>) -> Result, String> { - Ok(engine.inner().clone().sign_in_cover_wall().await) +pub async fn plugin_folder_change( + approvals: tauri::State<'_, Arc>, + plugin_id: String, + publisher_fingerprint: String, + id: String, +) -> Result<(), String> { + approvals + .change_root(&plugin_id, &publisher_fingerprint, &id) + .await } +/// Turns Core discovery on or off for a standing logical-library root. #[tauri::command] -pub async fn remove_entry( - engine: tauri::State<'_, Engine>, - key: String, - allow_rediscovery: bool, +pub async fn plugin_library_root_set_watching( + approvals: tauri::State<'_, Arc>, + plugin_id: String, + publisher_fingerprint: String, + id: String, + watching: bool, +) -> Result { + approvals + .set_watching(&plugin_id, &publisher_fingerprint, &id, watching) + .await +} + +/// Lists active runtime program approvals in one plugin's active account profile. +#[tauri::command] +pub async fn plugin_runtime_approvals( + approvals: tauri::State<'_, Arc>, + plugin_id: String, + publisher_fingerprint: String, +) -> Result, String> { + approvals.list(&plugin_id, &publisher_fingerprint).await +} + +/// Revokes one runtime program approval, so the next Play asks for a fresh program. +#[tauri::command] +pub async fn plugin_runtime_revoke( + approvals: tauri::State<'_, Arc>, + plugin_id: String, + publisher_fingerprint: String, + runtime_id: String, +) -> Result { + approvals + .revoke(&plugin_id, &publisher_fingerprint, &runtime_id) + .await +} + +/// Lists declared shared emulator resources and the host-resolved affected games for review. +#[tauri::command] +pub async fn plugin_shared_resource_reviews( + resources: tauri::State<'_, Arc>, + plugin_id: String, + publisher_fingerprint: String, +) -> Result, String> { + resources.list(&plugin_id, &publisher_fingerprint).await +} + +/// Accepts the exact current declaration and affected-game scope of one shared resource. +#[tauri::command] +pub async fn plugin_shared_resource_accept( + resources: tauri::State<'_, Arc>, + plugin_id: String, + publisher_fingerprint: String, + profile_id: String, + resource_id: String, ) -> Result<(), String> { - engine.remove_entry(key, allow_rediscovery); - Ok(()) + resources + .accept( + &plugin_id, + &publisher_fingerprint, + &profile_id, + &resource_id, + ) + .await } -// --------------------------------------------------------------------------- -// Store Account Commands -// --------------------------------------------------------------------------- +/// Forgets a shared-resource consent; the next use asks for a fresh review. +#[tauri::command] +pub async fn plugin_shared_resource_revoke( + resources: tauri::State<'_, Arc>, + plugin_id: String, + publisher_fingerprint: String, + profile_id: String, + resource_id: String, +) -> Result { + resources + .revoke( + &plugin_id, + &publisher_fingerprint, + &profile_id, + &resource_id, + ) + .await +} -/// Returns trusted packaged plugin metadata. Executable inspection runs off the async worker. +/// What the user allowed one plugin to start without asking, in the active profile. #[tauri::command] -pub async fn plugin_inventory( - engine: tauri::State<'_, Engine>, -) -> Result, String> { - let engine = engine.inner().clone(); - tokio::task::spawn_blocking(move || { - crate::plugin_host::inventory(|id| { - let (_, connected) = engine.provider_health(id); - (engine.provider_availability(id), connected) - }) - }) - .await - .map_err(|_| "plugin inventory worker failed".to_owned()) +pub async fn plugin_remembered_confirmations( + approvals: tauri::State<'_, Arc>, + plugin_id: String, + publisher_fingerprint: String, +) -> Result, String> { + approvals.list(&plugin_id, &publisher_fingerprint).await +} + +/// Forgets one remembered confirmation, so the next request asks the user again. +#[tauri::command] +pub async fn plugin_revoke_confirmation( + approvals: tauri::State<'_, Arc>, + plugin_id: String, + publisher_fingerprint: String, + id: String, +) -> Result { + approvals + .revoke(&plugin_id, &publisher_fingerprint, &id) + .await } /// Whether `provider_id` names a provider the host loaded with an account and catalog. @@ -616,6 +2103,44 @@ pub async fn plugin_stop( engine.plugin_stop(&provider_id).await } +/// Lists supervised custom launches for host-controlled termination. +#[tauri::command] +pub async fn custom_launch_ids( + engine: tauri::State<'_, Engine>, + entry_key: Option, +) -> Result, String> { + #[cfg(any(target_os = "linux", windows))] + { + match entry_key { + Some(key) => engine.supervised_custom_launch_ids_for_entry(key).await, + None => engine.supervised_custom_launch_ids().await, + } + .map_err(|error| error.message().to_owned()) + } + #[cfg(not(any(target_os = "linux", windows)))] + { + let _ = (engine, entry_key); + Ok(Vec::new()) + } +} + +/// Explicitly stops a supervised custom launch and confirms that its tree is fenced. +#[tauri::command] +pub async fn custom_launch_stop(engine: tauri::State<'_, Engine>, id: u64) -> Result<(), String> { + #[cfg(any(target_os = "linux", windows))] + { + engine + .stop_supervised_custom_launch(id) + .await + .map_err(|error| error.message().to_owned()) + } + #[cfg(not(any(target_os = "linux", windows)))] + { + let _ = (engine, id); + Err("custom launch termination is unavailable".into()) + } +} + /// Starts a stopped plugin with a fresh session and restores its account (Settings › Plugins › /// Iniciar). #[tauri::command] @@ -1314,6 +2839,15 @@ pub async fn ports_install( } /// Cancels a queued, running or executable-awaiting job. +#[tauri::command] +pub async fn ports_dismiss_plugin_setup( + engine: tauri::State<'_, Engine>, + request_id: String, +) -> Result<(), String> { + engine.dismiss_plugin_port(request_id); + Ok(()) +} + #[tauri::command] pub async fn ports_cancel( engine: tauri::State<'_, Engine>, @@ -1561,11 +3095,22 @@ mod tests { plugin_id: "org.gamenode.plugin.steam-discovery".to_owned(), name: "Steam".to_owned(), version: "1.2.3".to_owned(), + plugin_kind: "provider".to_owned(), + enabled: None, + runtime_available: None, + publisher_fingerprint: None, + compatibility_details: None, source: "official".to_owned(), status: "installed".to_owned(), capabilities: vec!["library.discovery".to_owned()], session: "active".to_owned(), native_access: vec!["files".to_owned()], + bundle_id: None, + bundle_name: None, + bundle_version: None, + bundle_component_kind: None, + bundle_publisher_fingerprint: None, + bundle_components: None, }]; let stores = vec![SystemStore { name: "Steam".to_owned(), @@ -1674,4 +3219,67 @@ mod tests { } assert_eq!(*called.lock().unwrap(), ["steam", "epic"]); } + + #[test] + fn durable_deletion_requires_explicit_confirmation() { + assert!(durable_delete_confirmation(true).is_ok()); + assert_eq!( + durable_delete_confirmation(false).unwrap_err(), + "deleting retained shared data requires confirmation" + ); + } + + #[test] + fn durable_usage_and_deletion_disclose_no_physical_path() { + let usage = PluginDurableUsage { + plugin_id: "org.example.producer".into(), + profile_id: "profile-a".into(), + record_count: 3, + logical_bytes: 4096, + max_bytes: 65_536, + max_age_seconds: Some(86_400), + oldest_updated_at: Some(1_700_000_000), + }; + let json = serde_json::to_value(&usage).unwrap(); + let object = json.as_object().unwrap(); + assert_eq!( + object + .keys() + .cloned() + .collect::>(), + [ + "logicalBytes", + "maxAgeSeconds", + "maxBytes", + "oldestUpdatedAt", + "pluginId", + "profileId", + "recordCount", + ] + .map(str::to_owned) + .into_iter() + .collect::>() + ); + let text = json.to_string(); + for forbidden in ["path", "sqlite", "/home", "\\\\"] { + assert!(!text.to_ascii_lowercase().contains(forbidden), "{text}"); + } + + let deleted = serde_json::to_value(&PluginDurableDeletion { + plugin_id: "org.example.producer".into(), + profile_id: "profile-a".into(), + removed_records: 3, + reclaimed_bytes: 4096, + usage: PluginDurableUsage { + record_count: 0, + logical_bytes: 0, + ..usage + }, + }) + .unwrap(); + assert_eq!(deleted["removedRecords"], 3); + assert_eq!(deleted["reclaimedBytes"], 4096); + assert_eq!(deleted["usage"]["recordCount"], 0); + assert!(!deleted.to_string().to_ascii_lowercase().contains("path")); + } } diff --git a/crates/app/src/engine/detected_target.rs b/crates/app/src/engine/detected_target.rs new file mode 100644 index 000000000..ac52486e6 --- /dev/null +++ b/crates/app/src/engine/detected_target.rs @@ -0,0 +1,347 @@ +//! User approval, repair and launch of provider-detected game targets. + +use super::{Engine, unix_now}; +use gamenode_core::drm_free::{InstallationHost, LocalError, Registration, resolve_install_path}; +use gamenode_core::library::{ + DetectedTarget, Input as LibraryInput, LaunchError, StoredEntry, TargetApproval, TargetSpec, +}; +use std::path::Path; + +impl Engine { + /// Approves the currently reported target after host validation. File I/O runs on a worker. + pub async fn review_detected_target( + &self, + entry_key: String, + expected_revision: u64, + ) -> Result<(), String> { + let engine = self.clone(); + tokio::task::spawn_blocking(move || { + engine.review_target_blocking(entry_key, expected_revision, None) + }) + .await + .map_err(|_| "target review worker failed".to_owned())? + } + + /// Lets the user locate a replacement executable, validates it under the install root and + /// records the explicit selection as approval for the new target revision. + pub async fn repair_detected_target( + &self, + entry_key: String, + expected_revision: u64, + ) -> Result<(), String> { + let engine = self.clone(); + tokio::task::spawn_blocking(move || { + engine.review_target_blocking(entry_key, expected_revision, Some(())) + }) + .await + .map_err(|_| "target repair worker failed".to_owned())? + } + + fn review_target_blocking( + &self, + entry_key: String, + expected_revision: u64, + repair: Option<()>, + ) -> Result<(), String> { + let entry = { + let state = self.lock(); + state + .library + .entry(&entry_key) + .cloned() + .ok_or_else(|| "library entry no longer exists".to_owned())? + }; + let current = entry + .target + .as_ref() + .filter(|target| target.revision == expected_revision) + .ok_or_else(|| "detected target changed; review the latest version".to_owned())?; + + let replacement = if let Some(()) = repair { + let TargetSpec::Executable { root, .. } = ¤t.spec else { + return Err("only executable targets can be repaired".into()); + }; + let Some(selected) = gamenode_platform::installations::pick_executable_in(root) + .map_err(|_| "could not open the executable picker".to_owned())? + else { + return Ok(()); + }; + let host = self + .shared + .ports + .installations + .as_deref() + .ok_or_else(|| "executable launching is unavailable".to_owned())?; + let (registration, identity) = + inspect_target(host, ¤t.spec, Some(&selected)).map_err(target_error)?; + let TargetSpec::Executable { arguments, .. } = ¤t.spec else { + unreachable!("checked above") + }; + let relative = Path::new(®istration.executable) + .strip_prefix(Path::new(®istration.root)) + .map_err(|_| "the selected executable must stay inside the game folder".to_owned())? + .to_string_lossy() + .replace('\\', "/"); + let spec = TargetSpec::Executable { + root: registration.root.clone(), + path: relative, + arguments: arguments.clone(), + working_directory: String::new(), + }; + if !spec.validate_shape() { + return Err("the selected executable is not a valid game target".into()); + } + current.repaired(spec, identity, unix_now()) + } else { + if !current.available { + return Err( + "the detected target is unavailable; locate its executable to repair it".into(), + ); + } + let identity = match ¤t.spec { + TargetSpec::Uri { .. } => None, + TargetSpec::Executable { .. } => { + let host = self + .shared + .ports + .installations + .as_deref() + .ok_or_else(|| "executable launching is unavailable".to_owned())?; + match inspect_target(host, ¤t.spec, None) { + Ok((_, identity)) => Some(identity), + Err(LocalError::InvalidTarget) => { + self.mark_detected_target_unavailable(&entry.key, expected_revision); + return Err("the detected executable is missing or invalid; locate it to repair the target".into()); + } + Err(error) => return Err(target_error(error)), + } + } + }; + let mut approved = current.clone(); + approved.approved = true; + approved.available = true; + approved.identity = identity; + approved + }; + + self.save_review(&entry, expected_revision, replacement) + } + + fn save_review( + &self, + entry: &StoredEntry, + expected_revision: u64, + target: DetectedTarget, + ) -> Result<(), String> { + match self + .shared + .ports + .library + .save_target_review(&entry.key, expected_revision, &target) + .map_err(|_| "could not save the target approval".to_owned())? + { + TargetApproval::Applied { .. } => { + self.library_input(LibraryInput::TargetReviewed { + entry_key: entry.key.clone(), + expected_revision, + target, + }); + Ok(()) + } + TargetApproval::Conflict { .. } => { + Err("detected target changed; review the latest version".into()) + } + TargetApproval::Missing => Err("detected target no longer exists".into()), + } + } + + fn mark_detected_target_unavailable(&self, entry_key: &str, expected_revision: u64) { + let entry = { + let state = self.lock(); + state.library.entry(entry_key).cloned() + }; + let Some(entry) = entry else { return }; + let Some(current) = entry + .target + .as_ref() + .filter(|target| target.revision == expected_revision) + else { + return; + }; + let target = DetectedTarget::missing(current, unix_now()); + let _ = self.save_review(&entry, expected_revision, target); + } +} + +pub(super) fn launch( + engine: &Engine, + entry: &StoredEntry, + target: &DetectedTarget, +) -> Result<(), LaunchError> { + if !target.available { + return Err(LaunchError::Incomplete); + } + if !target.approved { + return Err(LaunchError::Incomplete); + } + match &target.spec { + TargetSpec::Uri { uri } => { + let url = url::Url::parse(uri).map_err(|_| LaunchError::Failed)?; + engine + .shared + .ports + .uri + .open(&url) + .map_err(|error| match error { + gamenode_core::ports::UriError::Unsupported => LaunchError::Unsupported, + gamenode_core::ports::UriError::NoHandler => LaunchError::NoHandler, + gamenode_core::ports::UriError::Failed => LaunchError::Failed, + }) + } + TargetSpec::Executable { .. } => { + let Some(host) = engine.shared.ports.installations.as_deref() else { + return Err(LaunchError::Unsupported); + }; + let (registration, identity) = match inspect_target(host, &target.spec, None) { + Ok(value) => value, + Err(LocalError::Unsupported) => return Err(LaunchError::Unsupported), + Err(LocalError::InvalidTarget) => { + engine.mark_detected_target_unavailable(&entry.key, target.revision); + return Err(LaunchError::Incomplete); + } + Err(_) => return Err(LaunchError::Failed), + }; + if target.identity.as_deref() != Some(identity.as_str()) { + engine.mark_detected_target_unavailable(&entry.key, target.revision); + return Err(LaunchError::Incomplete); + } + host.launch(®istration).map_err(|error| match error { + LocalError::Unsupported => LaunchError::Unsupported, + LocalError::InvalidTarget => { + engine.mark_detected_target_unavailable(&entry.key, target.revision); + LaunchError::Incomplete + } + _ => LaunchError::Failed, + }) + } + } +} + +/// Resolves the approved detected executable for a parameter-only or declared mod-layer overlay. +/// The target revision is checked again, and a URI target is refused rather than silently +/// dropping the reviewed arguments or environment changes. +pub(super) fn resolved_command( + engine: &Engine, + entry_key: &str, + expected_revision: u64, +) -> Result { + let entry = { + let state = engine.lock(); + state + .library + .entry(entry_key) + .cloned() + .ok_or_else(|| tonic::Status::not_found("library entry not found"))? + }; + let target = entry + .target + .as_ref() + .filter(|target| target.revision == expected_revision) + .ok_or_else(|| { + tonic::Status::failed_precondition( + "the detected target changed; review the launch choice", + ) + })?; + if !target.available || !target.approved { + return Err(tonic::Status::failed_precondition( + "the detected target must be reviewed before a customized launch", + )); + } + match &target.spec { + TargetSpec::Uri { .. } => Err(tonic::Status::unimplemented( + "a detected URI target cannot apply a parameter or mod-layer overlay", + )), + TargetSpec::Executable { .. } => { + let host = engine + .shared + .ports + .installations + .as_deref() + .ok_or_else(|| { + tonic::Status::unimplemented( + "detected executable launch is unavailable on this platform", + ) + })?; + let (registration, identity) = + inspect_target(host, &target.spec, None).map_err(|error| match error { + LocalError::Unsupported => tonic::Status::unimplemented( + "detected executable launch is unavailable on this platform", + ), + LocalError::InvalidTarget => tonic::Status::failed_precondition( + "the detected executable changed or is invalid; review the target", + ), + _ => tonic::Status::unavailable("could not inspect the detected executable"), + })?; + if target.identity.as_deref() != Some(identity.as_str()) { + return Err(tonic::Status::failed_precondition( + "the detected executable changed; review the target", + )); + } + Ok(gamenode_core::drm_free::CustomLaunchCommand { + executable: registration.executable, + file_identity: registration.file_identity, + arguments: registration.arguments, + working_directory: registration.working_directory, + environment: Default::default(), + }) + } + } +} + +fn inspect_target( + host: &dyn InstallationHost, + spec: &TargetSpec, + selected_path: Option<&str>, +) -> Result<(Registration, String), LocalError> { + let TargetSpec::Executable { + root, + path, + arguments, + working_directory, + } = spec + else { + return Err(LocalError::InvalidTarget); + }; + if !spec.validate_shape() { + return Err(LocalError::InvalidTarget); + } + let executable = selected_path + .map(str::to_owned) + .or_else(|| resolve_install_path(root, path)) + .ok_or(LocalError::InvalidTarget)?; + let mut registration = host.inspect(&executable)?; + let identity = registration.file_identity.clone(); + registration.root = root.clone(); + registration.working_directory = if selected_path.is_some() || working_directory.is_empty() { + root.clone() + } else { + resolve_install_path(root, working_directory).ok_or(LocalError::InvalidTarget)? + }; + registration.arguments = arguments.clone(); + registration.gameplay = vec![registration.executable.clone()]; + registration.launchers.clear(); + let registration = host.validate_registration(®istration)?; + Ok((registration, identity)) +} + +fn target_error(error: LocalError) -> String { + match error { + LocalError::Unsupported => "executable targets are unavailable on this platform".into(), + LocalError::InvalidTarget => { + "the executable is missing, invalid, or outside the game's install folder".into() + } + LocalError::Busy => "target review is busy".into(), + LocalError::Cancelled => "target review was cancelled".into(), + LocalError::Failed(_) => "the executable could not be validated".into(), + } +} diff --git a/crates/app/src/engine/drm_free.rs b/crates/app/src/engine/drm_free.rs index b60c8cb44..fd460c7ef 100644 --- a/crates/app/src/engine/drm_free.rs +++ b/crates/app/src/engine/drm_free.rs @@ -133,7 +133,7 @@ impl Engine { let store_key = entry.key.clone(); let store_title = entry.name.clone().unwrap_or_else(|| entry.store_id.clone()); - let store_cover = state.library.cover_for(&store_key); + let store_cover = state.library.entry_cover_file(&store_key); let playtime_seconds = state .library .playtime_for(&store_key) @@ -142,7 +142,7 @@ impl Engine { let registration_cover = registration .custom_cover .clone() - .or_else(|| state.library.cover_for(&key)); + .or_else(|| state.library.entry_cover_file(&key)); ( PendingClaim { store_key, @@ -446,13 +446,23 @@ impl Engine { }); finished.await.map_err(|_| LocalError::Cancelled)? } - fn load_local_view(&self) -> LocalView { + pub(super) fn load_local_view(&self) -> LocalView { let Some(store) = &self.shared.ports.local_games else { return LocalView::default(); }; let result = (|| { let mut roots = store.watches()?; let registrations = store.registrations()?; + let plugin_watch_ids: Vec<_> = self + .shared + .plugin_scan_roots + .lock() + .unwrap_or_else(|p| p.into_inner()) + .values() + .flatten() + .filter(|r| r.root.watching && (r.valid)().is_ok()) + .map(|r| r.root.id.clone()) + .collect(); // Availability is a fact of this moment: the first time a folder is missing keeps // the time it became unavailable, and reconnecting clears it. let now = unix_now(); @@ -484,9 +494,10 @@ impl Engine { .candidates()? .into_iter() .filter(|candidate| { - watches + (watches .iter() .any(|watch| watch.enabled && watch.id == candidate.watch) + || plugin_watch_ids.contains(&candidate.watch)) && !registrations.iter().any(|r| { candidate_matches_registration(candidate, r) && r.removed @@ -1700,7 +1711,7 @@ impl Engine { let mut usage = backup_usage_at(&settings.destination, ®istrations, &profiles); let state = self.lock(); for game in &mut usage.games { - game.cover_file = state.library.cover_for(&game.entry_key); + game.cover_file = state.library.entry_cover_file(&game.entry_key); } usage.total_bytes = usage.games.iter().map(|game| game.bytes).sum(); usage.total_versions = usage.games.iter().map(|game| game.versions).sum(); @@ -1891,6 +1902,15 @@ impl Engine { &self, candidates: Vec, ) -> Result, LocalError> { + self.auto_register_candidates_checked(candidates, &|| Ok(())) + } + + fn auto_register_candidates_checked( + &self, + candidates: Vec, + valid: &dyn Fn() -> Result<(), LocalError>, + ) -> Result, LocalError> { + valid()?; let store = self .shared .ports @@ -1912,6 +1932,7 @@ impl Engine { }; let mut added_titles = Vec::new(); for mut candidate in candidates { + valid()?; if candidate.ignored || prior .iter() @@ -1946,6 +1967,7 @@ impl Engine { } candidate.likely_non_game = gamenode_core::drm_free::identity::likely_non_game(&candidate); + valid()?; store.save_candidate(&candidate).map_err(local_storage)?; if candidate.likely_non_game { // A likely non-game stays in the review unchecked; it is never added on its own. @@ -1956,6 +1978,7 @@ impl Engine { candidate.selected_target.as_deref(), ) { let mut registration = host.inspect(target)?; + valid()?; registration.root = candidate.root.clone(); registration.title = candidate.title.clone(); if let Some(pos) = registrations.iter().position(|r| { @@ -2069,6 +2092,7 @@ impl Engine { return; }; let mut added_titles = Vec::new(); + let mut checked_ids = Vec::new(); let result = (|| { // One parse serves every watched root; the scan drops it when it ends. let _release = gamenode_platform::manifest_cache::release_on_drop(); @@ -2093,15 +2117,86 @@ impl Engine { added_titles.extend(engine.auto_register_candidates(pending)?); } } + let contributions: Vec<_> = engine + .shared + .plugin_scan_roots + .lock() + .unwrap_or_else(|p| p.into_inner()) + .values() + .flatten() + .cloned() + .collect(); + let mut all: Vec<_> = enabled_watches.into_iter().map(|w| (w, None)).collect(); + all.extend( + contributions + .into_iter() + .filter(|r| only.is_none() && r.root.watching) + .map(|r| { + ( + WatchRoot { + id: r.root.id.clone(), + path: r.root.path.clone(), + enabled: true, + ..Default::default() + }, + Some(r), + ) + }), + ); + for (watch, _) in &mut all { + if let Ok(path) = std::fs::canonicalize(&watch.path) { + watch.path = gamenode_platform::host::strip_verbatim_prefix( + path.to_string_lossy().into_owned(), + ); + } + } + all.sort_by_key(|(w, _)| w.path.len()); let mut scanned_roots = Vec::::new(); let mut incomplete = Vec::new(); - let mut checked_ids = Vec::new(); - for watch in enabled_watches { + let mut failure = None; + for (watch, contribution) in all { + let valid = || -> Result<(), LocalError> { + if let Some(r) = &contribution { + (r.valid)().map_err(|_| LocalError::Cancelled)?; + let root = gamenode_platform::plugin_files::ApprovedRoot { + path: std::path::PathBuf::from(&r.root.path), + identity: gamenode_platform::plugin_files::Identity { + volume: r.root.volume, + node: r.root.node, + }, + }; + gamenode_platform::plugin_files::Confined::open( + &root, + &Default::default(), + ) + .map_err(|_| LocalError::InvalidTarget)?; + if gamenode_platform::volume::volume_info(&root.path).is_none_or(|v| { + v.volume_identity_token.is_empty() + || v.volume_identity_token != r.root.volume_token + }) { + return Err(LocalError::InvalidTarget); + } + } + Ok(()) + }; + if valid().is_err() { + incomplete.push(watch.path.clone()); + continue; + } + if !std::path::Path::new(&watch.path).is_dir() { + continue; + } + let normalized = gamenode_core::provider::path::normalize(&watch.path); if !std::path::Path::new(&watch.path).is_dir() { continue; } - let normalized = - gamenode_core::provider::path::normalize(&watch.path).to_lowercase(); + let normalized = if cfg!(windows) + || gamenode_core::provider::path::is_windows_style(&normalized) + { + normalized.to_lowercase() + } else { + normalized + }; if scanned_roots.iter().any(|root| { let sep = if gamenode_core::provider::path::is_windows_style(root) { '\\' @@ -2116,32 +2211,54 @@ impl Engine { }) { continue; } - scanned_roots.push(normalized); - checked_ids.push(watch.id.clone()); - let found = match gamenode_platform::discovery::WindowsDiscovery - .discover(&watch, &engine.shared.local_cancel) - { + if contribution.is_none() { + checked_ids.push(watch.id.clone()); + } + let scanner = engine + .shared + .ports + .discovery + .as_deref() + .unwrap_or(&gamenode_platform::discovery::WindowsDiscovery); + let found = match scanner.discover(&watch, &engine.shared.local_cancel) { Ok(found) => found, Err(LocalError::Unsupported) if engine.shared.ports.installations.is_some() => { DiscoveryReport::default() } - Err(error) => return Err(error), + Err(error) => { + failure.get_or_insert(error); + incomplete.push(watch.path.clone()); + continue; + } }; + if valid().is_err() { + incomplete.push(watch.path.clone()); + continue; + } if found.incomplete { incomplete.push(watch.path.clone()); + } else { + scanned_roots.push(normalized); } - for title in engine.auto_register_candidates(found.candidates)? { + let titles = + match engine.auto_register_candidates_checked(found.candidates, &valid) { + Ok(titles) => titles, + Err(error) => { + failure.get_or_insert(error); + continue; + } + }; + for title in titles { if !added_titles.contains(&title) { added_titles.push(title); } } } engine.lock().local.discovery_incomplete = incomplete; - Ok::<_, LocalError>(checked_ids) + failure.map_or(Ok(()), Err) })(); - let checked_ids = result.clone().unwrap_or_default(); { let mut state = engine.lock(); for title in &added_titles { diff --git a/crates/app/src/engine/drm_free/suggestions.rs b/crates/app/src/engine/drm_free/suggestions.rs index b084e688a..e26853748 100644 --- a/crates/app/src/engine/drm_free/suggestions.rs +++ b/crates/app/src/engine/drm_free/suggestions.rs @@ -291,7 +291,7 @@ impl Engine { return; } StepOutcome::Rejected => { - engine.check_rejected(true); + engine.check_rejected(true).await; return; } } diff --git a/crates/app/src/engine/mod.rs b/crates/app/src/engine/mod.rs index 9cde495eb..495fd7ed0 100644 --- a/crates/app/src/engine/mod.rs +++ b/crates/app/src/engine/mod.rs @@ -32,14 +32,17 @@ use tokio::runtime::Handle; mod achievements; mod artwork; +mod detected_target; mod drm_free; pub mod pc_ports; mod playtime; +mod plugin_ports; mod providers; mod sign_in; mod tools; pub use pc_ports::{PortProgressPublisher, PortsService}; +pub use providers::{ExtensionReadinessChoice, ExtensionReadinessSelection}; /// Longest the app waits for the server to confirm a sign-out. const REMOTE_SIGN_OUT_TIMEOUT: Duration = Duration::from_secs(5); @@ -76,6 +79,68 @@ pub enum GameNodePageError { Browser, } +/// A human summary of what a recipe would execute, using the host-owned runtime template and the +/// game's detected ROM name. No path, handle or recipe id is included. +fn runtime_launch_summary( + runtime: Option<&gamenode_core::library::RuntimeResource>, + recipe: &gamenode_core::library::CustomLaunchRecipe, + content_name: &str, +) -> String { + let Some(runtime) = runtime else { + return String::new(); + }; + let content = if content_name.trim().is_empty() { + "".to_owned() + } else { + content_name.trim().to_owned() + }; + let mut arguments = Vec::new(); + for argument in &runtime.launch_arguments { + match argument { + gamenode_core::library::RuntimeArgumentTemplate::Literal(value) => { + arguments.push(value.clone()); + } + gamenode_core::library::RuntimeArgumentTemplate::ContentPath => { + arguments.push(content.clone()); + } + } + } + arguments.extend(recipe.arguments.iter().cloned()); + let name = if runtime.version.trim().is_empty() { + runtime.name.clone() + } else { + format!("{} {}", runtime.name, runtime.version) + }; + if arguments.is_empty() { + name + } else { + format!("{} — {}", name, arguments.join(" ")) + } +} + +/// A recipe the authenticated plugin profile currently exposes for a matched library game. +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct LaunchRecipeOption { + pub plugin_id: String, + pub publisher_fingerprint: String, + pub recipe_id: String, + pub recipe_revision: u64, + /// Human-readable runtime/version and argument summary, never opaque recipe ids. + #[serde(default)] + pub summary: String, +} + +/// Selection state shown beside one library entry's detected launch target. +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct LaunchRecipeChoices { + pub target_revision: u64, + pub detected_default_available: bool, + pub selected: Option, + pub recipes: Vec, +} + /// Why a provider's achievements page could not be opened. The code is stable; the UI words the /// message and never receives or passes the URL itself. #[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize)] @@ -93,6 +158,7 @@ const COVER_FLUSH_INTERVAL: Duration = Duration::from_millis(300); /// The adapters the engine drives. #[derive(Clone)] pub struct Ports { + pub discovery: Option>, pub backups: Option>, pub local_games: Option>, pub installations: Option>, @@ -135,6 +201,36 @@ fn unix_now() -> i64 { }) } +fn validate_user_launch_authority( + profiles: &crate::plugin_host::profile::PluginProfiles, + authority: &crate::plugin_host::library::UserLaunchAuthority, +) -> Result<(), tonic::Status> { + let current = profiles.require()?; + if !current.verified() + || current.epoch() != authority.profile_epoch + || current.profile_id() != authority.profile_id + || !profiles.is_enabled(&authority.plugin_id)? + { + return Err(tonic::Status::permission_denied( + "plugin profile or activation changed", + )); + } + let (revision, grants) = + profiles.granted_permissions(&authority.plugin_id, &authority.publisher_fingerprint)?; + if authority + .grant_revision + .is_some_and(|expected| revision != expected) + || !grants.contains(gamenode_plugin_protocol::capability::GAME_CUSTOM_LAUNCH) + || (authority.requires_files + && !grants.contains(gamenode_plugin_protocol::capability::FILES_READ)) + { + return Err(tonic::Status::permission_denied( + "plugin launch permission changed", + )); + } + Ok(()) +} + type Job = Box; /// Runs blocking storage jobs one at a time, in submission order. @@ -196,6 +292,7 @@ struct State { Instant, >, tool_selected_target_exe: Option, + plugin_tool_request: Option, playtime: playtime::Playtime, machine: AuthMachine, settings: Settings, @@ -215,6 +312,7 @@ struct State { published_selection: Option>, /// The PC ports projection built by the service on a worker thread. ports_view: gamenode_core::ports::PortsView, + plugin_port_request: Option, /// Cached achievement summaries for the connected store accounts. achievement_summaries: std::collections::BTreeMap< (String, String), @@ -238,6 +336,8 @@ struct Shared { /// Without it, a refresh that read the store before a write can apply after a newer /// view and temporarily hide registrations or inferences from the snapshot. local_views: Mutex<()>, + plugin_scan_roots: + Mutex>>, ports: Ports, runtime: Handle, storage: StorageWorker, @@ -248,6 +348,17 @@ struct Shared { #[cfg(test)] autostart_hook: Mutex>, providers: Mutex>>, + /// Third-party plugin profiles follow the signed-in GameNode account. + plugin_profiles: Mutex>>, + /// Shared host resource adapter used for user-initiated custom Play selections. + selected_launch_api: Mutex>>, + /// Owns reviewed custom launches and their shared-resource leases off the UI thread. + #[cfg(any(target_os = "linux", windows))] + custom_launch_supervisor: Option>, + #[cfg(any(target_os = "linux", windows))] + custom_launch_leases: Arc, + /// The library projection plugins read through `ResourceHost`. + library_feed: Mutex>>, /// Serialize checks and catalog commits without delaying account cancellation. provider_checks: Mutex>>>, /// One catalog sync per provider, coalescing requests made while one runs. @@ -280,6 +391,17 @@ struct CatalogSync { } /// Cheap to clone; all clones share one state. +/// Why [`Engine::open_entry_then`] did not hand the entry's link to the operating system. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) enum OpenError { + /// The same opening is under way, or the game is already running. + Busy, + /// The entry or its provider is not in the library any more. + NotFound, + /// The provider's action could not run. + Launch(gamenode_core::library::LaunchError), +} + #[derive(Clone)] pub struct Engine { shared: Arc, @@ -295,8 +417,11 @@ impl Engine { settings: Settings, library: LibraryMachine, nonce: NonceSource, + custom_launch_leases: Arc, publish: impl Fn(Snapshot) + Send + Sync + 'static, ) -> Self { + #[cfg(not(any(target_os = "linux", windows)))] + let _ = custom_launch_leases; #[cfg(test)] let test_runtime = Arc::new(tests::provider_runtime::Runtime::new(&ports)); let mut library = library; @@ -330,6 +455,7 @@ impl Engine { tool_reset_config: false, tool_last_fetch: Default::default(), tool_selected_target_exe: None, + plugin_tool_request: None, playtime: playtime::Playtime::new(ports.platform), machine: AuthMachine::new(nonce), settings, @@ -342,6 +468,7 @@ impl Engine { library_loading: false, published_selection: None, ports_view: gamenode_core::ports::PortsView::default(), + plugin_port_request: None, achievement_summaries: Default::default(), achievement_language: crate::commands::normalize_locale( &crate::commands::system_locale(), @@ -349,6 +476,7 @@ impl Engine { .to_owned(), }), local_views: Mutex::new(()), + plugin_scan_roots: Mutex::default(), ports, runtime, storage: StorageWorker::new(), @@ -356,6 +484,14 @@ impl Engine { #[cfg(test)] autostart_hook: Mutex::new(None), providers: Mutex::new(None), + plugin_profiles: Mutex::new(None), + selected_launch_api: Mutex::new(None), + #[cfg(any(target_os = "linux", windows))] + custom_launch_supervisor: + crate::plugin_host::launch_supervisor::LaunchSupervisor::start_monitor().ok(), + #[cfg(any(target_os = "linux", windows))] + custom_launch_leases, + library_feed: Mutex::new(None), provider_checks: Mutex::new(std::collections::HashMap::new()), catalog_syncs: Mutex::new(std::collections::HashMap::new()), local_checking: Mutex::new(std::collections::BTreeSet::new()), @@ -389,7 +525,9 @@ impl Engine { pc_ports::PortsEvent::Changed { view, completion } => { { let mut state = self.lock(); + let review = state.ports_view.plugin_request.clone(); state.ports_view = view; + state.ports_view.plugin_request = review; self.publish(&mut state); } if let Some(completion) = completion { @@ -407,7 +545,7 @@ impl Engine { /// Publishes the current state without holding any adapter lock. Used by the provider status /// observer, which runs from whichever background thread changed the account. - fn publish_current(&self) { + pub(crate) fn publish_current(&self) { let mut state = self.lock(); self.publish(&mut state); } @@ -620,9 +758,284 @@ impl Engine { } fn publish(&self, state: &mut State) { + self.sync_library_feed(state); (self.shared.publish)(self.snapshot_of(state)); } + /// Feeds the plugin library projection. Plugins see the entries the library shows while an + /// account's library is open, each with its current GameNode match; never a store id, path + /// or scan field. An entry stays hidden until the storage worker has given it a durable + /// installation id, so an id a plugin saw never changes. + fn sync_library_feed(&self, state: &State) { + use crate::plugin_host::library::{InstallState, LibrarySource}; + let Some(feed) = self + .shared + .library_feed + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .clone() + else { + return; + }; + let library = &state.library; + let sources = if library.is_active() { + library + .visible_entries() + .map(|entry| { + let game_id = library.match_status(entry).game_id(); + LibrarySource { + entry_key: entry.key.clone(), + provider_id: entry.provider.clone(), + game_id, + name: entry + .name + .clone() + .filter(|name| !name.trim().is_empty()) + .or_else(|| { + game_id + .and_then(|id| library.game(id)) + .map(|g| g.name.clone()) + }) + .unwrap_or_default(), + display_name: library + .display_override(&entry.key) + .and_then(|over| over.display_name.clone()), + metadata_revision: library + .display_override(&entry.key) + .map_or(0, |over| over.revision), + artwork_revision: library + .artwork_override(&entry.key) + .map_or(0, |over| over.revision), + install_dir: entry.install_dir.clone(), + detected_target: entry + .target + .as_ref() + .map(|target| (target.revision, target.approved, target.available)), + install_state: if entry.installed { + InstallState::Installed + } else if entry.owned { + InstallState::Owned + } else { + InstallState::Shared + }, + } + }) + .collect() + } else { + Vec::new() + }; + let missing = feed.sync(sources); + if missing.is_empty() { + return; + } + let store = self.shared.ports.library.clone(); + self.shared + .storage + .submit(move || match store.installation_ids(&missing) { + Ok(ids) => feed.assign_ids(&missing, ids), + Err(error) => { + tracing::warn!(%error, "could not assign library installation ids"); + feed.ids_failed(&missing); + } + }); + } + + /// Connects the plugin library projection and its write side, and fills the projection from + /// the current library. + pub fn set_library_feed(&self, feed: Arc) { + feed.set_host(Arc::new(PluginLibraryHost { + shared: Arc::downgrade(&self.shared), + })); + *self + .shared + .library_feed + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(feed); + let state = self.lock(); + self.sync_library_feed(&state); + } + + pub fn set_selected_launch_api(&self, api: Arc) { + *self + .shared + .selected_launch_api + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(api); + } + + async fn launch_authorized_uri( + &self, + uri: url::Url, + arguments: Vec, + working_directory: String, + environment: gamenode_core::drm_free::LaunchEnvironmentDelta, + authority: crate::plugin_host::library::UserLaunchAuthority, + ) -> Result<(), tonic::Status> { + let profiles = self + .shared + .plugin_profiles + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .clone() + .ok_or_else(|| tonic::Status::unavailable("plugin profile is unavailable"))?; + let opener = Arc::clone(&self.shared.ports.uri); + tokio::task::spawn_blocking(move || { + let _transition = profiles.lock_transition(); + validate_user_launch_authority(&profiles, &authority)?; + opener + .open_custom(&uri, &arguments, &working_directory, &environment) + .map_err(|error| match error { + gamenode_core::ports::UriError::NoHandler => { + tonic::Status::failed_precondition("no application handles this launch URI") + } + gamenode_core::ports::UriError::Unsupported => tonic::Status::unimplemented( + "the URI handler cannot apply custom launch fields", + ), + gamenode_core::ports::UriError::Failed => { + tonic::Status::unavailable("the launch URI failed") + } + }) + }) + .await + .map_err(|_| tonic::Status::unavailable("custom launch worker stopped"))? + } + + /// Starts a reviewed executable on a worker and returns its host-owned launch identity. + /// The caller supplies only resource keys resolved by the host, never plugin-provided keys. + #[cfg(any(target_os = "linux", windows))] + pub(crate) async fn start_supervised_custom_launch( + &self, + command: gamenode_core::drm_free::CustomLaunchCommand, + keys: Vec, + entry_key: Option, + authority: Option, + ) -> Result { + let supervisor = self + .shared + .custom_launch_supervisor + .clone() + .ok_or_else(|| tonic::Status::unavailable("custom launch supervisor is unavailable"))?; + let leases = Arc::clone(&self.shared.custom_launch_leases); + let installations = self.shared.ports.installations.clone().ok_or_else(|| { + tonic::Status::unimplemented("custom executable launch is unavailable") + })?; + let profiles = self + .shared + .plugin_profiles + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .clone(); + tokio::task::spawn_blocking(move || { + // Persisted permission changes and profile transitions take this same lock. A + // revocation that commits first must prevent spawn, while a revocation after spawn + // must leave the already-running game alone. + let _transition = match (&authority, &profiles) { + (Some(_), Some(profiles)) => Some(profiles.lock_transition()), + (Some(_), None) => { + return Err(tonic::Status::unavailable("plugin profile is unavailable")); + } + (None, _) => None, + }; + if let Some(authority) = &authority { + validate_user_launch_authority( + profiles.as_ref().expect("authority requires profiles"), + authority, + )?; + } + let inspected = installations.inspect(&command.executable).map_err(|_| { + tonic::Status::failed_precondition("approved executable cannot be inspected") + })?; + if inspected.file_identity != command.file_identity + || !std::fs::canonicalize(&command.working_directory) + .is_ok_and(|path| path.is_dir()) + || !command.environment.validate() + { + return Err(tonic::Status::failed_precondition( + "approved launch inputs changed", + )); + } + supervisor + .start_for_entry(leases.as_ref(), &keys, entry_key, || { + // Repeat identity inspection after reserving resources and immediately before + // handing the command to the OS. Failed inspection must never spawn a process. + let valid = installations + .inspect(&command.executable) + .is_ok_and(|current| current.file_identity == command.file_identity); + if valid { + crate::plugin_host::launch_supervisor::spawn_native(&command) + } else { + crate::plugin_host::launch_supervisor::SpawnOutcome::NotStarted + } + }) + .map_err(|error| match error { + crate::plugin_host::resource_leases::ResourceLeaseError::Busy => { + tonic::Status::failed_precondition("a shared resource is busy") + } + crate::plugin_host::resource_leases::ResourceLeaseError::Unknown => { + tonic::Status::unavailable("custom launch could not be confirmed") + } + }) + }) + .await + .map_err(|_| tonic::Status::unavailable("custom launch worker stopped"))? + } + + /// Explicitly terminates and fences a previously supervised launch on a worker. + #[cfg(any(target_os = "linux", windows))] + pub async fn stop_supervised_custom_launch(&self, id: u64) -> Result<(), tonic::Status> { + let supervisor = self + .shared + .custom_launch_supervisor + .clone() + .ok_or_else(|| tonic::Status::unavailable("custom launch supervisor is unavailable"))?; + tokio::task::spawn_blocking(move || supervisor.stop(id)) + .await + .map_err(|_| tonic::Status::unavailable("custom launch worker stopped"))? + .map(|_| ()) + .map_err(|_| { + tonic::Status::unavailable("custom launch termination could not be confirmed") + }) + } + + /// Returns identifiers for running or indeterminate reviewed custom launches. + #[cfg(any(target_os = "linux", windows))] + pub async fn supervised_custom_launch_ids(&self) -> Result, tonic::Status> { + let supervisor = self + .shared + .custom_launch_supervisor + .clone() + .ok_or_else(|| tonic::Status::unavailable("custom launch supervisor is unavailable"))?; + tokio::task::spawn_blocking(move || supervisor.active_ids()) + .await + .map_err(|_| tonic::Status::unavailable("custom launch worker stopped"))? + .map_err(|_| tonic::Status::unavailable("custom launch state is unavailable")) + } + + /// Finds supervised launches belonging to a specific library entry. + #[cfg(any(target_os = "linux", windows))] + pub async fn supervised_custom_launch_ids_for_entry( + &self, + entry_key: String, + ) -> Result, tonic::Status> { + let supervisor = self + .shared + .custom_launch_supervisor + .clone() + .ok_or_else(|| tonic::Status::unavailable("custom launch supervisor is unavailable"))?; + tokio::task::spawn_blocking(move || supervisor.ids_for_entry(&entry_key)) + .await + .map_err(|_| tonic::Status::unavailable("custom launch worker stopped"))? + .map_err(|_| tonic::Status::unavailable("custom launch state is unavailable")) + } + + /// Returns the same host-owned coordinator used by launches for backup/restore integration. + #[cfg(all(test, any(target_os = "linux", windows)))] + pub(crate) fn shared_resource_leases( + &self, + ) -> Arc { + Arc::clone(&self.shared.custom_launch_leases) + } + /// Reads the last signed-in account, then the stored session and, if there is one, /// validates it. The account is read first so the cached library can open while the session /// is still being verified. @@ -766,8 +1179,25 @@ impl Engine { self.sync_provider_catalog(op, provider.to_owned()).await; } - /// Feeds an input to the state machine and launches its effects. Never blocks on I/O. + /// Feeds an input to the state machine and launches its effects on a worker. An account + /// transition can wait for an in-flight shared-data policy commit. + pub async fn dispatch_on_worker(&self, input: Input) { + let engine = self.clone(); + if let Err(error) = tokio::task::spawn_blocking(move || engine.dispatch(input)).await { + tracing::error!(%error, "auth dispatch worker failed"); + } + } + + /// Called by blocking workers and tests. Take the profile transition lock before the engine + /// lock so unrelated UI work can read the engine state while a policy commit is syncing. pub fn dispatch(&self, input: Input) { + let profiles = self + .shared + .plugin_profiles + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .clone(); + let transition = profiles.as_ref().map(|profiles| profiles.lock_transition()); let mut state = self.lock(); let is_tick = matches!(&input, Input::Tick); let auth_before = is_tick.then(|| (state.machine.state().clone(), state.machine.notice())); @@ -789,7 +1219,7 @@ impl Engine { for effect in effects { self.execute(effect); } - self.sync_library(&mut state); + self.sync_library(&mut state, transition); self.sync_tracker(&mut state); if submit_trigger { self.submit_totals(&mut state); @@ -1013,67 +1443,364 @@ impl Engine { /// Opens the provider's Play or Install link for an entry. The result appears in the /// snapshot's `launch`: "opening" until the operating system accepted the link. pub fn open_entry(&self, entry_key: String, kind: LaunchKind) { + self.open_entry_then(entry_key, kind, |_| {}); + } + + /// Loads active recipe choices for a matched game without blocking the UI thread. + pub async fn launch_recipe_choices( + &self, + entry_key: String, + ) -> Result { + let (game_id, target_revision, detected_default_available, content_name) = { + let state = self.lock(); + let entry = state + .library + .entry(&entry_key) + .ok_or_else(|| "library entry is unavailable".to_owned())?; + let game_id = state.library.match_status(entry).game_id().ok_or_else(|| { + "choose a GameNode game before selecting a launch recipe".to_owned() + })?; + let target = entry.target.as_ref(); + let content_name = entry + .fields + .get("rom") + .cloned() + .or_else(|| entry.name.clone()) + .unwrap_or_default(); + ( + game_id, + target.map_or(0, |target| target.revision), + target.is_some_and(|target| target.available), + content_name, + ) + }; + let profiles = self + .shared + .plugin_profiles + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .clone() + .ok_or_else(|| "plugin profiles are unavailable".to_owned())?; + let store = self.shared.ports.library.clone(); + tokio::task::spawn_blocking(move || { + let selection = store + .launch_recipe_selection(&entry_key) + .map_err(|error| error.to_string())?; + let identities = profiles.identities().map_err(|error| error.to_string())?; + let mut recipes = Vec::new(); + for identity in identities { + if !profiles + .is_enabled(&identity.plugin_id) + .map_err(|error| error.to_string())? + { + continue; + } + let resolver = profiles + .resolver(&identity.plugin_id, &identity.publisher_fingerprint, None) + .map_err(|error| error.to_string())?; + let owner_key = resolver.library_recipe_owner_key(); + for recipe in store + .custom_launch_recipes(&owner_key, game_id) + .map_err(|error| error.to_string())? + { + if recipe.base_target_revision == target_revision && recipe.validate() { + let runtime = store + .runtime_resource(&owner_key, &recipe.runtime_handle) + .ok() + .flatten(); + let summary = + runtime_launch_summary(runtime.as_ref(), &recipe, &content_name); + recipes.push(LaunchRecipeOption { + plugin_id: identity.plugin_id.clone(), + publisher_fingerprint: identity.publisher_fingerprint.clone(), + recipe_id: recipe.recipe_id, + recipe_revision: recipe.revision, + summary, + }); + } + } + } + recipes.sort_by(|left, right| { + (&left.plugin_id, &left.recipe_id).cmp(&(&right.plugin_id, &right.recipe_id)) + }); + Ok(LaunchRecipeChoices { + target_revision, + detected_default_available, + selected: selection, + recipes, + }) + }) + .await + .map_err(|_| "launch recipe worker stopped".to_owned())? + } + + /// Selects an authenticated plugin recipe only while its game and detected target revisions + /// still match the current library entry. + pub async fn select_launch_recipe( + &self, + entry_key: String, + plugin_id: String, + publisher_fingerprint: String, + recipe_id: String, + recipe_revision: u64, + expected_target_revision: u64, + ) -> Result<(), String> { + let (game_id, target_revision) = { + let state = self.lock(); + let entry = state + .library + .entry(&entry_key) + .ok_or_else(|| "library entry is unavailable".to_owned())?; + let game_id = state.library.match_status(entry).game_id().ok_or_else(|| { + "choose a GameNode game before selecting a launch recipe".to_owned() + })?; + let target_revision = entry.target.as_ref().map_or(0, |target| target.revision); + (game_id, target_revision) + }; + if target_revision != expected_target_revision { + return Err("the detected target changed; refresh launch choices".into()); + } + let profiles = self + .shared + .plugin_profiles + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .clone() + .ok_or_else(|| "plugin profiles are unavailable".to_owned())?; + let store = self.shared.ports.library.clone(); + tokio::task::spawn_blocking(move || { + use gamenode_core::library::{LaunchRecipeSelection, LaunchRecipeSelectionWrite}; + + let identity = profiles + .identities() + .map_err(|error| error.to_string())? + .into_iter() + .find(|identity| { + identity.plugin_id == plugin_id + && identity.publisher_fingerprint == publisher_fingerprint + }) + .ok_or_else(|| { + "plugin identity is not authenticated for this profile".to_owned() + })?; + if !profiles + .is_enabled(&identity.plugin_id) + .map_err(|error| error.to_string())? + { + return Err("the recipe's plugin is disabled".into()); + } + let resolver = profiles + .resolver(&identity.plugin_id, &identity.publisher_fingerprint, None) + .map_err(|error| error.to_string())?; + let owner_key = resolver.library_recipe_owner_key(); + let recipe = store + .custom_launch_recipes(&owner_key, game_id) + .map_err(|error| error.to_string())? + .into_iter() + .find(|recipe| { + recipe.recipe_id == recipe_id + && recipe.revision == recipe_revision + && recipe.base_target_revision == expected_target_revision + && recipe.validate() + }) + .ok_or_else(|| { + "the selected recipe changed or is no longer available".to_owned() + })?; + let selection = LaunchRecipeSelection { + entry_key: entry_key.clone(), + owner_key, + plugin_id: identity.plugin_id, + publisher_fingerprint: identity.publisher_fingerprint, + recipe_id: recipe.recipe_id, + recipe_revision: recipe.revision, + base_target_revision: expected_target_revision, + approved_plan_fingerprint: String::new(), + }; + match store + .save_launch_recipe_selection(&selection, expected_target_revision) + .map_err(|error| error.to_string())? + { + LaunchRecipeSelectionWrite::Applied => Ok(()), + LaunchRecipeSelectionWrite::Conflict => { + Err("the detected target or recipe changed; refresh launch choices".into()) + } + LaunchRecipeSelectionWrite::RecipeMissing => { + Err("the selected recipe is no longer available".into()) + } + } + }) + .await + .map_err(|_| "launch recipe worker stopped".to_owned())? + } + + /// Clears a custom recipe so the detected default is selected explicitly. + pub async fn use_detected_default( + &self, + entry_key: String, + expected_target_revision: u64, + ) -> Result<(), String> { + let current_revision = { + let state = self.lock(); + let entry = state + .library + .entry(&entry_key) + .ok_or_else(|| "library entry is unavailable".to_owned())?; + entry.target.as_ref().map_or(0, |target| target.revision) + }; + if current_revision != expected_target_revision { + return Err("the detected target changed; refresh launch choices".into()); + } + let store = self.shared.ports.library.clone(); + tokio::task::spawn_blocking(move || { + match store + .clear_launch_recipe_selection(&entry_key, expected_target_revision) + .map_err(|error| error.to_string())? + { + gamenode_core::library::LaunchRecipeSelectionWrite::Applied => Ok(()), + gamenode_core::library::LaunchRecipeSelectionWrite::Conflict => { + Err("the detected target changed; refresh launch choices".into()) + } + gamenode_core::library::LaunchRecipeSelectionWrite::RecipeMissing => { + Err("library entry is unavailable".into()) + } + } + }) + .await + .map_err(|_| "launch recipe worker stopped".to_owned())? + } + + /// [`open_entry`](Self::open_entry) that also reports how it ended to `done`, which runs + /// exactly once: on the worker when the link was handled, or at once when nothing was + /// started (the same opening is already under way, the game is already running, or the + /// entry is gone). + pub(crate) fn open_entry_then( + &self, + entry_key: String, + kind: LaunchKind, + done: impl FnOnce(Result<(), OpenError>) + Send + 'static, + ) { let mut state = self.lock(); if state.launch.as_ref().is_some_and(|launch| { launch.entry_key == entry_key && launch.kind == kind && matches!(launch.state, LaunchState::Opening) }) { - return; + drop(state); + return done(Err(OpenError::Busy)); } if kind == LaunchKind::Play && state.playtime.tracker.running().contains(&entry_key) { - return; + drop(state); + return done(Err(OpenError::Busy)); } let Some(entry) = state.library.entry(&entry_key).cloned() else { - return; + drop(state); + return done(Err(OpenError::NotFound)); }; let Some(provider) = state.library.provider(&entry.provider).cloned() else { - return; + drop(state); + return done(Err(OpenError::NotFound)); }; state.launch_seq += 1; let seq = state.launch_seq; state.launch = Some(LaunchStatus { - entry_key, + entry_key: entry_key.clone(), kind, state: LaunchState::Opening, }); self.publish(&mut state); let (engine, opener) = (self.clone(), self.shared.ports.uri.clone()); - self.shared.runtime.spawn_blocking(move || { - let result = if provider.is_manual_executable() { - if kind != LaunchKind::Play { - Err(gamenode_core::library::LaunchError::Unsupported) - } else { - engine + self.shared.runtime.spawn(async move { + let selection_store = engine.shared.ports.library.clone(); + let selection_key = entry_key.clone(); + let selection = if kind == LaunchKind::Play { + tokio::task::spawn_blocking(move || { + selection_store.launch_recipe_selection(&selection_key) + }) + .await + .map_err(|_| gamenode_core::library::LaunchError::Failed) + .and_then(|result| result.map_err(|_| gamenode_core::library::LaunchError::Failed)) + } else { + Ok(None) + }; + let run_detected = { + let engine = engine.clone(); + let opener = opener.clone(); + let entry = entry.clone(); + let provider = provider.clone(); + move || { + if kind == LaunchKind::Play + && let Some(target) = entry.target.as_ref() + { + detected_target::launch(&engine, &entry, target) + } else if provider.is_manual_executable() { + if kind != LaunchKind::Play { + Err(gamenode_core::library::LaunchError::Unsupported) + } else { + engine + .shared + .ports + .local_games + .as_ref() + .zip(engine.shared.ports.installations.as_ref()) + .ok_or(gamenode_core::library::LaunchError::Unsupported) + .and_then(|(store, host)| { + let registrations = store + .registrations() + .map_err(|_| gamenode_core::library::LaunchError::Failed)?; + let registration = registrations + .iter() + .find(|r| r.key() == entry.key && !r.removed) + .ok_or(gamenode_core::library::LaunchError::Incomplete)?; + let environment = + engine.port_launch_environment(®istration.id); + gamenode_core::library::launch::launch_manual_with_environment( + &**host, + &provider, + &entry.record(), + registration, + &environment, + kind, + ) + }) + } + } else { + open_action(&*opener, &provider, &entry.record(), kind) + } + } + }; + let result = match selection { + Err(error) => Err(error), + Ok(Some(_)) => { + let api = engine .shared - .ports - .local_games - .as_ref() - .zip(engine.shared.ports.installations.as_ref()) - .ok_or(gamenode_core::library::LaunchError::Unsupported) - .and_then(|(store, host)| { - let registrations = store - .registrations() - .map_err(|_| gamenode_core::library::LaunchError::Failed)?; - let registration = registrations - .iter() - .find(|r| r.key() == entry.key && !r.removed) - .ok_or(gamenode_core::library::LaunchError::Incomplete)?; - let environment = engine.port_launch_environment(®istration.id); - gamenode_core::library::launch::launch_manual_with_environment( - &**host, - &provider, - &entry.record(), - registration, - &environment, - kind, - ) - }) + .selected_launch_api + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .clone(); + match api { + Some(api) => match api.launch_selected_recipe(entry_key).await { + Ok(true) => Ok(()), + Ok(false) => Ok(()), + Err(status) => Err(match status.code() { + tonic::Code::Unimplemented => { + gamenode_core::library::LaunchError::Unsupported + } + tonic::Code::FailedPrecondition + | tonic::Code::PermissionDenied + | tonic::Code::NotFound => { + gamenode_core::library::LaunchError::RecipeNeedsAttention + } + _ => gamenode_core::library::LaunchError::Failed, + }), + }, + None => Err(gamenode_core::library::LaunchError::RecipeNeedsAttention), + } } - } else { - open_action(&*opener, &provider, &entry.record(), kind) + Ok(None) => tokio::task::spawn_blocking(run_detected) + .await + .unwrap_or(Err(gamenode_core::library::LaunchError::Failed)), }; let mut state = engine.lock(); + let outcome = result.clone().map_err(OpenError::Launch); if state.launch_seq == seq { state.launch = result.err().map(|error| LaunchStatus { state: LaunchState::Failed(error), @@ -1081,6 +1808,8 @@ impl Engine { }); engine.publish(&mut state); } + drop(state); + done(outcome); }); } @@ -1092,10 +1821,28 @@ impl Engine { self.publish(&mut state); } + /// Binds third-party plugin profiles to who is signed in. The engine applies the same account + /// it opens the library for, so plugins see the cached last account while a restored session + /// is unverified, and no profile at all after sign-out or a rejected session. + pub fn set_plugin_profiles(&self, profiles: Arc) { + let transition = profiles.lock_transition(); + *self + .shared + .plugin_profiles + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(profiles.clone()); + let mut state = self.lock(); + self.sync_library(&mut state, Some(transition)); + } + /// Brings the library in line with who is signed in: opens the cached library of the last /// account while the session is being verified, enables GameNode features once it is, and /// closes the library on sign-out or a rejected session. - fn sync_library(&self, state: &mut State) { + fn sync_library( + &self, + state: &mut State, + transition: Option>, + ) { let (account, access) = match state.machine.state() { AuthState::SignedIn(user) => ( Some(LastAccount { @@ -1111,6 +1858,12 @@ impl Engine { // Nothing is known yet, or a different session is being set up. AuthState::Starting | AuthState::Pending { .. } | AuthState::Verifying(_) => return, }; + if let Some(transition) = transition { + transition.update( + account.as_ref().map(|account| account.id.as_str()), + access == Access::Verified, + ); + } match &account { Some(account) if state.last_account.as_ref() != Some(account) => { state.last_account = Some(account.clone()); @@ -1177,9 +1930,9 @@ impl Engine { } /// A `401` on a library request is a rejected session, like a failed session check. - fn check_rejected(&self, rejected: bool) { + async fn check_rejected(&self, rejected: bool) { if rejected { - self.dispatch(Input::SessionRejected); + self.dispatch_on_worker(Input::SessionRejected).await; } } @@ -1206,6 +1959,7 @@ impl Engine { }); let Some(found) = state.library.provider(&provider).cloned() else { self.later(LibInput::ProviderScanned { + targets: Default::default(), op, provider, result: Err("unknown provider".to_owned()), @@ -1221,6 +1975,7 @@ impl Engine { self.scan_provider(runtime, found, op, provider); } else { self.later(LibInput::ProviderScanned { + targets: Default::default(), op, provider, result: Err("provider plugin is unavailable".to_owned()), @@ -1258,6 +2013,7 @@ impl Engine { .map_err(|error| error.to_string()) }; engine.library_input(LibInput::ProviderScanned { + targets: Default::default(), op, provider, result, @@ -1270,7 +2026,9 @@ impl Engine { outcome, now, } => self.persist(move |store| match outcome { - ScanOutcome::Scanned(records) => store.save_scan(&provider, &records, now), + ScanOutcome::Scanned { records, targets } => { + store.save_scan(&provider, &records, &targets, now) + } ScanOutcome::Failed(error) => store.save_scan_failure(&provider, &error), }), // The account service validates the session (persisting a rotated cookie) and fetches @@ -1336,7 +2094,7 @@ impl Engine { result, now: unix_now(), }); - engine.check_rejected(rejected); + engine.check_rejected(rejected).await; }); } LibEffect::PushFavorite { @@ -1364,7 +2122,7 @@ impl Engine { result, now: unix_now(), }); - engine.check_rejected(rejected); + engine.check_rejected(rejected).await; }); } LibEffect::PersistExcluded(excluded) => { @@ -1406,7 +2164,7 @@ impl Engine { result, now: unix_now(), }); - engine.check_rejected(rejected); + engine.check_rejected(rejected).await; }); } LibEffect::SearchGames { op, query } => { @@ -1421,7 +2179,7 @@ impl Engine { let result = api.search_games(&credential, &query).await; let rejected = matches!(result, Err(ApiError::Rejected)); engine.library_input(LibInput::MatchSearched { op, result }); - engine.check_rejected(rejected); + engine.check_rejected(rejected).await; }); } LibEffect::SuggestMatches { op, key, query } => { @@ -1437,7 +2195,7 @@ impl Engine { let result = api.search_page(&credential, &query).await; let rejected = matches!(result, Err(ApiError::Rejected)); engine.library_input(LibInput::SuggestionsFound { op, key, result }); - engine.check_rejected(rejected); + engine.check_rejected(rejected).await; }); } LibEffect::CatalogSearch { op, query } => { @@ -1453,7 +2211,7 @@ impl Engine { let result = api.search_page(&credential, &query).await; let rejected = matches!(result, Err(ApiError::Rejected)); engine.library_input(LibInput::CatalogSearchDone { op, query, result }); - engine.check_rejected(rejected); + engine.check_rejected(rejected).await; }); } LibEffect::FetchCover { game_id, url } => { @@ -1491,7 +2249,7 @@ impl Engine { game_id, result, }); - engine.check_rejected(rejected); + engine.check_rejected(rejected).await; }); } LibEffect::ReadEntry { op, game_id } => { @@ -1511,7 +2269,7 @@ impl Engine { game_id, result, }); - engine.check_rejected(rejected); + engine.check_rejected(rejected).await; }); } LibEffect::SyncAccountLibrary { op, user_id } => { @@ -1539,7 +2297,7 @@ impl Engine { result, now: unix_now(), }); - engine.check_rejected(rejected); + engine.check_rejected(rejected).await; }); } LibEffect::PersistAccountLibrary { @@ -1569,7 +2327,7 @@ impl Engine { let result = api.list_collections(&credential, &user_id).await; let rejected = matches!(result, Err(ApiError::Rejected)); engine.library_input(LibInput::CollectionsListed { op, result }); - engine.check_rejected(rejected); + engine.check_rejected(rejected).await; }); } LibEffect::CreateCollection { op, name, .. } => { @@ -1584,7 +2342,7 @@ impl Engine { let result = api.create_collection(&credential, &name).await; let rejected = matches!(result, Err(CreateCollectionError::Rejected)); engine.library_input(LibInput::CollectionCreated { op, result }); - engine.check_rejected(rejected); + engine.check_rejected(rejected).await; }); } LibEffect::CreateEntry { @@ -1611,7 +2369,7 @@ impl Engine { game_id, result, }); - engine.check_rejected(rejected); + engine.check_rejected(rejected).await; }); } LibEffect::UpdateEntry { @@ -1639,7 +2397,7 @@ impl Engine { game_id, result, }); - engine.check_rejected(rejected); + engine.check_rejected(rejected).await; }); } LibEffect::DeleteEntry { @@ -1663,7 +2421,7 @@ impl Engine { game_id, result, }); - engine.check_rejected(rejected); + engine.check_rejected(rejected).await; }); } } @@ -1870,22 +2628,28 @@ impl Engine { { Ok(url) => url, Err(reason) => { - engine.dispatch(Input::SignInFailed { op, reason }); + engine + .dispatch_on_worker(Input::SignInFailed { op, reason }) + .await; return; } }; // Mark the browser as opened first so a prompt callback is never rejected // for arriving "too early"; a launch failure then cancels the attempt. - engine.dispatch(Input::BrowserOpened { - op, - url: url.as_str().to_owned(), - }); + engine + .dispatch_on_worker(Input::BrowserOpened { + op, + url: url.as_str().to_owned(), + }) + .await; let opened = tokio::task::spawn_blocking(move || browser.open(&url)).await; if !matches!(opened, Ok(Ok(()))) { - engine.dispatch(Input::SignInFailed { - op, - reason: SignInFailure::BrowserLaunch, - }); + engine + .dispatch_on_worker(Input::SignInFailed { + op, + reason: SignInFailure::BrowserLaunch, + }) + .await; } }); } @@ -1908,7 +2672,9 @@ impl Engine { let (engine, api) = (self.clone(), ports.api.clone()); self.shared.runtime.spawn(async move { let result = api.get_session(&credential).await; - engine.dispatch(Input::SessionChecked { op, result }); + engine + .dispatch_on_worker(Input::SessionChecked { op, result }) + .await; }); } Effect::SignOut { op, credential } => self.sign_out(op, credential), @@ -1939,14 +2705,1211 @@ impl Engine { }; drop(credential); // held only long enough to attempt invalidation let local_deleted = local_rx.await.unwrap_or(false); - engine.dispatch(Input::SignOutFinished { - op, - remote, - local_deleted, - }); + engine + .dispatch_on_worker(Input::SignOutFinished { + op, + remote, + local_deleted, + }) + .await; }); } } #[cfg(test)] mod tests; + +/// The engine's side of plugin library services. It holds the engine weakly, so the projection +/// the engine feeds does not keep the engine alive. +struct PluginLibraryHost { + shared: std::sync::Weak, +} + +impl PluginLibraryHost { + fn engine(&self) -> Result { + self.shared + .upgrade() + .map(|shared| Engine { shared }) + .ok_or_else(|| tonic::Status::unavailable("the library is not available")) + } +} + +#[async_trait::async_trait] +impl crate::plugin_host::library::LibraryHost for PluginLibraryHost { + async fn runtime_resources( + &self, + owner_key: String, + ) -> Result, tonic::Status> { + let engine = self.engine()?; + let store = engine.shared.ports.library.clone(); + tokio::task::spawn_blocking(move || store.runtime_resources(&owner_key)) + .await + .map_err(|_| tonic::Status::unavailable("library worker stopped"))? + .map_err(|_| tonic::Status::internal("could not read runtime resources")) + } + + async fn runtime_resource( + &self, + owner_key: String, + runtime_id: String, + ) -> Result, tonic::Status> { + let engine = self.engine()?; + let store = engine.shared.ports.library.clone(); + tokio::task::spawn_blocking(move || store.runtime_resource(&owner_key, &runtime_id)) + .await + .map_err(|_| tonic::Status::unavailable("library worker stopped"))? + .map_err(|_| tonic::Status::internal("could not read runtime resource")) + } + + async fn save_runtime_resource( + &self, + owner_key: String, + runtime: gamenode_core::library::RuntimeResource, + ) -> Result { + let engine = self.engine()?; + let store = engine.shared.ports.library.clone(); + tokio::task::spawn_blocking(move || store.save_runtime_resource(&owner_key, &runtime)) + .await + .map_err(|_| tonic::Status::unavailable("library worker stopped"))? + .map_err(|_| tonic::Status::internal("could not save runtime resource")) + } + + async fn remove_runtime_resource( + &self, + owner_key: String, + runtime_id: String, + expected_revision: u64, + ) -> Result { + let engine = self.engine()?; + let store = engine.shared.ports.library.clone(); + tokio::task::spawn_blocking(move || { + store.remove_runtime_resource(&owner_key, &runtime_id, expected_revision) + }) + .await + .map_err(|_| tonic::Status::unavailable("library worker stopped"))? + .map_err(|_| tonic::Status::internal("could not remove runtime resource")) + } + + async fn runtime_content_bindings( + &self, + owner_key: String, + game_id: u64, + installation_id: String, + ) -> Result, tonic::Status> { + let engine = self.engine()?; + let store = engine.shared.ports.library.clone(); + tokio::task::spawn_blocking(move || { + store.runtime_content_bindings(&owner_key, game_id, &installation_id) + }) + .await + .map_err(|_| tonic::Status::unavailable("library worker stopped"))? + .map_err(|_| tonic::Status::internal("could not read runtime content bindings")) + } + + async fn save_runtime_content_binding( + &self, + owner_key: String, + binding: gamenode_core::library::RuntimeContentBinding, + ) -> Result { + let engine = self.engine()?; + let store = engine.shared.ports.library.clone(); + tokio::task::spawn_blocking(move || { + store.save_runtime_content_binding(&owner_key, &binding) + }) + .await + .map_err(|_| tonic::Status::unavailable("library worker stopped"))? + .map_err(|_| tonic::Status::internal("could not save runtime content binding")) + } + + async fn remove_runtime_content_binding( + &self, + owner_key: String, + binding: gamenode_core::library::RuntimeContentBinding, + ) -> Result { + let engine = self.engine()?; + let store = engine.shared.ports.library.clone(); + tokio::task::spawn_blocking(move || { + store.remove_runtime_content_binding(&owner_key, &binding) + }) + .await + .map_err(|_| tonic::Status::unavailable("library worker stopped"))? + .map_err(|_| tonic::Status::internal("could not remove runtime content binding")) + } + + async fn runtime_catalog_revision(&self, owner_key: String) -> Result { + let engine = self.engine()?; + let store = engine.shared.ports.library.clone(); + tokio::task::spawn_blocking(move || store.runtime_catalog_revision(&owner_key)) + .await + .map_err(|_| tonic::Status::unavailable("library worker stopped"))? + .map_err(|_| tonic::Status::internal("could not read runtime catalog revision")) + } + + async fn shared_runtime_resources( + &self, + ) -> Result, tonic::Status> { + let engine = self.engine()?; + let store = engine.shared.ports.library.clone(); + tokio::task::spawn_blocking(move || store.shared_runtime_resources()) + .await + .map_err(|_| tonic::Status::unavailable("library worker stopped"))? + .map_err(|_| tonic::Status::internal("could not read shared runtime resources")) + } + + async fn shared_runtime_catalog_revision(&self) -> Result { + let engine = self.engine()?; + let store = engine.shared.ports.library.clone(); + tokio::task::spawn_blocking(move || store.shared_runtime_catalog_revision()) + .await + .map_err(|_| tonic::Status::unavailable("library worker stopped"))? + .map_err(|_| tonic::Status::internal("could not read shared runtime catalog revision")) + } + + async fn runtime_availability( + &self, + owner_key: Option, + installation_ids: Vec, + ) -> Result, tonic::Status> { + let engine = self.engine()?; + let store = engine.shared.ports.library.clone(); + tokio::task::spawn_blocking(move || { + store.runtime_availability(owner_key.as_deref(), &installation_ids) + }) + .await + .map_err(|_| tonic::Status::unavailable("library worker stopped"))? + .map_err(|_| tonic::Status::internal("could not read runtime availability")) + } + + async fn installed_programs( + &self, + ) -> Result, tonic::Status> { + let engine = self.engine()?; + let store = engine.shared.ports.library.clone(); + tokio::task::spawn_blocking(move || { + let cache = store.load_cache(None)?; + Ok::<_, gamenode_core::ports::StorageError>( + crate::plugin_host::runtime_access::installed_programs_from_entries(&cache.entries), + ) + }) + .await + .map_err(|_| tonic::Status::unavailable("library worker stopped"))? + .map_err(|_| tonic::Status::internal("could not read the installed-program inventory")) + } + + async fn custom_launch_recipe( + &self, + owner_key: String, + recipe_id: String, + ) -> Result, tonic::Status> { + let engine = self.engine()?; + let store = engine.shared.ports.library.clone(); + tokio::task::spawn_blocking(move || store.custom_launch_recipe(&owner_key, &recipe_id)) + .await + .map_err(|_| tonic::Status::unavailable("library worker stopped"))? + .map_err(|_| tonic::Status::internal("could not read custom launch recipe")) + } + + async fn save_custom_launch_recipe( + &self, + owner_key: String, + recipe: gamenode_core::library::CustomLaunchRecipe, + ) -> Result { + let engine = self.engine()?; + let store = engine.shared.ports.library.clone(); + tokio::task::spawn_blocking(move || store.save_custom_launch_recipe(&owner_key, &recipe)) + .await + .map_err(|_| tonic::Status::unavailable("library worker stopped"))? + .map_err(|_| tonic::Status::internal("could not save custom launch recipe")) + } + + async fn remove_custom_launch_recipe( + &self, + owner_key: String, + recipe_id: String, + expected_revision: u64, + ) -> Result { + let engine = self.engine()?; + let store = engine.shared.ports.library.clone(); + tokio::task::spawn_blocking(move || { + store.remove_custom_launch_recipe(&owner_key, &recipe_id, expected_revision) + }) + .await + .map_err(|_| tonic::Status::unavailable("library worker stopped"))? + .map_err(|_| tonic::Status::internal("could not remove custom launch recipe")) + } + + async fn launch_recipe_selection( + &self, + entry_key: String, + ) -> Result, tonic::Status> { + let engine = self.engine()?; + let store = engine.shared.ports.library.clone(); + tokio::task::spawn_blocking(move || store.launch_recipe_selection(&entry_key)) + .await + .map_err(|_| tonic::Status::unavailable("library worker stopped"))? + .map_err(|_| tonic::Status::internal("could not read launch recipe selection")) + } + + async fn approve_launch_recipe_plan( + &self, + entry_key: String, + recipe_id: String, + recipe_revision: u64, + target_revision: u64, + fingerprint: String, + ) -> Result { + let engine = self.engine()?; + let store = engine.shared.ports.library.clone(); + tokio::task::spawn_blocking(move || { + store.approve_launch_recipe_plan( + &entry_key, + &recipe_id, + recipe_revision, + target_revision, + &fingerprint, + ) + }) + .await + .map_err(|_| tonic::Status::unavailable("library worker stopped"))? + .map_err(|_| tonic::Status::internal("could not remember launch plan")) + } + + async fn detected_launch( + &self, + entry_key: String, + expected_revision: u64, + ) -> Result { + let engine = self.engine()?; + tokio::task::spawn_blocking(move || { + detected_target::resolved_command(&engine, &entry_key, expected_revision) + }) + .await + .map_err(|_| tonic::Status::unavailable("detected launch worker stopped"))? + } + + async fn prepare_custom_launch( + &self, + recipe: gamenode_core::library::CustomLaunchRecipe, + executable_path: Option, + working_directory_path: Option, + runtime: Option, + ) -> Result { + let engine = self.engine()?; + let ports = engine.shared.ports.clone(); + tokio::task::spawn_blocking(move || { + use crate::plugin_host::library::CustomLaunchDispatch; + use gamenode_core::drm_free::CustomLaunchCommand; + if !recipe.validate() { + return Err(tonic::Status::invalid_argument( + "invalid custom launch recipe", + )); + } + if !recipe.uri.is_empty() { + let uri = url::Url::parse(&recipe.uri) + .map_err(|_| tonic::Status::invalid_argument("invalid launch URI"))?; + let environment = recipe.effective_environment(); + return Ok(CustomLaunchDispatch::Uri { + uri, + arguments: recipe.effective_arguments(), + working_directory: working_directory_path.unwrap_or_default(), + environment, + }); + } + if let Some(runtime) = runtime { + if !recipe.executable_handle.is_empty() || recipe.executable.is_some() { + return Err(tonic::Status::invalid_argument( + "a runtime recipe cannot also select a direct executable", + )); + } + if recipe.runtime_handle != runtime.runtime_id { + return Err(tonic::Status::failed_precondition( + "the selected runtime changed during launch preparation", + )); + } + let installations = ports.installations.ok_or_else(|| { + tonic::Status::unimplemented("runtime launch is unavailable on this platform") + })?; + let registration = installations + .inspect(&runtime.executable) + .map_err(|error| match error { + gamenode_core::drm_free::LocalError::Unsupported => { + tonic::Status::unimplemented( + "runtime launch is unavailable on this platform", + ) + } + gamenode_core::drm_free::LocalError::InvalidTarget => { + tonic::Status::failed_precondition( + "the approved runtime executable changed or is invalid", + ) + } + _ => tonic::Status::unavailable("could not inspect approved runtime"), + })?; + let mut arguments = + Vec::with_capacity(runtime.arguments.len() + recipe.arguments.len()); + for argument in runtime.arguments { + match argument { + gamenode_core::library::RuntimeArgumentTemplate::Literal(value) => { + arguments.push(value) + } + gamenode_core::library::RuntimeArgumentTemplate::ContentPath => { + let path = runtime.content_path.as_ref().ok_or_else(|| { + tonic::Status::failed_precondition( + "the selected runtime requires a content binding", + ) + })?; + arguments.push(path.clone()); + } + } + } + arguments.extend(recipe.effective_arguments()); + let working_directory = working_directory_path + .unwrap_or_else(|| registration.working_directory.clone()); + let command = CustomLaunchCommand { + executable: registration.executable, + file_identity: registration.file_identity, + arguments, + working_directory, + environment: recipe.effective_environment(), + }; + return Ok(CustomLaunchDispatch::Runtime { + command, + runtime_id: runtime.runtime_id, + runtime_version: runtime.version, + runtime_revision: runtime.runtime_revision, + content_id: runtime.content_id, + binding_revision: runtime.binding_revision, + lease_keys: runtime.lease_keys, + }); + } + if !recipe.runtime_handle.is_empty() { + return Err(tonic::Status::failed_precondition( + "the selected runtime could not be resolved", + )); + } + let executable = executable_path.ok_or_else(|| { + tonic::Status::permission_denied("executable handle is unavailable") + })?; + let installations = ports.installations.ok_or_else(|| { + tonic::Status::unimplemented("custom executable launch is unavailable") + })?; + let registration = installations + .inspect(&executable) + .map_err(|error| match error { + gamenode_core::drm_free::LocalError::Unsupported => { + tonic::Status::unimplemented("custom executable launch is unavailable") + } + gamenode_core::drm_free::LocalError::InvalidTarget => { + tonic::Status::failed_precondition( + "approved executable changed or is invalid", + ) + } + _ => tonic::Status::unavailable("could not inspect approved executable"), + })?; + let working_directory = + working_directory_path.unwrap_or_else(|| registration.working_directory.clone()); + let environment = recipe.effective_environment(); + let command = CustomLaunchCommand { + executable: registration.executable, + file_identity: registration.file_identity, + arguments: recipe.effective_arguments(), + working_directory, + environment, + }; + Ok(CustomLaunchDispatch::Executable(command)) + }) + .await + .map_err(|_| tonic::Status::unavailable("custom launch preparation worker stopped"))? + } + + async fn launch_custom( + &self, + dispatch: crate::plugin_host::library::CustomLaunchDispatch, + ) -> Result<(), tonic::Status> { + let engine = self.engine()?; + #[cfg(any(target_os = "linux", windows))] + let dispatch = match dispatch { + crate::plugin_host::library::CustomLaunchDispatch::Executable(command) + | crate::plugin_host::library::CustomLaunchDispatch::Detected { command } => { + return engine + .start_supervised_custom_launch(command, Vec::new(), None, None) + .await + .map(|_| ()); + } + crate::plugin_host::library::CustomLaunchDispatch::Runtime { + command, + lease_keys, + .. + } => { + return engine + .start_supervised_custom_launch(command, lease_keys, None, None) + .await + .map(|_| ()); + } + uri => uri, + }; + let ports = engine.shared.ports.clone(); + tokio::task::spawn_blocking(move || { + use crate::plugin_host::library::CustomLaunchDispatch; + use gamenode_core::ports::UriError; + match dispatch { + CustomLaunchDispatch::Uri { + uri, + arguments, + working_directory, + environment, + } => ports + .uri + .open_custom(&uri, &arguments, &working_directory, &environment) + .map_err(|error| match error { + UriError::NoHandler => tonic::Status::failed_precondition( + "no application handles this launch URI", + ), + UriError::Unsupported => tonic::Status::unimplemented( + "the URI handler cannot apply custom launch fields", + ), + UriError::Failed => tonic::Status::unavailable("the launch URI failed"), + }), + CustomLaunchDispatch::Executable(command) + | CustomLaunchDispatch::Detected { command } => { + let installations = ports.installations.ok_or_else(|| { + tonic::Status::unimplemented("custom executable launch is unavailable") + })?; + installations + .launch_custom(&command) + .map_err(|error| match error { + gamenode_core::drm_free::LocalError::Unsupported => { + tonic::Status::unimplemented( + "custom executable launch is unavailable", + ) + } + gamenode_core::drm_free::LocalError::InvalidTarget => { + tonic::Status::failed_precondition( + "approved executable changed or is invalid", + ) + } + _ => tonic::Status::unavailable("custom executable launch failed"), + }) + } + CustomLaunchDispatch::Runtime { command, .. } => { + let installations = ports.installations.ok_or_else(|| { + tonic::Status::unimplemented( + "runtime launch is unavailable on this platform", + ) + })?; + installations + .launch_custom(&command) + .map_err(|error| match error { + gamenode_core::drm_free::LocalError::Unsupported => { + tonic::Status::unimplemented( + "runtime launch is unavailable on this platform", + ) + } + gamenode_core::drm_free::LocalError::InvalidTarget => { + tonic::Status::failed_precondition( + "approved runtime executable changed or is invalid", + ) + } + _ => tonic::Status::unavailable("runtime launch failed"), + }) + } + } + }) + .await + .map_err(|_| tonic::Status::unavailable("custom launch worker stopped"))? + } + + async fn launch_custom_for_entry( + &self, + dispatch: crate::plugin_host::library::CustomLaunchDispatch, + entry_key: String, + ) -> Result<(), tonic::Status> { + #[cfg(any(target_os = "linux", windows))] + { + let engine = self.engine()?; + match dispatch { + crate::plugin_host::library::CustomLaunchDispatch::Executable(command) + | crate::plugin_host::library::CustomLaunchDispatch::Detected { command } => { + return engine + .start_supervised_custom_launch(command, Vec::new(), Some(entry_key), None) + .await + .map(|_| ()); + } + crate::plugin_host::library::CustomLaunchDispatch::Runtime { + command, + lease_keys, + .. + } => { + return engine + .start_supervised_custom_launch(command, lease_keys, Some(entry_key), None) + .await + .map(|_| ()); + } + uri => return self.launch_custom(uri).await, + } + } + #[cfg(not(any(target_os = "linux", windows)))] + { + let _ = entry_key; + self.launch_custom(dispatch).await + } + } + + async fn launch_custom_for_entry_authorized( + &self, + dispatch: crate::plugin_host::library::CustomLaunchDispatch, + entry_key: String, + authority: crate::plugin_host::library::UserLaunchAuthority, + ) -> Result<(), tonic::Status> { + let engine = self.engine()?; + match dispatch { + #[cfg(any(target_os = "linux", windows))] + crate::plugin_host::library::CustomLaunchDispatch::Executable(command) + | crate::plugin_host::library::CustomLaunchDispatch::Detected { command } => engine + .start_supervised_custom_launch( + command, + Vec::new(), + Some(entry_key), + Some(authority), + ) + .await + .map(|_| ()), + #[cfg(any(target_os = "linux", windows))] + crate::plugin_host::library::CustomLaunchDispatch::Runtime { + command, + lease_keys, + .. + } => engine + .start_supervised_custom_launch( + command, + lease_keys, + Some(entry_key), + Some(authority), + ) + .await + .map(|_| ()), + crate::plugin_host::library::CustomLaunchDispatch::Uri { + uri, + arguments, + working_directory, + environment, + } => { + engine + .launch_authorized_uri( + uri, + arguments, + working_directory, + environment, + authority, + ) + .await + } + #[cfg(not(any(target_os = "linux", windows)))] + _ => Err(tonic::Status::unimplemented( + "custom executable launch is unavailable", + )), + } + } + + fn ports_supported(&self) -> bool { + self.engine() + .ok() + .and_then(|e| e.ports_service()) + .is_some_and(|s| s.is_supported()) + } + async fn ports_catalog( + &self, + detail: Option, + ) -> Result, tonic::Status> { + self.engine()?.plugin_ports_catalog(detail).await + } + async fn request_port( + &self, + port_id: String, + review: gamenode_core::ports::view::PortPluginRequest, + check: crate::plugin_host::jobs::Fence, + ) -> Result<(), tonic::Status> { + self.engine()? + .review_plugin_port(port_id, review, check) + .await + } + + fn tools_supported(&self) -> bool { + self.engine().is_ok_and(|e| { + cfg!(windows) + && e.shared.ports.tool_installer.is_some() + && e.shared.ports.tools.is_some() + && e.shared.ports.tool_catalog.is_some() + }) + } + async fn tools_list( + &self, + entry_key: String, + ) -> Result, tonic::Status> { + let engine = self.engine()?; + tokio::task::spawn_blocking(move || engine.plugin_tools_list(&entry_key)) + .await + .map_err(|_| tonic::Status::unavailable("tools worker unavailable"))? + } + async fn request_tool( + &self, + entry_key: String, + tool_id: String, + review: gamenode_core::tools::ToolPluginRequest, + check: crate::plugin_host::jobs::Fence, + ) -> Result<(), tonic::Status> { + self.engine()? + .request_plugin_tool(entry_key, tool_id, review, check) + .await + } + + async fn backup_context( + &self, + entry_key: String, + ) -> Result { + let engine = self.engine()?; + tokio::task::spawn_blocking(move || { + use gamenode_core::drm_free::BackupTarget; + let adapter = engine + .shared + .ports + .backups + .clone() + .filter(|adapter| adapter.scoped_available()) + .ok_or_else(|| { + tonic::Status::unavailable("backups are unavailable on this platform") + })?; + let (root, manual_id) = { + let state = engine.lock(); + let entry = state + .library + .entry(&entry_key) + .filter(|entry| entry.installed) + .ok_or_else(|| tonic::Status::not_found("installed game not found"))?; + ( + entry.install_dir.clone(), + entry_key.strip_prefix("manual:").map(str::to_owned), + ) + }; + let mut target = BackupTarget { + installation_id: String::new(), + root, + gameplay: vec![], + track_folder: manual_id.is_none(), + }; + let local = engine.load_local_view(); + if let Some(id) = manual_id { + let registration = local + .registrations + .iter() + .find(|r| r.id == id && !r.removed) + .ok_or_else(|| tonic::Status::not_found("installed game not found"))?; + target.gameplay = registration.gameplay.clone(); + } + if target.root.is_empty() { + return Err(tonic::Status::failed_precondition( + "installation folder unavailable", + )); + } + Ok(crate::plugin_host::library::BackupHostContext { + engine: adapter, + target, + destination: local.settings.destination, + }) + }) + .await + .map_err(|_| tonic::Status::unavailable("backup context unavailable"))? + } + + fn plugin_roots_supported(&self) -> bool { + true + } + fn set_plugin_roots( + &self, + owner: String, + roots: Vec, + ) -> Result<(), tonic::Status> { + let engine = self.engine()?; + let mut active = engine + .shared + .plugin_scan_roots + .lock() + .unwrap_or_else(|p| p.into_inner()); + let previous = active + .get(&owner) + .map(|roots| roots.iter().map(|r| r.root.clone()).collect::>()) + .unwrap_or_default(); + let changed = previous != roots.iter().map(|r| r.root.clone()).collect::>(); + if roots.is_empty() { + active.remove(&owner); + } else { + active.insert(owner, roots); + } + drop(active); + if changed || !previous.is_empty() { + engine.rescan_local_folders(); + } + Ok(()) + } + + fn favorites(&self, provider_id: &str) -> Vec<(u64, bool)> { + let Ok(engine) = self.engine() else { + return Vec::new(); + }; + let state = engine.lock(); + let library = &state.library; + if !library.is_active() { + return Vec::new(); + } + let mut games = std::collections::BTreeMap::new(); + for entry in library + .visible_entries() + .filter(|entry| entry.provider == provider_id) + { + if let Some(game) = library.match_status(entry).game_id() { + games.insert( + game, + library + .favorite_state(game) + .is_some_and(|favorite| favorite.is_favorite), + ); + } + } + games.into_iter().collect() + } + + fn set_favorite( + &self, + provider_id: &str, + game_id: u64, + favorite: bool, + guard: &dyn Fn() -> Result<(), tonic::Status>, + ) -> Result { + use crate::plugin_host::library::FavoriteWrite; + let engine = self.engine()?; + let mut state = engine.lock(); + // Checked under the engine lock, in the same section that commits. + guard()?; + let library = &state.library; + let key = library + .is_active() + .then(|| { + library + .visible_entries() + .filter(|entry| entry.provider == provider_id) + .find(|entry| library.match_status(entry).game_id() == Some(game_id)) + .map(|entry| entry.key.clone()) + }) + .flatten(); + let Some(key) = key else { + return Ok(FavoriteWrite::NoMatchedEntry); + }; + let is_favorite = |state: &State| { + state + .library + .favorite_state(game_id) + .is_some_and(|favorite| favorite.is_favorite) + }; + if is_favorite(&state) == favorite { + return Ok(FavoriteWrite::AlreadyApplied); + } + engine.run_library( + &mut state, + LibInput::SetFavorite { + key, + favorite, + now: unix_now(), + }, + ); + engine.publish(&mut state); + if is_favorite(&state) != favorite { + // The library had no account to keep the favorite for. + return Err(tonic::Status::unavailable("the library is not available")); + } + Ok(FavoriteWrite::Applied) + } + + async fn search_catalog( + &self, + query: String, + limit: usize, + ) -> Result, tonic::Status> { + use crate::plugin_host::library::CatalogGame; + let engine = self.engine()?; + let (credential, api) = { + let state = engine.lock(); + // The catalog is the user's GameNode account: never searched without a verified, + // online session. + let credential = state + .library + .is_active() + .then(|| state.library.network_block().is_none()) + .filter(|online| *online) + .and_then(|_| state.machine.verified_credential().cloned()); + let Some(credential) = credential else { + return Err(tonic::Status::unavailable( + "the GameNode catalog needs a verified, online session", + )); + }; + (credential, engine.shared.ports.games.clone()) + }; + match api.search_games(&credential, &query).await { + Ok(mut games) => { + games.truncate(limit); + engine.library_input(LibInput::CatalogSearched { + games: games.clone(), + }); + Ok(games + .into_iter() + .map(|game| CatalogGame { + id: game.id, + name: game.name, + release_year: game.release_year, + }) + .collect()) + } + Err(error) => { + engine + .check_rejected(matches!(error, ApiError::Rejected)) + .await; + Err(tonic::Status::unavailable( + "the GameNode catalog could not answer", + )) + } + } + } + + fn assign_match( + &self, + entry_key: &str, + game_id: u64, + expected_revision: u64, + guard: &dyn Fn() -> Result<(), tonic::Status>, + ) -> Result { + use crate::plugin_host::library::MatchWrite; + use gamenode_core::library::PluginMatch; + let engine = self.engine()?; + let feed = engine + .shared + .library_feed + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .clone() + .ok_or_else(|| tonic::Status::unavailable("the library is not available"))?; + let mut state = engine.lock(); + // Checked under the engine lock, in the same section that commits. + guard()?; + // Bring the projection up to date under the same lock, so the revision compared is the + // one the entry has now. + engine.sync_library_feed(&state); + let not_found = || tonic::Status::not_found("library entry not found"); + let current = feed.revision_of(entry_key).ok_or_else(not_found)?; + let plan = state.library.plan_plugin_match(entry_key, game_id); + match plan { + PluginMatch::NoAccount => { + return Err(tonic::Status::unavailable("the library is not available")); + } + PluginMatch::UnknownEntry => return Err(not_found()), + PluginMatch::Already => { + return Ok(MatchWrite::AlreadyApplied { revision: current }); + } + _ => {} + } + if expected_revision != current { + return Ok(MatchWrite::Conflict { current }); + } + match plan { + PluginMatch::UnknownGame => return Ok(MatchWrite::UnknownGame), + PluginMatch::UserChoice => return Ok(MatchWrite::UserChoice), + _ => {} + } + engine.run_library( + &mut state, + LibInput::AssignPluginMatch { + key: entry_key.to_owned(), + game_id, + now: unix_now(), + }, + ); + // Playtime is submitted per game, so a new match is a moment to submit, as for the + // user's own pick. + engine.submit_totals(&mut state); + engine.publish(&mut state); + if state.library.plan_plugin_match(entry_key, game_id) != PluginMatch::Already { + return Err(tonic::Status::unavailable("the library is not available")); + } + let revision = feed.revision_of(entry_key).unwrap_or(current); + Ok(MatchWrite::Applied { revision }) + } + + async fn read_artwork( + &self, + entry_key: String, + max_bytes: u64, + ) -> Result { + use gamenode_platform::plugin_artwork::{self, ReadError}; + let engine = self.engine()?; + let (file, revision, dir) = { + let state = engine.lock(); + let library = &state.library; + ( + library + .is_active() + .then(|| library.entry_cover_file(&entry_key)) + .flatten(), + library + .artwork_override(&entry_key) + .map_or(0, |over| over.revision), + engine.shared.ports.covers_dir.clone(), + ) + }; + let file = file.ok_or_else(|| tonic::Status::not_found("the entry has no cover"))?; + let name = file.clone(); + let read = + tokio::task::spawn_blocking(move || plugin_artwork::read(&dir, &name, max_bytes)) + .await + .map_err(|_| tonic::Status::unavailable("the library is not available"))?; + match read { + Ok(bytes) => Ok(crate::plugin_host::library::StoredArtwork { + bytes, + media_type: plugin_artwork::media_type_of(&file), + revision, + }), + Err(ReadError::TooLarge) => Err(tonic::Status::resource_exhausted( + "the cover is larger than max_bytes; ask for more", + )), + Err(ReadError::Unavailable) => Err(tonic::Status::not_found( + "the cover is not on this device yet", + )), + } + } + + async fn set_artwork( + &self, + entry_key: String, + expected_revision: u64, + image: Option, + guard: crate::plugin_host::library::CommitGuard, + ) -> Result { + use gamenode_core::library::ArtworkWrite; + use gamenode_platform::plugin_artwork; + let engine = self.engine()?; + let store = engine.shared.ports.library.clone(); + let dir = engine.shared.ports.covers_dir.clone(); + let name = image + .as_ref() + .map(|image| plugin_artwork::file_name(&entry_key, image)); + let (done, written) = tokio::sync::oneshot::channel(); + { + let (key, name) = (entry_key.clone(), name.clone()); + // The storage worker runs jobs in order, so this write cannot overtake or be + // overtaken by other library writes; authorization is rechecked where it commits. + engine.shared.storage.submit(move || { + let result = guard().and_then(|()| { + // The file goes first and the row second: a crash in between leaves a file + // nothing refers to, never a row that points at nothing. + let existed = match (&image, &name) { + (Some(image), Some(name)) => { + Some(plugin_artwork::store(&dir, name, image).map_err(|error| { + tracing::warn!(%error, "could not store a plugin cover"); + tonic::Status::unavailable("could not store the cover") + })?) + } + _ => None, + }; + let outcome = store + .save_artwork(&key, expected_revision, name.as_deref()) + .map_err(|error| { + tracing::warn!(%error, "could not record a plugin cover"); + tonic::Status::unavailable("could not store the cover") + }); + match &outcome { + Ok(ArtworkWrite::Applied { replaced, .. }) => { + if let Some(old) = replaced + && Some(old) != name.as_ref() + { + plugin_artwork::remove(&dir, old); + } + } + // The same file is the live one. + Ok(ArtworkWrite::Unchanged { .. }) => {} + // Nothing refers to the file just written, unless it was already there. + Ok(ArtworkWrite::Conflict { .. }) | Err(_) => { + if let (Some(false), Some(name)) = (existed, &name) { + plugin_artwork::remove(&dir, name); + } + } + } + outcome + }); + let _ = done.send(result); + }); + } + let written = written + .await + .map_err(|_| tonic::Status::unavailable("the library is not available"))??; + if let ArtworkWrite::Applied { revision, .. } = &written { + engine.library_input(LibInput::ArtworkStored { + key: entry_key, + file: name, + revision: *revision, + }); + } + Ok(written) + } + + async fn launch_fingerprint(&self, entry_key: String) -> Result { + use sha2::{Digest, Sha256}; + let engine = self.engine()?; + let (entry, provider) = { + let state = engine.lock(); + let entry = state + .library + .entry(&entry_key) + .cloned() + .ok_or_else(|| tonic::Status::not_found("library entry not found"))?; + let provider = state + .library + .provider(&entry.provider) + .cloned() + .ok_or_else(|| tonic::Status::not_found("library entry not found"))?; + (entry, provider) + }; + let worker = engine.clone(); + tokio::task::spawn_blocking(move || { + let mut hash = Sha256::new(); + let mut part = |bytes: &[u8]| { + hash.update((bytes.len() as u64).to_be_bytes()); + hash.update(bytes); + }; + if provider.is_manual_executable() { + let store = worker.shared.ports.local_games.as_ref().ok_or_else(|| { + tonic::Status::unimplemented("starting games is not available") + })?; + let registrations = store + .registrations() + .map_err(|_| tonic::Status::unavailable("the library is not available"))?; + let registration = registrations + .iter() + .find(|r| r.key() == entry.key && !r.removed) + .ok_or_else(|| { + tonic::Status::failed_precondition("the game has no approved executable") + })?; + part(b"manual"); + part(registration.id.as_bytes()); + part(registration.executable.as_bytes()); + part(registration.working_directory.as_bytes()); + for argument in ®istration.arguments { + part(argument.as_bytes()); + } + part(®istration.revision.to_be_bytes()); + } else { + match provider.launch_uri(&entry.record()) { + Ok(uri) => { + part(b"uri"); + part(uri.as_str().as_bytes()); + } + Err(_) => part(b"none"), + } + } + let digest = hash.finalize(); + Ok(u64::from_be_bytes( + digest[..8].try_into().expect("a digest has eight bytes"), + )) + }) + .await + .map_err(|_| tonic::Status::unavailable("the library is not available"))? + } + + async fn launch_target_revision(&self, entry_key: String) -> Result { + let engine = self.engine()?; + let state = engine.lock(); + let entry = state + .library + .entry(&entry_key) + .ok_or_else(|| tonic::Status::not_found("library entry not found"))?; + // Zero means the provider reports no detected executable/URI target. A runtime recipe is + // still a complete launch for a ROM store, so that is a revision, not an error. + Ok(entry.target.as_ref().map_or(0, |target| target.revision)) + } + + async fn open_entry(&self, entry_key: String, install: bool) -> Result<(), tonic::Status> { + use gamenode_core::library::LaunchError; + let engine = self.engine()?; + let (done, opened) = tokio::sync::oneshot::channel(); + let kind = if install { + LaunchKind::Install + } else { + LaunchKind::Play + }; + engine.open_entry_then(entry_key, kind, move |result| { + let _ = done.send(result); + }); + match opened + .await + .map_err(|_| tonic::Status::unavailable("the library is not available"))? + { + Ok(()) => Ok(()), + Err(OpenError::Busy) => Err(tonic::Status::failed_precondition( + "the game is already running or being opened", + )), + Err(OpenError::NotFound) => Err(tonic::Status::not_found("library entry not found")), + Err(OpenError::Launch(LaunchError::Unsupported)) => Err(tonic::Status::unimplemented( + "this provider does not support that action", + )), + Err(OpenError::Launch(LaunchError::Incomplete)) => Err( + tonic::Status::failed_precondition("the game is missing data the provider needs"), + ), + Err(OpenError::Launch(LaunchError::RecipeNeedsAttention)) => { + Err(tonic::Status::failed_precondition( + "the selected launch recipe needs attention; review it or use the detected default", + )) + } + Err(OpenError::Launch(LaunchError::NoHandler)) => Err( + tonic::Status::failed_precondition("the store application is not available"), + ), + Err(OpenError::Launch(LaunchError::Failed)) => { + Err(tonic::Status::unavailable("the link could not be opened")) + } + } + } + + async fn set_display_name( + &self, + entry_key: String, + expected_revision: u64, + display_name: Option, + guard: crate::plugin_host::library::CommitGuard, + ) -> Result { + use gamenode_core::library::DisplayWrite; + let engine = self.engine()?; + let store = engine.shared.ports.library.clone(); + let (done, written) = tokio::sync::oneshot::channel(); + { + let (key, name) = (entry_key.clone(), display_name.clone()); + // The storage worker runs jobs in order, so this write cannot overtake or be + // overtaken by other library writes; authorization is rechecked where it commits. + engine.shared.storage.submit(move || { + let result = guard().and_then(|()| { + store + .save_display_name(&key, expected_revision, name.as_deref()) + .map_err(|error| { + tracing::warn!(%error, "could not store a display name"); + tonic::Status::unavailable("could not store the display name") + }) + }); + let _ = done.send(result); + }); + } + let written = written + .await + .map_err(|_| tonic::Status::unavailable("the library is not available"))??; + if let DisplayWrite::Applied { revision } = written { + engine.library_input(LibInput::DisplayNameStored { + key: entry_key, + display_name, + revision, + }); + } + Ok(written) + } +} diff --git a/crates/app/src/engine/pc_ports.rs b/crates/app/src/engine/pc_ports.rs index ba42b7cae..12d93b336 100644 --- a/crates/app/src/engine/pc_ports.rs +++ b/crates/app/src/engine/pc_ports.rs @@ -75,6 +75,14 @@ pub enum PortsEvent { /// tests inject a fake to check the planning and wiring without touching a disk or the network. pub trait InstallRunner: Send + Sync { fn enqueue(&self, request: InstallJobRequest) -> Result<(), JobError>; + fn enqueue_checked( + &self, + _request: InstallJobRequest, + _check: gamenode_platform::ports::job_runner::InstallAuthority, + ) -> Result<(), JobError> { + Err(JobError::Closed) + } + fn cancel(&self, job_id: &str) -> bool; fn complete_with_executable(&self, job_id: &str, executable: &str) -> Result<(), JobError>; fn awaiting_jobs(&self) -> Result, JobError>; @@ -86,6 +94,14 @@ pub trait InstallRunner: Send + Sync { } impl InstallRunner for JobRunner { + fn enqueue_checked( + &self, + request: InstallJobRequest, + check: gamenode_platform::ports::job_runner::InstallAuthority, + ) -> Result<(), JobError> { + JobRunner::enqueue_checked(self, request, check) + } + fn enqueue(&self, request: InstallJobRequest) -> Result<(), JobError> { JobRunner::enqueue(self, request) } @@ -266,6 +282,8 @@ impl From for PortsError { #[derive(Clone, Debug, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct PortInstallRequest { + #[serde(default)] + pub plugin_request_id: Option, pub catalog_id: String, /// Parent folder chosen by the user; the host creates a subfolder inside it. pub parent_folder: String, @@ -769,21 +787,47 @@ impl PortsService { if !self.is_supported() { return Err(PortsError::Unsupported); } - let runner = lock(&self.inner).runner.clone(); - let Some(runner) = runner else { - return Err(PortsError::Unavailable( - "the install worker is not available".into(), - )); - }; + self.install_inner(request, None) + } + + pub(super) fn install_checked( + &self, + request: &PortInstallRequest, + check: crate::plugin_host::jobs::Fence, + ) -> Result, PortsError> { + self.install_inner(request, Some(check)) + } + + fn install_inner( + &self, + request: &PortInstallRequest, + check: Option, + ) -> Result, PortsError> { + if let Some(check) = &check { + check() + .map_err(|_| PortsError::Unavailable("port request no longer authorized".into()))?; + } + let runner = lock(&self.inner) + .runner + .clone() + .ok_or_else(|| PortsError::Unavailable("install worker unavailable".into()))?; self.wait_ready(); let prepared = self.prepare_install(request)?; + if let Some(check) = &check { + check() + .map_err(|_| PortsError::Unavailable("port request no longer authorized".into()))?; + } { // Clearing the cache and queueing an install exclude each other, so a clear cannot // start between this job's active check and its cache use. let _gate = lock(&self.cache_gate); - runner - .enqueue(prepared.clone()) - .map_err(|error| PortsError::Unavailable(error.to_string()))?; + match check { + Some(check) => { + runner.enqueue_checked(prepared.clone(), Arc::new(move || check().is_ok())) + } + None => runner.enqueue(prepared.clone()), + } + .map_err(|error| PortsError::Unavailable(error.to_string()))?; } // Remembering the folder is a convenience; a failed write must not report the queued // install as failed. @@ -804,6 +848,10 @@ impl PortsService { Ok(Some(prepared.job_id)) } + pub(super) fn plugin_job(&self, id: &str) -> Result, PortsError> { + Ok(self.config.store.job(id)?) + } + /// The executable follow-up for a job whose recipe had no launchable file. Blocking. pub fn pick_executable(&self, job_id: &str) -> Result, PortsError> { if !self.is_supported() { @@ -1151,7 +1199,7 @@ impl PortsService { } } - fn build_view(&self) -> Result { + pub(super) fn build_view(&self) -> Result { let (catalog, facts, active) = { let inner = lock(&self.inner); ( @@ -1615,7 +1663,7 @@ impl PortProgressPublisher { // --------------------------------------------------------------------------------------------- impl Engine { - fn ports_service(&self) -> Option> { + pub(super) fn ports_service(&self) -> Option> { self.shared.ports.pc_ports.clone() } @@ -1736,9 +1784,21 @@ impl Engine { let Some(service) = self.ports_service() else { return Err(PortsError::Unsupported); }; - tokio::task::spawn_blocking(move || service.install(&request)) - .await - .map_err(|_| PortsError::NotReady)? + let check = self.plugin_port_install_check(&request)?; + let engine = self.clone(); + let request_id = request.plugin_request_id.clone(); + tokio::task::spawn_blocking(move || { + let result = match check { + Some(check) => service.install_checked(&request, check), + None => service.install(&request), + }; + if let Some(id) = request_id { + engine.plugin_port_enqueued(&id, &result); + } + result + }) + .await + .map_err(|_| PortsError::NotReady)? } /// The executable follow-up of a completed install. The native dialog runs on a worker. diff --git a/crates/app/src/engine/pc_ports/view.rs b/crates/app/src/engine/pc_ports/view.rs index e71936ab7..72f187ffd 100644 --- a/crates/app/src/engine/pc_ports/view.rs +++ b/crates/app/src/engine/pc_ports/view.rs @@ -94,6 +94,7 @@ pub fn build(input: ViewInput<'_>) -> PortsView { }) .count(); PortsView { + plugin_request: None, catalog: catalog_status(input.status), entries, provenance: provenance(input.installations, input.jobs), diff --git a/crates/app/src/engine/playtime.rs b/crates/app/src/engine/playtime.rs index 80e3918e0..411fa7a42 100644 --- a/crates/app/src/engine/playtime.rs +++ b/crates/app/src/engine/playtime.rs @@ -6,7 +6,9 @@ use gamenode_core::playtime::{ }; use gamenode_core::ports::ProcessError; use gamenode_core::sync::{SyncNowError, SyncPreferences, SyncSummary, SyncView}; -use gamenode_core::tracker::{Effect as TrackEffect, Entry, Input as TrackInput, Tracker}; +use gamenode_core::tracker::{ + Effect as TrackEffect, Entry, Input as TrackInput, Tracker, runtime_sessions::RuntimeSessions, +}; /// How long a rejected total waits before a normal automatic pass retries it. An explicit /// "Sync now" is itself the next opportunity and does not wait. @@ -14,6 +16,7 @@ const REJECTED_RETRY_AFTER_SECS: i64 = 300; pub(super) struct Playtime { pub tracker: Tracker, + pub runtime_sessions: RuntimeSessions, pub preferences: SyncPreferences, pub source: PlaytimeSource, pub available: bool, @@ -58,9 +61,14 @@ pub(super) struct Playtime { display_dirty: bool, } impl Playtime { + pub(super) fn is_stopped(&self) -> bool { + self.stopped + } + pub fn new(platform: Platform) -> Self { Self { tracker: Tracker::new(platform == Platform::Windows), + runtime_sessions: RuntimeSessions::default(), preferences: SyncPreferences::default(), source: PlaytimeSource::Store, available: true, @@ -106,6 +114,27 @@ impl Playtime { } } } + +/// Package-manager games declare an exact executable (for example `/usr/bin/0ad`) while their +/// install root is the shared `/usr/bin`. Without this exact policy the tracker matches every +/// process under `/usr/bin`, so a long-running shell can be attributed to an arbitrary package. +/// The field only narrows process matching; it is not launch authority. +fn package_executable_policy( + entry: &gamenode_core::library::StoredEntry, +) -> Option<(String, gamenode_core::drm_free::ProcessPolicy)> { + let executable = entry.fields.get("executable")?.trim(); + if executable.is_empty() { + return None; + } + Some(( + entry.key.clone(), + gamenode_core::drm_free::ProcessPolicy::Explicit { + gameplay: vec![executable.to_owned()], + launchers: Vec::new(), + }, + )) +} + impl Engine { pub(super) fn start_playtime(&self) -> Result<(), StorageError> { let store = &self.shared.ports.playtime; @@ -161,6 +190,9 @@ impl Engine { .collect(); let changed = account != state.playtime.owner; if changed { + let runtime_effects = state.playtime.runtime_sessions.reset(); + let runtime_effects = runtime_track_effects(runtime_effects); + self.track_effects(state, runtime_effects); self.cancel_submissions(state); state.playtime.display_totals.clear(); state.playtime.display_sessions.clear(); @@ -171,27 +203,25 @@ impl Engine { self.load_sync_summary(account); } } - state.playtime.tracker.set_policies( - state - .local - .registrations - .iter() - .filter(|r| !r.removed) - .map(|r| (r.key(), r.process_policy())) - .chain( - state - .local - .registrations - .iter() - .filter(|r| !r.removed) - .filter_map(|r| { - r.transferred_from - .clone() - .map(|key| (key, gamenode_core::drm_free::ProcessPolicy::Ignored)) - }), - ) - .collect(), - ); + // Package-manager entries share a broad install root such as `/usr/bin`, so a prefix + // match would attribute any process under that root (a shell, for example) to an + // arbitrary package. A declared executable is an exact process policy and takes + // precedence over that broad root. Local registrations are inserted last and still win. + let mut policies = std::collections::BTreeMap::new(); + for entry in state.library.installed_entries() { + if let Some((key, policy)) = package_executable_policy(entry) { + policies.insert(key, policy); + } + } + for registration in state.local.registrations.iter().filter(|r| !r.removed) { + policies.insert(registration.key(), registration.process_policy()); + } + for registration in state.local.registrations.iter().filter(|r| !r.removed) { + if let Some(key) = ®istration.transferred_from { + policies.insert(key.clone(), gamenode_core::drm_free::ProcessPolicy::Ignored); + } + } + state.playtime.tracker.set_policies(policies); let effects = state.playtime.tracker.update( TrackInput::Library { account: account.clone(), @@ -200,7 +230,7 @@ impl Engine { }, gamenode_platform::random::session_id, ); - let tracker_changed = self.track_effects(state, effects); + let tracker_changed = self.track_process_effects(state, effects); state.playtime.owner = account; if changed { self.refresh_playtime_display(state); @@ -214,7 +244,7 @@ impl Engine { } /// Runs the tracker effects and returns whether there were any: any effect is a real change /// worth publishing, even when it only writes history in the background. - fn track_effects(&self, state: &mut State, effects: Vec) -> bool { + pub(super) fn track_effects(&self, state: &mut State, effects: Vec) -> bool { let changed = !effects.is_empty(); let changed_history = effects.iter().any(|e| { matches!( @@ -305,6 +335,21 @@ impl Engine { } changed } + fn track_process_effects(&self, state: &mut State, effects: Vec) -> bool { + let keys: std::collections::BTreeSet<_> = effects + .iter() + .filter_map(|effect| match effect { + TrackEffect::OpenSession(session) => Some(session.entry_key.clone()), + _ => None, + }) + .collect(); + let runtime_effects = keys + .into_iter() + .flat_map(|key| state.playtime.runtime_sessions.fence_entry(&key)) + .collect(); + let runtime_changed = self.track_effects(state, runtime_track_effects(runtime_effects)); + self.track_effects(state, effects) || runtime_changed + } fn tracker_input(&self, input: TrackInput) { let mut state = self.lock(); if state.playtime.stopped { @@ -314,7 +359,7 @@ impl Engine { .playtime .tracker .update(input, gamenode_platform::random::session_id); - self.track_effects(&mut state, effects); + self.track_process_effects(&mut state, effects); let running = state.playtime.tracker.running_started_at(); state.library.set_running(running); self.read_counters(&mut state); @@ -335,13 +380,20 @@ impl Engine { // rebuilding the whole library just to refresh the tray tooltip is wasteful, and the UI // already holds the previous snapshot. let mut changed = self.sync_tracker(&mut state); + let expired_runtime = state + .playtime + .runtime_sessions + .expire(std::time::Instant::now()); + if !expired_runtime.is_empty() { + changed |= self.track_effects(&mut state, runtime_track_effects(expired_runtime)); + } if now >= state.playtime.next_checkpoint { state.playtime.next_checkpoint = now + 60; let effects = state.playtime.tracker.update( TrackInput::Tick { now }, gamenode_platform::random::session_id, ); - changed |= self.track_effects(&mut state, effects); + changed |= self.track_process_effects(&mut state, effects); } if now >= state.playtime.next_scan { state.playtime.next_scan = now + 1800; @@ -467,6 +519,8 @@ impl Engine { gamenode_platform::random::session_id, ); self.track_effects(&mut state, effects); + let runtime_effects = state.playtime.runtime_sessions.reset(); + self.track_effects(&mut state, runtime_track_effects(runtime_effects)); state.playtime.tracker.set_floor(now); state.playtime.source = source; self.cancel_submissions(&mut state); @@ -501,6 +555,8 @@ impl Engine { gamenode_platform::random::session_id, ); self.track_effects(state, effects); + let runtime_effects = state.playtime.runtime_sessions.reset(); + self.track_effects(state, runtime_track_effects(runtime_effects)); self.cancel_submissions(state); state.library.set_running(Default::default()); } @@ -897,7 +953,7 @@ impl Engine { SubmitEffect::SessionRejected => { let engine = self.clone(); self.shared.runtime.spawn(async move { - engine.dispatch(Input::SessionRejected); + engine.dispatch_on_worker(Input::SessionRejected).await; }); } SubmitEffect::Send { submission, .. } => { @@ -1019,6 +1075,31 @@ impl Engine { } } +fn runtime_track_effects( + effects: Vec, +) -> Vec { + effects + .into_iter() + .map(|effect| match effect { + gamenode_core::tracker::runtime_sessions::Effect::Open(session) => { + TrackEffect::OpenSession(session) + } + gamenode_core::tracker::runtime_sessions::Effect::Checkpoint { id, at } => { + TrackEffect::Checkpoint { id, at } + } + gamenode_core::tracker::runtime_sessions::Effect::Close { + id, + ended_at, + game_id, + } => TrackEffect::CloseSession { + id, + ended_at, + game_id, + }, + }) + .collect() +} + /// The totals that can be submitted right now: the entry is known, its provider reports playtime /// and its game match exists. A pass and its summary both use this rule. fn submission_candidates(state: &State, totals: &[Total]) -> Vec { @@ -1037,3 +1118,59 @@ fn submission_candidates(state: &State, totals: &[Total]) -> Vec { }) .collect() } + +#[cfg(test)] +mod tests { + use super::*; + use gamenode_core::drm_free::ProcessPolicy; + use gamenode_core::library::StoredEntry; + use std::collections::BTreeMap; + + fn package_entry(key: &str, executable: Option<&str>) -> StoredEntry { + let mut fields = BTreeMap::new(); + if let Some(executable) = executable { + fields.insert("executable".to_owned(), executable.to_owned()); + } + StoredEntry { + key: key.to_owned(), + provider: "packagekit".to_owned(), + store_id: key.trim_start_matches("packagekit:").to_owned(), + name: None, + install_dir: "/usr/bin".to_owned(), + fields, + installed: true, + target: None, + owned: false, + shared: false, + first_seen: 0, + last_seen: 0, + } + } + + #[test] + fn package_manager_entries_get_an_exact_executable_policy() { + let entry = package_entry("packagekit:0ad", Some("/usr/bin/0ad")); + assert_eq!( + package_executable_policy(&entry), + Some(( + "packagekit:0ad".to_owned(), + ProcessPolicy::Explicit { + gameplay: vec!["/usr/bin/0ad".to_owned()], + launchers: Vec::new(), + }, + )) + ); + } + + #[test] + fn entries_without_an_executable_keep_the_existing_root_match() { + assert_eq!( + package_executable_policy(&package_entry("packagekit:0ad", None)), + None + ); + assert_eq!( + package_executable_policy(&package_entry("packagekit:0ad", Some(" "))), + None + ); + } +} diff --git a/crates/app/src/engine/plugin_ports.rs b/crates/app/src/engine/plugin_ports.rs new file mode 100644 index 000000000..f79b2d91b --- /dev/null +++ b/crates/app/src/engine/plugin_ports.rs @@ -0,0 +1,274 @@ +//! Plugin requests reuse the trusted guided setup and the existing PC port runner. +use super::*; +use crate::plugin_host::jobs::Fence; +use gamenode_core::ports::view::PortPluginRequest; +use gamenode_plugin_protocol::proto::PortRecord; +use pc_ports::{PortInstallRequest, PortsError}; +use tonic::Status; + +pub(super) struct PendingPort { + id: String, + catalog_id: String, + check: Fence, + started: bool, + native_job: Option, + done: Option>>, +} +struct ReviewWait { + engine: Engine, + id: String, +} +impl Drop for ReviewWait { + fn drop(&mut self) { + self.engine.close_plugin_port(&self.id); + } +} + +impl Engine { + pub(super) async fn plugin_ports_catalog( + &self, + detail: Option, + ) -> Result, Status> { + let service = self + .ports_service() + .ok_or_else(|| Status::unavailable("ports catalog unavailable"))?; + service.open(); + tokio::task::spawn_blocking(move || { + let initial = service + .build_view() + .map_err(|_| Status::unavailable("ports catalog unavailable"))?; + if initial.entries.is_empty() + && initial.catalog.state != gamenode_core::ports::view::PortCatalogState::Ready + { + return Err(Status::unavailable( + "ports catalog is loading or unavailable; retry", + )); + } + if let Some(id) = &detail + && service + .detail(id) + .map_err(|_| Status::unavailable("port details unavailable"))? + .is_none() + { + return Err(Status::not_found("port not found")); + } + let view = service + .build_view() + .map_err(|_| Status::unavailable("ports catalog unavailable"))?; + use gamenode_core::ports::view::PortCatalogState; + if !matches!( + view.catalog.state, + PortCatalogState::Ready | PortCatalogState::Stale | PortCatalogState::Refreshing + ) { + return Err(Status::unavailable( + "ports catalog is loading or unavailable; retry", + )); + } + if view.catalog.state == PortCatalogState::Refreshing && view.entries.is_empty() { + return Err(Status::unavailable("ports catalog is loading; retry")); + } + let records = view + .entries + .into_iter() + .filter(|e| detail.as_ref().is_none_or(|id| e.catalog_id == *id)) + .map(|entry| PortRecord { + port_id: entry.catalog_id, + name: entry.name, + platform: "windows".into(), + availability: if !service.is_supported() { + "unavailable" + } else if entry.installed_registration_key.is_some() { + "installed" + } else if entry.installable { + "available" + } else { + "blocked" + } + .into(), + }) + .collect::>(); + if detail.is_some() && records.is_empty() { + return Err(Status::not_found("port not found")); + } + Ok(records) + }) + .await + .map_err(|_| Status::unavailable("ports catalog worker unavailable"))? + } + + pub(super) async fn review_plugin_port( + &self, + catalog_id: String, + mut review: PortPluginRequest, + check: Fence, + ) -> Result<(), Status> { + let service = self + .ports_service() + .filter(|s| s.is_supported()) + .ok_or_else(|| Status::unavailable("port installs unavailable on this platform"))?; + // Resolve the catalog before opening the window; arbitrary URLs never become recipes. + self.plugin_ports_catalog(Some(catalog_id.clone())).await?; + let id = gamenode_platform::random::session_id(); + review.id = id.clone(); + review.catalog_id = catalog_id.clone(); + let (done, mut accepted) = tokio::sync::oneshot::channel(); + { + let mut state = self.lock(); + if state.plugin_port_request.is_some() { + return Err(Status::resource_exhausted( + "a plugin port setup is already open", + )); + } + state.plugin_port_request = Some(PendingPort { + id: id.clone(), + catalog_id, + check: check.clone(), + started: false, + native_job: None, + done: Some(done), + }); + state.ports_view.plugin_request = Some(Box::new(review)); + self.publish(&mut state); + } + let _wait = ReviewWait { + engine: self.clone(), + id: id.clone(), + }; + let deadline = Instant::now() + Duration::from_secs(300); + let native_job = loop { + tokio::select! { + answer = &mut accepted => break answer.map_err(|_| Status::cancelled("port setup closed"))??, + () = tokio::time::sleep(Duration::from_millis(100)) => { + let started = self.lock().plugin_port_request.as_ref().is_some_and(|p| p.id == id && p.started); + if !started { + let guard = check.clone(); + tokio::task::spawn_blocking(move || guard()).await.map_err(|_| Status::unavailable("port scope worker unavailable"))??; + if Instant::now() >= deadline { return Err(Status::deadline_exceeded("port setup timed out")); } + } + } + } + }; + loop { + let guard = check.clone(); + let authorized = tokio::task::spawn_blocking(move || guard()) + .await + .map_err(|_| Status::unavailable("port scope worker unavailable"))?; + if authorized.is_err() { + service.cancel(&native_job); + } + let backend = service.clone(); + let job_id = native_job.clone(); + let job = tokio::task::spawn_blocking(move || backend.plugin_job(&job_id)) + .await + .map_err(|_| Status::unavailable("port job worker unavailable"))? + .map_err(|_| Status::unavailable("port job unavailable"))? + .ok_or_else(|| Status::unavailable("port job unavailable"))?; + use gamenode_core::ports::PortJobPhase; + match job.phase { + PortJobPhase::Completed => return Ok(()), + PortJobPhase::Cancelled => { + return Err(Status::cancelled("port installation cancelled")); + } + PortJobPhase::Failed { .. } | PortJobPhase::Interrupted { .. } => { + return Err(Status::failed_precondition( + "port installation did not complete; inspect Core status", + )); + } + _ => tokio::time::sleep(Duration::from_millis(250)).await, + } + } + } + + pub(super) fn close_plugin_port(&self, id: &str) { + let mut state = self.lock(); + if state + .plugin_port_request + .as_ref() + .is_some_and(|p| p.id == id) + { + if let Some(mut pending) = state.plugin_port_request.take() { + if let Some(job) = &pending.native_job + && let Some(service) = self.ports_service() + { + service.cancel(job); + } + if let Some(done) = pending.done.take() { + let _ = done.send(Err(Status::cancelled("port setup declined"))); + } + } + state.ports_view.plugin_request = None; + self.publish(&mut state); + } + } + + pub fn dismiss_plugin_port(&self, id: String) { + let started = self + .lock() + .plugin_port_request + .as_ref() + .is_some_and(|p| p.id == id && p.started); + if started { + let mut state = self.lock(); + if state + .ports_view + .plugin_request + .as_ref() + .is_some_and(|p| p.id == id) + { + state.ports_view.plugin_request = None; + self.publish(&mut state); + } + } else { + self.close_plugin_port(&id); + } + } + + pub(super) fn plugin_port_install_check( + &self, + request: &PortInstallRequest, + ) -> Result, PortsError> { + let mut state = self.lock(); + let Some(pending) = state.plugin_port_request.as_mut() else { + return if request.plugin_request_id.is_some() { + Err(PortsError::Unavailable("port setup expired".into())) + } else { + Ok(None) + }; + }; + // A user's own setup is unrelated to the plugin review and must keep working while a + // reviewed install waits for the plugin's completion. + if request.plugin_request_id.is_none() { + return Ok(None); + } + if pending.started + || request.plugin_request_id.as_deref() != Some(&pending.id) + || request.catalog_id != pending.catalog_id + || request.retry_job_id.is_some() + { + return Err(PortsError::Unavailable( + "port setup does not match this request".into(), + )); + } + pending.started = true; + Ok(Some(pending.check.clone())) + } + + pub(super) fn plugin_port_enqueued( + &self, + id: &str, + result: &Result, PortsError>, + ) { + let mut state = self.lock(); + if let Some(pending) = state.plugin_port_request.as_mut().filter(|p| p.id == id) { + match result { + Ok(Some(job_id)) => { + pending.native_job = Some(job_id.clone()); + if let Some(done) = pending.done.take() { + let _ = done.send(Ok(job_id.clone())); + } + } + _ => pending.started = false, // Keep the same review open for a corrected user choice. + } + } + } +} diff --git a/crates/app/src/engine/providers.rs b/crates/app/src/engine/providers.rs index b16beac83..6fcb94f03 100644 --- a/crates/app/src/engine/providers.rs +++ b/crates/app/src/engine/providers.rs @@ -1,13 +1,57 @@ //! Store-neutral dispatch of provider observations through Core policy. use super::*; -use crate::plugin_host::runtime::ProviderRuntime; +use crate::plugin_host::runtime::{ProviderRuntime, RuntimeSessionHandler}; use crate::plugin_host::services::{AccountPersistence, LibraryAccounts}; use gamenode_core::snapshot::StoreAccountState; use gamenode_plugin_protocol::{ models, - proto::{AccountLoginOutcome, OperationDisposition, ProviderOperation}, + proto::{ + AccountLoginOutcome, OperationDisposition, ProviderOperation, RuntimeSessionOutcome, + RuntimeSessionReport, RuntimeSessionResult, RuntimeSessionTransition, + }, }; +/// The launch targets a provider reported for its own games, keyed by record id (task 7.7). +/// +/// A target is only a candidate: nothing here starts a process, and a target that fails the shape +/// checks is dropped with a warning, leaving the record's other facts intact. An executable target +/// keeps the record's reported install folder as its root, so its path stays relative and the +/// platform adapter can still check containment and file identity. +fn detected_targets( + provider: &str, + records: &[gamenode_plugin_protocol::proto::DiscoveryRecord], +) -> std::collections::BTreeMap { + let mut targets = std::collections::BTreeMap::new(); + for record in records { + let Some(detected) = record + .target + .as_ref() + .and_then(|target| target.target.as_ref()) + else { + continue; + }; + let spec = match detected { + gamenode_plugin_protocol::proto::detected_target::Target::Uri(uri) => { + gamenode_core::library::TargetSpec::Uri { uri: uri.clone() } + } + gamenode_plugin_protocol::proto::detected_target::Target::Executable(executable) => { + gamenode_core::library::TargetSpec::Executable { + root: record.install_dir.clone(), + path: executable.path.clone(), + arguments: executable.arguments.clone(), + working_directory: executable.working_directory.clone(), + } + } + }; + if spec.validate_shape() { + targets.insert(record.id.clone(), spec); + } else { + tracing::warn!(provider, id = %record.id, "ignored an invalid detected launch target"); + } + } + targets +} + /// This port is called only on provider storage workers. Waiting here preserves /// the Engine's database queue order without blocking a command or UI callback. pub(super) struct EngineAccounts(pub(super) std::sync::Weak); @@ -146,9 +190,377 @@ fn category( }) } +/// A reference to a library choice shown in the extension package review. The host resolves +/// it against the current library; paths and permission decisions never come from this input. +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ExtensionReadinessSelection { + installation_id: String, + revision: String, + profile_epoch: String, +} + +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ExtensionReadinessChoice { + name: String, + provider_id: String, + selection: ExtensionReadinessSelection, +} + impl Engine { + async fn authorize_runtime_context( + &self, + plugin_id: String, + publisher_fingerprint: String, + owner_key: String, + profile_epoch: u64, + request: gamenode_plugin_protocol::proto::RuntimeSessionContextRequest, + ) -> Result { + let profiles = self + .shared + .plugin_profiles + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .clone() + .ok_or_else(|| tonic::Status::unavailable("plugin profile service unavailable"))?; + let preference_plugin = plugin_id.clone(); + let accounting = self + .shared + .runtime + .spawn_blocking(move || profiles.is_playtime_accounting_enabled(&preference_plugin)) + .await + .map_err(|_| tonic::Status::unavailable("playtime preference worker unavailable"))? + .map_err(|_| tonic::Status::unavailable("playtime preference unavailable"))?; + if !accounting { + return Err(tonic::Status::permission_denied( + "plugin playtime accounting is disabled", + )); + } + let game_id = request + .game_id + .parse::() + .ok() + .filter(|id| *id > 0) + .ok_or_else(|| tonic::Status::invalid_argument("invalid game id"))?; + if request.installation_id.is_empty() + || request.runtime_id.is_empty() + || request.runtime_instance_id.is_empty() + || request.content_id.is_empty() + { + return Err(tonic::Status::invalid_argument( + "runtime context is incomplete", + )); + } + let library = self.shared.ports.library.clone(); + let installation_id = request.installation_id.clone(); + let runtime_id = request.runtime_id.clone(); + let content_id = request.content_id.clone(); + let owner = owner_key.clone(); + let bindings = self + .shared + .runtime + .spawn_blocking(move || { + library.runtime_content_bindings(&owner, game_id, &installation_id) + }) + .await + .map_err(|_| tonic::Status::unavailable("runtime binding worker unavailable"))? + .map_err(|_| tonic::Status::unavailable("runtime binding store unavailable"))?; + let binding_revision = bindings + .iter() + .find(|binding| { + binding.runtime_id == runtime_id + && binding.content_id == content_id + && binding + .supported_platforms + .iter() + .any(|platform| platform == std::env::consts::OS) + }) + .map(|binding| binding.revision) + .ok_or_else(|| { + tonic::Status::permission_denied("runtime content binding is not approved") + })?; + + let library_revision = self + .shared + .library_feed + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .as_ref() + .and_then(|feed| feed.revision_of(&request.installation_id)) + .ok_or_else(|| { + tonic::Status::permission_denied("installation is not in the host library") + })?; + + let game_name = { + let state = self.lock(); + let Some(entry) = state.library.entry(&request.installation_id) else { + return Err(tonic::Status::permission_denied( + "installation is not in the library", + )); + }; + if state.library.match_status(entry).game_id() != Some(game_id) { + return Err(tonic::Status::permission_denied( + "installation belongs to another game", + )); + } + entry + .record() + .name + .unwrap_or_else(|| format!("Game {game_id}")) + }; + let api = self + .shared + .selected_launch_api + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .clone() + .ok_or_else(|| { + tonic::Status::unavailable("runtime context confirmation is unavailable") + })?; + if !api + .confirm_runtime_context( + plugin_id, + publisher_fingerprint, + profile_epoch, + request.game_id.clone(), + request.installation_id.clone(), + game_name, + ) + .await? + { + Err(tonic::Status::permission_denied( + "runtime context was not approved", + )) + } else { + let library = self.shared.ports.library.clone(); + let owner = owner_key; + let installation_id = request.installation_id.clone(); + let runtime_id = request.runtime_id.clone(); + let content_id = request.content_id.clone(); + let refreshed = self + .shared + .runtime + .spawn_blocking(move || { + library.runtime_content_bindings(&owner, game_id, &installation_id) + }) + .await + .map_err(|_| tonic::Status::unavailable("runtime binding worker unavailable"))? + .map_err(|_| tonic::Status::unavailable("runtime binding store unavailable"))?; + let current_binding_revision = refreshed + .iter() + .find(|binding| { + binding.runtime_id == runtime_id + && binding.content_id == content_id + && binding + .supported_platforms + .iter() + .any(|platform| platform == std::env::consts::OS) + }) + .map(|binding| binding.revision); + let current_library_revision = self + .shared + .library_feed + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .as_ref() + .and_then(|feed| feed.revision_of(&request.installation_id)); + if current_binding_revision != Some(binding_revision) + || current_library_revision != Some(library_revision) + { + return Err(tonic::Status::failed_precondition( + "runtime target changed during confirmation", + )); + } + Ok(crate::plugin_host::runtime::RuntimeContextRevision { + library_revision, + binding_revision, + }) + } + } + + fn extension_readiness_library( + &self, + ) -> Result< + ( + crate::plugin_host::profile::ProfileContext, + Arc, + ), + tonic::Status, + > { + let profiles = self + .shared + .plugin_profiles + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .clone() + .ok_or_else(|| tonic::Status::unavailable("plugin profiles are unavailable"))?; + let feed = self + .shared + .library_feed + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .clone() + .ok_or_else(|| tonic::Status::unavailable("the game library is unavailable"))?; + let profile = profiles.require()?; + if !profile.verified() { + return Err(tonic::Status::failed_precondition( + "a verified account is required", + )); + } + Ok((profile, feed)) + } + + pub fn extension_readiness_choices(&self) -> Vec { + // A profile transition publishes the new library under the engine lock. + let _state = self.lock(); + let Ok((profile, feed)) = self.extension_readiness_library() else { + return Vec::new(); + }; + feed.readiness_targets() + .into_iter() + .map( + |(installation_id, name, provider_id, revision)| ExtensionReadinessChoice { + name, + provider_id, + selection: ExtensionReadinessSelection { + installation_id, + revision: revision.to_string(), + profile_epoch: profile.epoch().to_string(), + }, + }, + ) + .collect() + } + + pub fn resolve_extension_readiness( + &self, + selection: ExtensionReadinessSelection, + ) -> Result { + let _state = self.lock(); + let (profile, feed) = self.extension_readiness_library()?; + let stale = || tonic::Status::failed_precondition("the selected extension target changed"); + if selection.profile_epoch != profile.epoch().to_string() { + return Err(stale()); + } + let revision = selection.revision.parse().map_err(|_| stale())?; + let game_id = feed + .readiness_game(&selection.installation_id, revision) + .ok_or_else(stale)?; + let installation_id = selection.installation_id; + Ok(crate::plugin_host::process::ExtensionTarget { + context: gamenode_plugin_protocol::proto::TargetGameContext { + game_id: game_id.to_string(), + installation_id: installation_id.clone(), + profile_id: profile.profile_id().to_owned(), + revision: revision.to_string(), + }, + profile_epoch: profile.epoch(), + still_selected: Arc::new(move || { + feed.readiness_game(&installation_id, revision) == Some(game_id) + }), + }) + } + + pub async fn available_extensions( + &self, + operation: crate::plugin_host::intents::Operation, + ) -> Result, tonic::Status> { + self.provider_runtime() + .ok_or_else(|| tonic::Status::unavailable("plugin runtime is unavailable"))? + .available_extensions(operation) + .await + } + + pub async fn start_extension_action( + &self, + entry_key: &str, + plugin_id: &str, + operation: crate::plugin_host::intents::Operation, + ) -> Result<(), tonic::Status> { + let profile = self + .shared + .plugin_profiles + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .clone() + .ok_or_else(|| tonic::Status::unavailable("plugin profiles are unavailable"))? + .require()?; + let feed = self + .shared + .library_feed + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .clone() + .ok_or_else(|| tonic::Status::unavailable("the game library is unavailable"))?; + let (source, projected) = feed + .projected_entry(entry_key) + .ok_or_else(|| tonic::Status::not_found("the selected installation is unavailable"))?; + if operation == crate::plugin_host::intents::Operation::Launch + && source.install_state != crate::plugin_host::library::InstallState::Installed + { + return Err(tonic::Status::failed_precondition( + "extension actions require an installed game", + )); + } + let game_id = projected + .game_id + .ok_or_else(|| tonic::Status::failed_precondition("the game is not matched"))? + .to_string(); + let target_revision = match operation { + crate::plugin_host::intents::Operation::Launch => { + feed.host() + .ok_or_else(|| tonic::Status::unavailable("the game library is unavailable"))? + .launch_fingerprint(entry_key.to_owned()) + .await? + } + crate::plugin_host::intents::Operation::Install => 0, + _ => { + return Err(tonic::Status::invalid_argument( + "unsupported extension action", + )); + } + }; + let runtime = self + .provider_runtime() + .ok_or_else(|| tonic::Status::unavailable("plugin runtime is unavailable"))?; + let selected_key = entry_key.to_owned(); + let installation_id = projected.installation_id.clone(); + let still_selected = Arc::new(move || { + feed.projected_entry(&selected_key) + .is_some_and(|(current, entry)| { + entry.installation_id == installation_id + && current.provider_id == source.provider_id + && current.game_id == source.game_id + && current.install_dir == source.install_dir + && (operation != crate::plugin_host::intents::Operation::Launch + || current.install_state + == crate::plugin_host::library::InstallState::Installed) + }) + }); + runtime + .start_extension( + plugin_id, + crate::plugin_host::process::ExtensionTarget { + context: gamenode_plugin_protocol::proto::TargetGameContext { + game_id, + installation_id: projected.installation_id, + profile_id: profile.profile_id().to_owned(), + revision: target_revision.to_string(), + }, + profile_epoch: profile.epoch(), + still_selected, + }, + operation, + ) + .await + } + pub fn set_provider_runtime(&self, runtime: Arc) { runtime.set_account_persistence(Arc::new(EngineAccounts(Arc::downgrade(&self.shared)))); + runtime.set_runtime_session_handler(Arc::new(EngineRuntimeSessionHandler(Arc::downgrade( + &self.shared, + )))); let weak = Arc::downgrade(&self.shared); let background = self.shared.runtime.clone(); runtime.set_observer(Arc::new(move || { @@ -165,6 +577,350 @@ impl Engine { .lock() .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(runtime); } + + /// Accepts authenticated runtime evidence after validating it against the host-owned content + /// binding and the current library/account state. Blocking database reads run on Tokio's + /// worker pool; only the short in-memory arbitration and effect scheduling use the engine lock. + pub(super) async fn report_runtime_session( + &self, + plugin_id: String, + owner_key: String, + report: RuntimeSessionReport, + context_authorized: bool, + context_revision: Option, + received_at: std::time::Instant, + ) -> RuntimeSessionResult { + let correlation_id = report.correlation_id.clone(); + let profiles = self + .shared + .plugin_profiles + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .clone(); + let Some(profiles) = profiles else { + return runtime_result( + correlation_id, + RuntimeSessionOutcome::RejectedUnavailable, + "plugin profile service unavailable", + ); + }; + let accounting_plugin_id = plugin_id.clone(); + let accounting_enabled = self + .shared + .runtime + .spawn_blocking(move || profiles.is_playtime_accounting_enabled(&accounting_plugin_id)) + .await; + match accounting_enabled { + Ok(Ok(true)) => {} + Ok(Ok(false)) => { + return runtime_result( + correlation_id, + RuntimeSessionOutcome::RejectedUnavailable, + "plugin playtime accounting is disabled", + ); + } + _ => { + return runtime_result( + correlation_id, + RuntimeSessionOutcome::RejectedUnavailable, + "plugin playtime preference unavailable", + ); + } + } + let game_id = match report.game_id.parse::() { + Ok(id) if id > 0 => id, + _ => { + return runtime_result( + correlation_id, + RuntimeSessionOutcome::RejectedInvalid, + "invalid game id", + ); + } + }; + let installation_for_read = report.installation_id.clone(); + let runtime_id_for_read = report.runtime_id.clone(); + let content_id_for_read = report.content_id.clone(); + let library = self.shared.ports.library.clone(); + let bindings = match self + .shared + .runtime + .spawn_blocking(move || { + library.runtime_content_bindings(&owner_key, game_id, &installation_for_read) + }) + .await + { + Ok(Ok(bindings)) => bindings, + _ => { + return runtime_result( + correlation_id, + RuntimeSessionOutcome::RejectedUnavailable, + "runtime binding store unavailable", + ); + } + }; + let binding = bindings.iter().find(|binding| { + binding.runtime_id == runtime_id_for_read + && binding.content_id == content_id_for_read + && binding + .supported_platforms + .iter() + .any(|platform| platform == std::env::consts::OS) + }); + if binding.is_none() { + return runtime_result( + correlation_id, + RuntimeSessionOutcome::RejectedUnauthorized, + "content/runtime binding is not approved", + ); + } + if context_authorized { + let Some(expected) = context_revision else { + return runtime_result( + correlation_id, + RuntimeSessionOutcome::RejectedUnauthorized, + "approved runtime context revision is missing", + ); + }; + let current_library_revision = self + .shared + .library_feed + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .as_ref() + .and_then(|feed| feed.revision_of(&report.installation_id)); + if binding.map(|binding| binding.revision) != Some(expected.binding_revision) + || current_library_revision != Some(expected.library_revision) + { + return runtime_result( + correlation_id, + RuntimeSessionOutcome::RejectedStale, + "runtime target changed after context approval", + ); + } + } + + let mut state = self.lock(); + if !state.playtime.ready || state.playtime.is_stopped() { + return runtime_result( + correlation_id, + RuntimeSessionOutcome::RejectedUnavailable, + "playtime service unavailable", + ); + } + let Some(account) = state.library.account().map(|account| account.id.clone()) else { + return runtime_result( + correlation_id, + RuntimeSessionOutcome::RejectedUnavailable, + "account profile unavailable", + ); + }; + let Some(entry) = state.library.entry(&report.installation_id) else { + return runtime_result( + correlation_id, + RuntimeSessionOutcome::RejectedUnauthorized, + "installation is not in the library", + ); + }; + if state.library.match_status(entry).game_id() != Some(game_id) { + return runtime_result( + correlation_id, + RuntimeSessionOutcome::RejectedUnauthorized, + "installation belongs to another game", + ); + } + let process_evidence_running = state.playtime.tracker.running().contains(&entry.key); + let source = state.library.provider(&entry.provider).map_or_else( + || entry.provider.clone(), + |provider| provider.source().to_owned(), + ); + let has_counter = state + .library + .provider(&entry.provider) + .is_some_and(|provider| provider.manifest().playtime.is_some()); + match runtime_report_source_conflict( + process_evidence_running, + state.playtime.source.uses_counter(has_counter), + ) { + Some(RuntimeReportSourceConflict::ProcessEvidence) => { + return runtime_result( + correlation_id, + RuntimeSessionOutcome::Duplicate, + "process evidence already measures this installation", + ); + } + Some(RuntimeReportSourceConflict::ProviderCounter) => { + return runtime_result( + correlation_id, + RuntimeSessionOutcome::RejectedUnavailable, + "selected playtime source is the provider counter", + ); + } + None => {} + } + let transition = match RuntimeSessionTransition::try_from(report.transition) { + Ok(RuntimeSessionTransition::Identified) => { + gamenode_core::tracker::runtime_sessions::Transition::Identified + } + Ok(RuntimeSessionTransition::Started) => { + gamenode_core::tracker::runtime_sessions::Transition::Started + } + Ok(RuntimeSessionTransition::Paused) => { + gamenode_core::tracker::runtime_sessions::Transition::Paused + } + Ok(RuntimeSessionTransition::Resumed) => { + gamenode_core::tracker::runtime_sessions::Transition::Resumed + } + Ok(RuntimeSessionTransition::ContentChanged) => { + gamenode_core::tracker::runtime_sessions::Transition::ContentChanged + } + Ok(RuntimeSessionTransition::Ended) => { + gamenode_core::tracker::runtime_sessions::Transition::Ended + } + Ok(RuntimeSessionTransition::IdentificationLost) => { + gamenode_core::tracker::runtime_sessions::Transition::IdentificationLost + } + _ => { + return runtime_result( + correlation_id, + RuntimeSessionOutcome::RejectedInvalid, + "invalid transition", + ); + } + }; + let now = unix_now(); + let observation = gamenode_core::tracker::runtime_sessions::Report { + correlation_id: report.correlation_id.clone(), + game_id, + installation_id: report.installation_id.clone(), + content_id: report.content_id, + runtime_id: report.runtime_id, + runtime_instance_id: report.runtime_instance_id, + reporter_session_id: report.reporter_session_id, + sequence: report.sequence, + observed_at: report.observed_at, + transition, + source_observation_id: report.source_observation_id, + context_authorized, + received_at, + }; + let (outcome, effects) = state.playtime.runtime_sessions.report( + &plugin_id, + &account, + &source, + observation, + now, + gamenode_platform::random::session_id, + ); + let (outcome, host_session_id, reason, accepted) = match outcome { + gamenode_core::tracker::runtime_sessions::Outcome::Accepted { host_session_id } => ( + RuntimeSessionOutcome::Accepted, + host_session_id.unwrap_or_default(), + String::new(), + true, + ), + gamenode_core::tracker::runtime_sessions::Outcome::Duplicate => ( + RuntimeSessionOutcome::Duplicate, + String::new(), + "duplicate evidence".into(), + true, + ), + gamenode_core::tracker::runtime_sessions::Outcome::Invalid(reason) => ( + RuntimeSessionOutcome::RejectedInvalid, + String::new(), + reason.into(), + false, + ), + gamenode_core::tracker::runtime_sessions::Outcome::Stale => ( + RuntimeSessionOutcome::RejectedStale, + String::new(), + "report is outside the freshness window".into(), + false, + ), + gamenode_core::tracker::runtime_sessions::Outcome::Conflict(reason) => ( + RuntimeSessionOutcome::RejectedConflict, + String::new(), + reason.into(), + false, + ), + gamenode_core::tracker::runtime_sessions::Outcome::Unavailable(reason) => ( + RuntimeSessionOutcome::RejectedUnavailable, + String::new(), + reason.into(), + false, + ), + }; + self.track_effects(&mut state, runtime_track_effects(effects)); + self.publish(&mut state); + RuntimeSessionResult { + correlation_id, + outcome: outcome as i32, + host_session_id, + accepted_sequence: if accepted { report.sequence } else { 0 }, + accepted_at: if accepted { now } else { 0 }, + reason, + denial: None, + } + } + + /// Persist a per-plugin playtime preference. Disabling fences active runtime sessions at + /// their last accepted observation while preserving all completed history. + pub async fn set_plugin_playtime_accounting( + &self, + plugin_id: String, + enabled: bool, + ) -> Result<(), String> { + let profiles = self + .shared + .plugin_profiles + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .clone() + .ok_or_else(|| "plugin profiles are unavailable".to_owned())?; + let persisted_plugin_id = plugin_id.clone(); + self.shared + .runtime + .spawn_blocking(move || { + profiles + .set_playtime_accounting_enabled(&persisted_plugin_id, enabled) + .map_err(|error| error.message().to_owned()) + }) + .await + .map_err(|_| "plugin accounting preference worker failed".to_owned())??; + if !enabled { + self.fence_runtime_sessions(&plugin_id); + } + Ok(()) + } + + pub async fn plugin_playtime_accounting_enabled( + &self, + plugin_id: String, + ) -> Result { + let profiles = self + .shared + .plugin_profiles + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .clone() + .ok_or_else(|| "plugin profiles are unavailable".to_owned())?; + self.shared + .runtime + .spawn_blocking(move || { + profiles + .is_playtime_accounting_enabled(&plugin_id) + .map_err(|error| error.message().to_owned()) + }) + .await + .map_err(|_| "plugin accounting preference worker failed".to_owned())? + } + + fn fence_runtime_sessions(&self, plugin_id: &str) { + let mut state = self.lock(); + let effects = state.playtime.runtime_sessions.fence_plugin(plugin_id); + let effects = runtime_track_effects(effects); + self.track_effects(&mut state, effects); + self.publish(&mut state); + } pub fn provider_health(&self, id: &str) -> (bool, bool) { self.provider_runtime() .map(|runtime| (runtime.available(id), runtime.connected(id))) @@ -177,6 +933,12 @@ impl Engine { .unwrap_or("unavailable") } + pub fn managed_plugin_inventory(&self) -> Vec { + self.provider_runtime() + .map(|runtime| runtime.managed_plugin_inventory()) + .unwrap_or_default() + } + pub(super) fn provider_runtime(&self) -> Option> { self.shared .providers @@ -330,6 +1092,37 @@ impl Engine { self.publish_current(); Ok(()) } + /// Adds or replaces one provider in the running library and requests a scan. + /// + /// The accepted import has already registered and enabled the package with the live host; + /// this only makes the existing library list and scan it. A scan already running coalesces + /// the request into one more run, so the caller never waits for provider I/O. + pub fn add_library_provider(&self, provider: gamenode_core::provider::Provider) { + let id = provider.id().to_owned(); + { + let mut state = self.lock(); + state.library.put_provider(provider); + self.publish(&mut state); + } + tracing::info!(provider = %id, "added an imported provider to the library"); + self.rescan(); + } + + /// Removes an uninstalled provider and its live rows from the running library. + /// + /// Commands pass the installed plugin id, which may differ from the provider id a package + /// contributes (for example `dolphin-emu`); the machine resolves the store by its discovery + /// plugin. A direct provider id is still accepted. The persisted cache keeps the rows so a + /// later reinstall can restore them; the library view stops showing the store immediately, + /// and a running scan no longer waits for it. + pub fn remove_library_provider(&self, id: &str) { + let mut state = self.lock(); + if state.library.remove_provider_for_plugin(id) || state.library.remove_provider(id) { + self.publish(&mut state); + tracing::info!(provider = %id, "removed an uninstalled provider from the library"); + } + } + fn provider_check_gate(&self, provider: &str) -> Arc> { self.shared .provider_checks @@ -407,51 +1200,58 @@ impl Engine { let failed_provider = provider.clone(); let committed = completion .commit(move |result, _| { - let completed = - result.disposition == OperationDisposition::Completed as i32; - let discovery = if completed { - result.discovery.filter(|d| d.provider_id == provider) - } else { - None - }; - // The location travels with the scan answer, before the records, so - // the library stores both under the same scan op. A successful scan - // without a location clears the previous one; a failed scan keeps it. - if let Some(located) = &discovery { - engine.library_input(LibInput::ProviderLocated { - op, - provider: provider.clone(), - install_root: located.install_root.clone(), - library_folders: located.library_folders, - }); - } - let result = discovery - .map(|d| { - gamenode_core::provider::record::finish_records( - &provider, - d.records + let mut scanned = None; + let result = if result.disposition + == OperationDisposition::Completed as i32 + { + result + .discovery + .filter(|d| d.provider_id == provider) + .map(|d| { + // Targets are collected before the records are + // flattened, so a provider's typed target can never + // be mistaken for a template field. + engine.library_input(LibInput::ProviderLocated { + op, + provider: provider.clone(), + install_root: d.install_root.clone(), + library_folders: d.library_folders, + }); + let detected = detected_targets(&provider, &d.records); + let records = + gamenode_core::provider::record::finish_records( + &provider, + d.records + .into_iter() + .map(|r| gamenode_core::provider::RawRecord { + id: Some(r.id), + name: Some(r.name), + install_dir: Some(r.install_dir), + fields: r.fields.into_iter().collect(), + }) + .collect(), + &found.manifest().exclude_ids, + ); + let targets = detected .into_iter() - .map(|r| gamenode_core::provider::RawRecord { - id: Some(r.id), - name: Some(r.name), - install_dir: Some(r.install_dir), - fields: r.fields.into_iter().collect(), + .filter(|(id, _)| { + records.iter().any(|record| &record.id == id) }) - .collect(), - &found.manifest().exclude_ids, - ) - }) - .ok_or_else(|| { - if completed { + .collect(); + scanned = Some(targets); + records + }) + .ok_or_else(|| { "provider discovery returned no observations".into() - } else { - "provider discovery failed".into() - } - }); + }) + } else { + Err("provider discovery failed".into()) + }; engine.library_input(LibInput::ProviderScanned { op, provider, result, + targets: scanned.unwrap_or_default(), now: unix_now(), }); }) @@ -461,6 +1261,7 @@ impl Engine { op, provider: failed_provider, result: Err("provider discovery superseded".into()), + targets: Default::default(), now: unix_now(), }); } @@ -469,6 +1270,7 @@ impl Engine { op, provider, result: Err("provider discovery unavailable".into()), + targets: Default::default(), now: unix_now(), }), } @@ -622,3 +1424,143 @@ impl Engine { } } } + +fn runtime_result( + correlation_id: String, + outcome: RuntimeSessionOutcome, + reason: &str, +) -> RuntimeSessionResult { + RuntimeSessionResult { + correlation_id, + outcome: outcome as i32, + host_session_id: String::new(), + accepted_sequence: 0, + accepted_at: 0, + reason: reason.to_owned(), + denial: None, + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum RuntimeReportSourceConflict { + ProcessEvidence, + ProviderCounter, +} + +fn runtime_report_source_conflict( + process_evidence_running: bool, + provider_counter_selected: bool, +) -> Option { + if process_evidence_running { + Some(RuntimeReportSourceConflict::ProcessEvidence) + } else if provider_counter_selected { + Some(RuntimeReportSourceConflict::ProviderCounter) + } else { + None + } +} + +fn runtime_track_effects( + effects: Vec, +) -> Vec { + effects + .into_iter() + .map(|effect| match effect { + gamenode_core::tracker::runtime_sessions::Effect::Open(session) => { + gamenode_core::tracker::Effect::OpenSession(session) + } + gamenode_core::tracker::runtime_sessions::Effect::Checkpoint { id, at } => { + gamenode_core::tracker::Effect::Checkpoint { id, at } + } + gamenode_core::tracker::runtime_sessions::Effect::Close { + id, + ended_at, + game_id, + } => gamenode_core::tracker::Effect::CloseSession { + id, + ended_at, + game_id, + }, + }) + .collect() +} + +struct EngineRuntimeSessionHandler(std::sync::Weak); + +#[tonic::async_trait] +impl RuntimeSessionHandler for EngineRuntimeSessionHandler { + async fn authorize_context( + &self, + plugin_id: String, + publisher_fingerprint: String, + owner_key: String, + profile_epoch: u64, + request: gamenode_plugin_protocol::proto::RuntimeSessionContextRequest, + ) -> Result { + let shared = self + .0 + .upgrade() + .ok_or_else(|| tonic::Status::unavailable("playtime engine unavailable"))?; + Engine { shared } + .authorize_runtime_context( + plugin_id, + publisher_fingerprint, + owner_key, + profile_epoch, + request, + ) + .await + } + + async fn report( + &self, + plugin_id: String, + owner_key: String, + report: RuntimeSessionReport, + context_authorized: bool, + context_revision: Option, + received_at: std::time::Instant, + ) -> RuntimeSessionResult { + let Some(shared) = self.0.upgrade() else { + return runtime_result( + report.correlation_id, + RuntimeSessionOutcome::RejectedUnavailable, + "playtime engine unavailable", + ); + }; + Engine { shared } + .report_runtime_session( + plugin_id, + owner_key, + report, + context_authorized, + context_revision, + received_at, + ) + .await + } + + async fn disconnected(&self, plugin_id: String) { + if let Some(shared) = self.0.upgrade() { + Engine { shared }.fence_runtime_sessions(&plugin_id); + } + } +} + +#[cfg(test)] +mod runtime_report_source_tests { + use super::{RuntimeReportSourceConflict, runtime_report_source_conflict}; + + #[test] + fn plugin_playtime_is_not_double_counted_with_host_process_or_provider_counter_evidence() { + assert_eq!( + runtime_report_source_conflict(true, false), + Some(RuntimeReportSourceConflict::ProcessEvidence) + ); + assert_eq!( + runtime_report_source_conflict(false, true), + Some(RuntimeReportSourceConflict::ProviderCounter) + ); + assert_eq!(runtime_report_source_conflict(false, false), None); + } +} diff --git a/crates/app/src/engine/tests.rs b/crates/app/src/engine/tests.rs index 8231f3191..9eca042cd 100644 --- a/crates/app/src/engine/tests.rs +++ b/crates/app/src/engine/tests.rs @@ -699,6 +699,8 @@ struct Harness { uri: Arc, covers: tempfile::TempDir, achievements: Arc, + /// Achievement calls seen by this harness's fixture provider runtime. + achievement_probe: Arc, } fn harness(api: Arc, creds: Arc) -> Harness { @@ -744,6 +746,7 @@ fn harness_with_providers( let processes = Arc::new(gamenode_core::tracker::scripted::ScriptedProcesses::default()); let achievements = test_achievement_store(); let ports = Ports { + discovery: None, achievements: achievements.clone(), backups: None, local_games: None, @@ -803,17 +806,21 @@ fn harness_with_providers( }); let publishes = Arc::new(AtomicUsize::new(0)); let publish_count = publishes.clone(); + let runtime = Arc::new(provider_runtime::Runtime::new(&ports)); + let achievement_probe = runtime.achievement_probe(); let engine = Engine::new( ports, tokio::runtime::Handle::current(), Settings::default(), LibraryMachine::new(providers, Default::default()), nonce, + Arc::new(crate::plugin_host::resource_leases::ResourceLeases::default()), move |s| { publish_count.fetch_add(1, Ordering::SeqCst); let _ = tx.send(s); }, ); + engine.set_provider_runtime(runtime); Harness { processes, engine, @@ -828,6 +835,7 @@ fn harness_with_providers( uri, covers, achievements, + achievement_probe, } } @@ -1803,3 +1811,37 @@ async fn corrupt_artwork_is_replaced_and_failures_can_be_retried() { ); assert_eq!(std::fs::read(dir.path().join("7.jpg")).unwrap(), bytes); } + +#[test] +fn runtime_launch_summary_shows_the_runtime_and_content_argument() { + use gamenode_core::library::{ + ApprovedFileReference, CustomLaunchRecipe, RuntimeArgumentTemplate, RuntimeResource, + }; + + let runtime = RuntimeResource { + id: "runtime-1".into(), + name: "Dolphin".into(), + version: "2609".into(), + executable: ApprovedFileReference::default(), + platform: "linux".into(), + supported_formats: vec!["gamecube-rom".into()], + launch_arguments: vec![ + RuntimeArgumentTemplate::Literal("-b".into()), + RuntimeArgumentTemplate::Literal("-e".into()), + RuntimeArgumentTemplate::ContentPath, + ], + revision: 1, + observed_at: 0, + provenance: Default::default(), + extensions: Default::default(), + }; + let recipe = CustomLaunchRecipe { + runtime_handle: "runtime-1".into(), + ..CustomLaunchRecipe::default() + }; + + assert_eq!( + super::runtime_launch_summary(Some(&runtime), &recipe, "Pikmin (USA) (Rev 1).rvz"), + "Dolphin 2609 — -b -e Pikmin (USA) (Rev 1).rvz" + ); +} diff --git a/crates/app/src/engine/tests/achievements.rs b/crates/app/src/engine/tests/achievements.rs index 4b8e4bb50..01c29f395 100644 --- a/crates/app/src/engine/tests/achievements.rs +++ b/crates/app/src/engine/tests/achievements.rs @@ -2,7 +2,7 @@ use super::*; -/// Achievement tests share the test provider runtime's concurrency counter. +/// Achievement scheduler tests drive tight timeouts; running them one at a time keeps them stable. static ACHIEVEMENT_TEST_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); use gamenode_core::achievements::{ @@ -21,6 +21,7 @@ fn entry(store_id: &str) -> StoredEntry { install_dir: format!("Game {store_id}"), fields: Default::default(), installed: true, + target: None, owned: false, shared: false, first_seen: 1, @@ -765,7 +766,7 @@ async fn achievement_batches_are_dispatched_one_at_a_time() { panic!("every achievement batch completes; saved={saved} queue={queue:?}"); } assert_eq!( - super::provider_runtime::ACHIEVEMENT_MAX_ACTIVE.load(Ordering::SeqCst), + h.achievement_probe.max_active.load(Ordering::SeqCst), 1, "a single provider never has two achievement batches in flight" ); @@ -820,6 +821,7 @@ async fn sync_with_gamenode_does_not_send_achievement_data() { fn owned_entry(store_id: &str) -> StoredEntry { StoredEntry { installed: false, + target: None, owned: true, ..entry(store_id) } @@ -946,7 +948,7 @@ async fn a_failed_execute_is_requeued_and_reads_the_same_game_after_recovery() { .lock() .achievement_summaries .remove(&("steam".to_owned(), "620".to_owned())); - super::provider_runtime::ACHIEVEMENT_FAIL_NEXT.store(true, Ordering::SeqCst); + h.achievement_probe.fail_next.store(true, Ordering::SeqCst); h.engine .refresh_selected_achievements("steam:620".to_owned()); @@ -962,7 +964,7 @@ async fn a_failed_execute_is_requeued_and_reads_the_same_game_after_recovery() { .await; wait.expect("the requeued batch succeeds after the transient failure"); assert!( - !super::provider_runtime::ACHIEVEMENT_FAIL_NEXT.load(Ordering::SeqCst), + !h.achievement_probe.fail_next.load(Ordering::SeqCst), "the injected failure was consumed" ); } @@ -981,6 +983,15 @@ async fn a_rate_limit_pause_still_runs_selected_work_but_holds_import_work() { .is_some_and(|library| library.rows.len() == 2) }) .await; + // Let the startup import finish first: a batch still in flight would save "70" after the + // pause below is installed and look like import work that ignored it. + let imported = tokio::time::timeout(Duration::from_secs(5), async { + while h.achievements.load_summaries("steam", "A").unwrap().len() < 2 { + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await; + imported.expect("the startup import saves both games"); wait_worker_idle(&h).await; h.achievements.delete_account("steam", "A").unwrap(); { diff --git a/crates/app/src/engine/tests/catalog.rs b/crates/app/src/engine/tests/catalog.rs index 41057ab41..6bc5276a2 100644 --- a/crates/app/src/engine/tests/catalog.rs +++ b/crates/app/src/engine/tests/catalog.rs @@ -89,6 +89,7 @@ async fn a_selected_unmatched_entry_gets_engine_fetched_suggestions_and_can_use_ name: Some("hollow_knight".to_owned()), install_dir: "/games/Hollow_Knight_2017".to_owned(), fields: Default::default(), + target: None, installed: false, owned: true, shared: false, diff --git a/crates/app/src/engine/tests/drm_free.rs b/crates/app/src/engine/tests/drm_free.rs index 5746c6f33..0d776a373 100644 --- a/crates/app/src/engine/tests/drm_free.rs +++ b/crates/app/src/engine/tests/drm_free.rs @@ -1220,6 +1220,134 @@ async fn windows_watched_folder_produces_review_candidates() { .unwrap(); } +#[derive(Default)] +struct LibraryRootScanner { + calls: Mutex>, +} +impl gamenode_core::drm_free::DiscoveryHost for LibraryRootScanner { + fn discover( + &self, + root: &WatchRoot, + _cancel: &std::sync::atomic::AtomicBool, + ) -> Result { + self.calls.lock().unwrap().push(root.path.clone()); + Ok(Default::default()) + } +} +fn plugin_scan_root( + path: &std::path::Path, + id: &str, +) -> crate::plugin_host::library::PluginScanRoot { + let approved = + gamenode_platform::plugin_files::approve_root(path, &Default::default()).unwrap(); + let volume = gamenode_platform::volume::volume_info(&approved.path).unwrap(); + crate::plugin_host::library::PluginScanRoot { + root: gamenode_platform::plugin_storage::PluginLibraryRoot { + id: id.into(), + name: "Root".into(), + path: approved.path.to_str().unwrap().into(), + volume: approved.identity.volume, + node: approved.identity.node, + volume_token: volume.volume_identity_token, + declared: false, + watching: true, + }, + valid: Arc::new(|| Ok(())), + } +} + +#[cfg(unix)] +#[tokio::test(flavor = "multi_thread")] +async fn plugin_roots_deduplicate_aliases_and_overlap_preserve_legacy_watches_and_skip_unavailable_volumes() + { + use crate::plugin_host::library::LibraryHost; + let base = tempfile::tempdir().unwrap(); + let games = base.path().join("games"); + let child = games.join("child"); + let offline = base.path().join("offline"); + std::fs::create_dir_all(&child).unwrap(); + std::fs::create_dir(&offline).unwrap(); + std::fs::write(offline.join("save"), b"keep").unwrap(); + let alias = base.path().join("alias"); + std::os::unix::fs::symlink(&games, &alias).unwrap(); + let database = gamenode_platform::db::SqliteSettingsStore::new( + gamenode_platform::db::open(std::path::Path::new(":memory:")).unwrap(), + ); + let store = Arc::new(database.local_game_store()); + store + .save_watch(&WatchRoot { + id: "legacy".into(), + path: alias.to_str().unwrap().into(), + enabled: true, + ..Default::default() + }) + .unwrap(); + let scanner = Arc::new(LibraryRootScanner::default()); + let mut h = harness(FakeApi::new(), FakeCreds::with(None)); + let ports = &mut Arc::get_mut(&mut h.engine.shared).unwrap().ports; + ports.local_games = Some(store.clone()); + ports.discovery = Some(scanner.clone()); + let host = super::super::PluginLibraryHost { + shared: Arc::downgrade(&h.engine.shared), + }; + let unavailable = plugin_scan_root(&offline, "offline"); + let away = offline.with_extension("away"); + std::fs::rename(&offline, &away).unwrap(); + host.set_plugin_roots( + "plugin/account".into(), + vec![ + plugin_scan_root(&games, "same"), + plugin_scan_root(&child, "child"), + unavailable, + ], + ) + .unwrap(); + eventually(|| { + !h.engine.snapshot().local_games.discovery_scanning + && scanner.calls.lock().unwrap().len() == 1 + }) + .await; + assert_eq!(scanner.calls.lock().unwrap()[0], games.to_str().unwrap()); + assert!(!offline.exists()); + assert_eq!(std::fs::read(away.join("save")).unwrap(), b"keep"); + host.set_plugin_roots("plugin/account".into(), vec![]) + .unwrap(); + eventually(|| { + !h.engine.snapshot().local_games.discovery_scanning + && scanner.calls.lock().unwrap().len() == 2 + }) + .await; + assert!(store.watches().unwrap()[0].enabled); + assert_eq!(store.watches().unwrap()[0].id, "legacy"); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_revoked_plugin_root_never_reaches_the_core_scanner() { + use crate::plugin_host::library::LibraryHost; + let folder = tempfile::tempdir().unwrap(); + let mut root = plugin_scan_root(folder.path(), "revoked"); + root.valid = Arc::new(|| Err(tonic::Status::permission_denied("revoked"))); + let database = gamenode_platform::db::SqliteSettingsStore::new( + gamenode_platform::db::open(std::path::Path::new(":memory:")).unwrap(), + ); + let scanner = Arc::new(LibraryRootScanner::default()); + let mut h = harness(FakeApi::new(), FakeCreds::with(None)); + let ports = &mut Arc::get_mut(&mut h.engine.shared).unwrap().ports; + ports.local_games = Some(Arc::new(database.local_game_store())); + ports.discovery = Some(scanner.clone()); + let host = super::super::PluginLibraryHost { + shared: Arc::downgrade(&h.engine.shared), + }; + host.set_plugin_roots("plugin/account".into(), vec![root]) + .unwrap(); + eventually(|| { + h.engine.snapshot().local_games.discovery_completed + && !h.engine.snapshot().local_games.discovery_scanning + }) + .await; + assert!(scanner.calls.lock().unwrap().is_empty()); +} + #[tokio::test(flavor = "multi_thread")] async fn discovery_defaults_exclude_likely_non_games_and_keep_manual_choices() { let api = FakeApi::new(); @@ -3067,3 +3195,362 @@ async fn backup_usage_counts_versions_and_bytes_per_game_largest_first() { "largest first, removed games keep their last known title" ); } + +#[cfg(target_os = "linux")] +#[tokio::test(flavor = "multi_thread")] +async fn plugin_custom_launch_dispatch_is_supervised_and_can_be_stopped() { + use crate::plugin_host::library::{CustomLaunchDispatch, LibraryHost}; + use gamenode_core::drm_free::{CustomLaunchCommand, LaunchEnvironmentDelta}; + if std::env::var_os("GAMENODE_TEST_HELPER_BINARY").is_none() { + return; + } + let mut h = harness(FakeApi::new(), FakeCreds::with(None)); + let installation_host = Arc::new(gamenode_platform::installations::LinuxInstallations); + let registration = installation_host.inspect("/bin/sh").unwrap(); + Arc::get_mut(&mut h.engine.shared) + .unwrap() + .ports + .installations = Some(installation_host); + let host = super::super::PluginLibraryHost { + shared: Arc::downgrade(&h.engine.shared), + }; + host.launch_custom_for_entry( + CustomLaunchDispatch::Executable(CustomLaunchCommand { + executable: registration.executable, + file_identity: registration.file_identity, + arguments: vec!["-c".into(), "sleep 30 & wait".into()], + working_directory: "/".into(), + environment: LaunchEnvironmentDelta::default(), + }), + "steam:620".into(), + ) + .await + .unwrap(); + let ids = h + .engine + .shared + .custom_launch_supervisor + .as_ref() + .unwrap() + .active_ids() + .unwrap(); + assert_eq!(ids.len(), 1); + assert_eq!( + h.engine + .supervised_custom_launch_ids_for_entry("steam:620".into()) + .await + .unwrap(), + ids + ); + assert!( + h.engine + .supervised_custom_launch_ids_for_entry("steam:other".into()) + .await + .unwrap() + .is_empty() + ); + h.engine + .stop_supervised_custom_launch(ids[0]) + .await + .unwrap(); + assert!( + h.engine + .shared + .custom_launch_supervisor + .as_ref() + .unwrap() + .active_ids() + .unwrap() + .is_empty() + ); +} + +#[cfg(target_os = "linux")] +#[tokio::test(flavor = "multi_thread")] +async fn supervised_custom_launch_runtime_serializes_with_exclusive_resource_lease() { + use crate::plugin_host::grants::PluginIdentity; + use crate::plugin_host::library::{CustomLaunchDispatch, LibraryHost}; + use crate::plugin_host::resource_leases::{ + ResourceLeaseCoordinator, ResourceLeaseError, ResourceLeaseKey, + }; + use gamenode_core::drm_free::{CustomLaunchCommand, LaunchEnvironmentDelta}; + if std::env::var_os("GAMENODE_TEST_HELPER_BINARY").is_none() { + return; + } + let mut h = harness(FakeApi::new(), FakeCreds::with(None)); + let installation_host = Arc::new(gamenode_platform::installations::LinuxInstallations); + let registration = installation_host.inspect("/bin/sh").unwrap(); + Arc::get_mut(&mut h.engine.shared) + .unwrap() + .ports + .installations = Some(installation_host); + let key = ResourceLeaseKey::derive( + &PluginIdentity { + plugin_id: "fixture".into(), + publisher_fingerprint: "fixture".into(), + profile_id: "fixture".into(), + }, + 1, + "save", + 1, + b"host-approved-backing", + ) + .unwrap(); + let command = CustomLaunchCommand { + executable: registration.executable, + file_identity: registration.file_identity, + arguments: vec!["-c".into(), "sleep 30 & wait".into()], + working_directory: "/".into(), + environment: LaunchEnvironmentDelta::default(), + }; + let dispatch = CustomLaunchDispatch::Runtime { + command, + runtime_id: "runtime".into(), + runtime_version: "1".into(), + runtime_revision: 1, + content_id: "game".into(), + binding_revision: Some(1), + lease_keys: vec![key], + }; + let host = super::super::PluginLibraryHost { + shared: Arc::downgrade(&h.engine.shared), + }; + let coordinator = h.engine.shared_resource_leases(); + let exclusive = coordinator.acquire_exclusive(&[key]).unwrap(); + assert_eq!( + host.launch_custom_for_entry(dispatch.clone(), "steam:620".into()) + .await + .unwrap_err() + .code(), + tonic::Code::FailedPrecondition + ); + assert!( + h.engine + .supervised_custom_launch_ids() + .await + .unwrap() + .is_empty() + ); + drop(exclusive); + host.launch_custom_for_entry(dispatch, "steam:620".into()) + .await + .unwrap(); + let ids = h + .engine + .supervised_custom_launch_ids_for_entry("steam:620".into()) + .await + .unwrap(); + assert_eq!(ids.len(), 1); + let id = ids[0]; + assert!(matches!( + coordinator.acquire_exclusive(&[key]), + Err(ResourceLeaseError::Busy) + )); + h.engine.stop_supervised_custom_launch(id).await.unwrap(); + assert!(coordinator.acquire_exclusive(&[key]).is_ok()); +} + +#[cfg(target_os = "linux")] +fn selected_launch_authority_fixture() -> ( + tempfile::TempDir, + Arc, + crate::plugin_host::profile::PluginStateLayout, + crate::plugin_host::grants::PluginIdentity, + crate::plugin_host::library::UserLaunchAuthority, +) { + use crate::plugin_host::grants::{ + GrantScope, PermissionDecision, PermissionRequest, PluginIdentity, + }; + use crate::plugin_host::library::UserLaunchAuthority; + use gamenode_plugin_protocol::capability as cap; + let dir = tempfile::tempdir().unwrap(); + let profiles = Arc::new(crate::plugin_host::profile::PluginProfiles::default()); + let layout = crate::plugin_host::profile::PluginStateLayout::new(dir.path()); + profiles.set_state_layout(layout.clone()); + profiles.update(Some("account"), true); + let profile = profiles.require().unwrap(); + let identity = PluginIdentity { + plugin_id: "org.example.runtime".into(), + publisher_fingerprint: "publisher".into(), + profile_id: profile.profile_id().into(), + }; + let scope = GrantScope::Declared { + value: "selected-game".into(), + }; + let request = PermissionRequest { + permission_id: cap::GAME_CUSTOM_LAUNCH.into(), + required: false, + allowed_scopes: [scope.clone()].into(), + }; + let decision = PermissionDecision { + permission_id: cap::GAME_CUSTOM_LAUNCH.into(), + scope, + granted: true, + }; + layout + .open_grants(&profile) + .unwrap() + .replace_grants(identity.clone(), &[request], &[decision]) + .unwrap(); + layout + .open_activation(&profile) + .unwrap() + .set_enabled(&identity.plugin_id, true) + .unwrap(); + let (revision, _) = profiles + .granted_permissions(&identity.plugin_id, &identity.publisher_fingerprint) + .unwrap(); + let authority = UserLaunchAuthority { + plugin_id: identity.plugin_id.clone(), + publisher_fingerprint: identity.publisher_fingerprint.clone(), + profile_id: identity.profile_id.clone(), + profile_epoch: profile.epoch(), + grant_revision: Some(revision), + requires_files: false, + }; + (dir, profiles, layout, identity, authority) +} + +#[cfg(target_os = "linux")] +#[tokio::test(flavor = "multi_thread")] +async fn selected_custom_launch_revocation_blocks_new_launch_without_stopping_existing_tree() { + use crate::plugin_host::grants::{GrantScope, PermissionRequest}; + use crate::plugin_host::library::{CustomLaunchDispatch, LibraryHost}; + use gamenode_core::drm_free::CustomLaunchCommand; + use gamenode_plugin_protocol::capability as cap; + if std::env::var_os("GAMENODE_TEST_HELPER_BINARY").is_none() { + return; + } + let (_dir, profiles, layout, identity, authority) = selected_launch_authority_fixture(); + let mut h = harness(FakeApi::new(), FakeCreds::with(None)); + let installation_host = Arc::new(gamenode_platform::installations::LinuxInstallations); + let registration = installation_host.inspect("/bin/sh").unwrap(); + Arc::get_mut(&mut h.engine.shared) + .unwrap() + .ports + .installations = Some(installation_host); + *h.engine.shared.plugin_profiles.lock().unwrap() = Some(profiles.clone()); + let host = super::super::PluginLibraryHost { + shared: Arc::downgrade(&h.engine.shared), + }; + let dispatch = CustomLaunchDispatch::Executable(CustomLaunchCommand { + executable: registration.executable, + file_identity: registration.file_identity, + arguments: vec!["-c".into(), "sleep 30 & wait".into()], + working_directory: "/".into(), + environment: Default::default(), + }); + host.launch_custom_for_entry_authorized( + dispatch.clone(), + "steam:620".into(), + authority.clone(), + ) + .await + .unwrap(); + let ids = h + .engine + .supervised_custom_launch_ids_for_entry("steam:620".into()) + .await + .unwrap(); + assert_eq!(ids.len(), 1); + let profile = profiles.require().unwrap(); + let scope = GrantScope::Declared { + value: "selected-game".into(), + }; + let request = PermissionRequest { + permission_id: cap::GAME_CUSTOM_LAUNCH.into(), + required: false, + allowed_scopes: [scope].into(), + }; + { + let _transition = profiles.lock_transition(); + layout + .open_grants(&profile) + .unwrap() + .replace_grants(identity, &[request], &[]) + .unwrap(); + } + let mut session_authority = authority.clone(); + session_authority.grant_revision = None; + assert_eq!( + host.launch_custom_for_entry_authorized( + dispatch.clone(), + "steam:620".into(), + session_authority + ) + .await + .unwrap_err() + .code(), + tonic::Code::PermissionDenied + ); + assert_eq!( + host.launch_custom_for_entry_authorized(dispatch, "steam:620".into(), authority) + .await + .unwrap_err() + .code(), + tonic::Code::PermissionDenied + ); + assert_eq!( + h.engine + .supervised_custom_launch_ids_for_entry("steam:620".into()) + .await + .unwrap(), + ids + ); + h.engine + .stop_supervised_custom_launch(ids[0]) + .await + .unwrap(); +} + +#[cfg(target_os = "linux")] +#[tokio::test(flavor = "multi_thread")] +async fn selected_custom_launch_rechecks_profile_after_waiting_for_transition() { + use gamenode_core::drm_free::CustomLaunchCommand; + if std::env::var_os("GAMENODE_TEST_HELPER_BINARY").is_none() { + return; + } + let (_dir, profiles, _layout, _identity, authority) = selected_launch_authority_fixture(); + let mut h = harness(FakeApi::new(), FakeCreds::with(None)); + let installation_host = Arc::new(gamenode_platform::installations::LinuxInstallations); + let registration = installation_host.inspect("/bin/sh").unwrap(); + Arc::get_mut(&mut h.engine.shared) + .unwrap() + .ports + .installations = Some(installation_host); + *h.engine.shared.plugin_profiles.lock().unwrap() = Some(profiles.clone()); + let command = CustomLaunchCommand { + executable: registration.executable, + file_identity: registration.file_identity, + arguments: vec!["-c".into(), "sleep 30".into()], + working_directory: "/".into(), + environment: Default::default(), + }; + let transition = profiles.lock_transition(); + let engine = h.engine.clone(); + let pending = tokio::spawn(async move { + engine + .start_supervised_custom_launch( + command, + vec![], + Some("steam:620".into()), + Some(authority), + ) + .await + }); + tokio::time::sleep(Duration::from_millis(50)).await; + assert!(!pending.is_finished()); + transition.update(Some("another-account"), true); + drop(transition); + assert_eq!( + pending.await.unwrap().unwrap_err().code(), + tonic::Code::PermissionDenied + ); + assert!( + h.engine + .supervised_custom_launch_ids() + .await + .unwrap() + .is_empty() + ); +} diff --git a/crates/app/src/engine/tests/library.rs b/crates/app/src/engine/tests/library.rs index 696e55b48..e040509a2 100644 --- a/crates/app/src/engine/tests/library.rs +++ b/crates/app/src/engine/tests/library.rs @@ -3,7 +3,7 @@ //! Every adapter is a double with a switchable delay, so the tests can show that slow scans, //! requests and storage never hold up the caller. -use std::collections::BTreeMap; +use std::collections::{BTreeMap, HashMap}; use std::sync::Arc; use std::sync::Mutex; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; @@ -143,6 +143,12 @@ pub(super) struct FakeLibrary { pub(super) cleared: Mutex>, pub(super) favorites: Mutex>, pub(super) store_accounts: Mutex>, + pub(super) installations: Mutex>, + pub(super) installations_fail: AtomicBool, + pub(super) chosen: Mutex>, + pub(super) launch_selection: Mutex>, + pub(super) runtime_bindings: + Mutex>>, } impl FakeLibrary { @@ -152,6 +158,18 @@ impl FakeLibrary { } impl LibraryStore for FakeLibrary { + fn launch_recipe_selection( + &self, + entry_key: &str, + ) -> Result, StorageError> { + Ok(self + .launch_selection + .lock() + .unwrap() + .clone() + .filter(|selection| selection.entry_key == entry_key)) + } + fn load_cache(&self, account_id: Option<&str>) -> Result { self.pause(); self.loaded_for @@ -160,7 +178,13 @@ impl LibraryStore for FakeLibrary { .push(account_id.map(str::to_owned)); Ok(self.cache.lock().unwrap().clone()) } - fn save_scan(&self, provider: &str, records: &[Record], _now: i64) -> Result<(), StorageError> { + fn save_scan( + &self, + provider: &str, + records: &[Record], + _targets: &BTreeMap, + _now: i64, + ) -> Result<(), StorageError> { self.pause(); self.scans .lock() @@ -205,7 +229,11 @@ impl LibraryStore for FakeLibrary { self.matches.lock().unwrap().extend_from_slice(matches); Ok(()) } - fn save_chosen_match(&self, _account: &str, _choice: &ChosenMatch) -> Result<(), StorageError> { + fn save_chosen_match(&self, account: &str, choice: &ChosenMatch) -> Result<(), StorageError> { + self.chosen + .lock() + .unwrap() + .push((account.to_owned(), choice.clone())); Ok(()) } fn delete_chosen_match(&self, _account: &str, _entry_key: &str) -> Result<(), StorageError> { @@ -356,6 +384,95 @@ impl LibraryStore for FakeLibrary { self.cache.lock().unwrap().excluded = excluded.to_vec(); Ok(()) } + fn installation_ids( + &self, + entry_keys: &[String], + ) -> Result, StorageError> { + self.pause(); + if self.installations_fail.load(Ordering::SeqCst) { + return Err(StorageError::Failed("installation ids unavailable".into())); + } + let mut ids = self.installations.lock().unwrap(); + Ok(entry_keys + .iter() + .map(|key| { + let next = format!("{:032x}", ids.len() as u128 + 0xa5a5_0000); + let id = ids.entry(key.clone()).or_insert(next).clone(); + (key.clone(), id) + }) + .collect()) + } + fn save_display_name( + &self, + entry_key: &str, + expected_revision: u64, + display_name: Option<&str>, + ) -> Result { + use gamenode_core::library::{DisplayOverride, DisplayWrite}; + self.pause(); + let mut cache = self.cache.lock().unwrap(); + let current = cache + .display_overrides + .iter() + .find(|over| over.entry_key == entry_key) + .cloned(); + let revision = current.as_ref().map_or(0, |over| over.revision); + if revision != expected_revision { + return Ok(DisplayWrite::Conflict { current: revision }); + } + if current + .as_ref() + .and_then(|over| over.display_name.as_deref()) + == display_name + { + return Ok(DisplayWrite::Unchanged { revision }); + } + cache + .display_overrides + .retain(|over| over.entry_key != entry_key); + cache.display_overrides.push(DisplayOverride { + entry_key: entry_key.to_owned(), + display_name: display_name.map(str::to_owned), + revision: revision + 1, + }); + Ok(DisplayWrite::Applied { + revision: revision + 1, + }) + } + fn save_artwork( + &self, + entry_key: &str, + expected_revision: u64, + file: Option<&str>, + ) -> Result { + use gamenode_core::library::{ArtworkOverride, ArtworkWrite}; + self.pause(); + let mut cache = self.cache.lock().unwrap(); + let current = cache + .artwork_overrides + .iter() + .find(|over| over.entry_key == entry_key) + .cloned(); + let revision = current.as_ref().map_or(0, |over| over.revision); + if revision != expected_revision { + return Ok(ArtworkWrite::Conflict { current: revision }); + } + if current.as_ref().and_then(|over| over.file.as_deref()) == file { + return Ok(ArtworkWrite::Unchanged { revision }); + } + cache + .artwork_overrides + .retain(|over| over.entry_key != entry_key); + cache.artwork_overrides.push(ArtworkOverride { + entry_key: entry_key.to_owned(), + file: file.map(str::to_owned), + revision: revision + 1, + }); + Ok(ArtworkWrite::Applied { + revision: revision + 1, + replaced: current.and_then(|over| over.file), + }) + } fn load_last_account(&self) -> Result, StorageError> { Ok(self.account.lock().unwrap().clone()) } @@ -369,6 +486,20 @@ impl LibraryStore for FakeLibrary { self.account.lock().unwrap().take(); Ok(()) } + fn runtime_content_bindings( + &self, + owner_key: &str, + game_id: u64, + installation_id: &str, + ) -> Result, StorageError> { + Ok(self + .runtime_bindings + .lock() + .unwrap() + .get(&(owner_key.to_owned(), game_id, installation_id.to_owned())) + .cloned() + .unwrap_or_default()) + } } /// Waits for something that is not part of the snapshot (a write that reached an adapter). @@ -401,6 +532,7 @@ fn cached_portal_2() -> StoredEntry { name: Some("Portal 2".to_owned()), install_dir: "Portal 2".to_owned(), fields: Default::default(), + target: None, installed: true, owned: false, shared: false, @@ -648,6 +780,41 @@ async fn play_and_install_open_the_providers_links_without_blocking() { ); } +#[tokio::test(flavor = "multi_thread")] +async fn selected_recipe_never_falls_back_to_the_detected_provider_link() { + let mut h = harness(FakeApi::new(), FakeCreds::with(None)); + h.signed_out().await; + h.sign_in("token").await; + h.until("listed", |s| view(s).is_some_and(|v| v.rows.len() == 1)) + .await; + *h.store.launch_selection.lock().unwrap() = + Some(gamenode_core::library::LaunchRecipeSelection { + entry_key: "steam:620".into(), + owner_key: "plugin-owner".into(), + plugin_id: "org.example.launcher".into(), + publisher_fingerprint: "ab".repeat(32), + recipe_id: "selected-recipe".into(), + recipe_revision: 1, + base_target_revision: 1, + approved_plan_fingerprint: String::new(), + }); + + h.engine + .open_entry("steam:620".to_owned(), LaunchKind::Play); + let snapshot = h + .until("selection needs attention", |snapshot| { + snapshot.launch.as_ref().is_some_and(|launch| { + launch.state == LaunchState::Failed(LaunchError::RecipeNeedsAttention) + }) + }) + .await; + assert!(h.uri.opened.lock().unwrap().is_empty()); + assert_eq!( + snapshot.launch.unwrap().state, + LaunchState::Failed(LaunchError::RecipeNeedsAttention) + ); +} + #[tokio::test(flavor = "multi_thread")] async fn a_missing_store_client_is_reported_until_dismissed() { let mut h = harness(FakeApi::new(), FakeCreds::with(None)); @@ -1210,6 +1377,7 @@ async fn a_cover_burst_publishes_far_fewer_snapshots_and_keeps_the_last_cover() name: Some(format!("Game {i}")), install_dir: format!("Game {i}"), fields: Default::default(), + target: None, installed: false, owned: true, shared: false, @@ -1863,6 +2031,958 @@ async fn batch_status_and_collection_changes_reach_the_api_and_refresh_the_rows( assert!(entry.collection_ids.iter().any(|id| id == "coop")); } +// Tests retained from the plugin branch during main integration. + +/// What a whole-library plugin would list right now: `(installation id, game id, name)`. +fn feed_entries( + feed: &crate::plugin_host::library::LibraryFeed, +) -> Vec<(String, Option, String)> { + use crate::plugin_host::library::Scope; + let scope = Scope { + own_provider: "steam".to_owned(), + read_all: true, + provider_filter: None, + }; + feed.page(&scope, None, None, 200) + .1 + .into_iter() + .map(|entry| (entry.installation_id, entry.game_id, entry.name)) + .collect() +} + +fn open_guard() -> crate::plugin_host::library::CommitGuard { + Box::new(|| Ok(())) +} + +fn denying_guard() -> crate::plugin_host::library::CommitGuard { + Box::new(|| Err(tonic::Status::permission_denied("revoked"))) +} + +fn projected( + feed: &crate::plugin_host::library::LibraryFeed, + id: &str, +) -> crate::plugin_host::library::Projected { + use crate::plugin_host::library::Scope; + let scope = Scope { + own_provider: "steam".to_owned(), + read_all: false, + provider_filter: None, + }; + feed.get(&scope, id).1.expect("the entry is projected") +} + +fn row_title(snapshot: &Snapshot) -> Option<&str> { + view(snapshot) + .and_then(|v| v.rows.first()) + .map(|row| row.title.as_str()) +} + +fn search_page(games: &[(u64, &str)]) -> gamenode_core::game_api::SearchPage { + gamenode_core::game_api::SearchPage { + games: games + .iter() + .map(|(id, name)| GameSummary { + id: *id, + name: (*name).to_owned(), + release_year: Some(2013), + cover_url: None, + platforms: vec![], + }) + .collect(), + complete: Some(true), + } +} + +fn row_cover(snapshot: &Snapshot) -> Option<&str> { + view(snapshot) + .and_then(|v| v.rows.first()) + .and_then(|row| row.cover_file.as_deref()) +} + +/// A prepared cover of one flat colour and a size, as the service would hand over. +fn cover_of(shade: u8, width: u32, height: u32) -> gamenode_platform::plugin_artwork::Prepared { + let mut bytes = Vec::new(); + image::DynamicImage::ImageRgb8(image::RgbImage::from_pixel( + width, + height, + image::Rgb([shade, 60, 90]), + )) + .write_with_encoder(image::codecs::png::PngEncoder::new(&mut bytes)) + .unwrap(); + gamenode_platform::plugin_artwork::prepare(&bytes, "image/png").unwrap() +} + +fn files_in(dir: &std::path::Path) -> Vec { + let mut names: Vec = std::fs::read_dir(dir) + .unwrap() + .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned()) + .collect(); + names.sort(); + names +} + +// Plugin-specific engine regressions retained across the library redesign. + +#[tokio::test(flavor = "multi_thread")] +async fn plugin_profiles_follow_the_cached_then_verified_account_and_end_at_sign_out() { + use crate::plugin_host::profile::{PluginProfiles, profile_id_for_account}; + let api = FakeApi::new(); + *api.delay.lock().unwrap() = Duration::from_millis(300); + let mut h = harness(api, FakeCreds::with(Some("stored"))); + seed_cache(&h, Some(account("u2", "Bo"))); + let profiles = std::sync::Arc::new(PluginProfiles::default()); + h.engine.set_plugin_profiles(profiles.clone()); + assert!(profiles.current().is_none(), "no profile before a session"); + h.engine.start(); + + // An unverified restore runs on the cached account. + h.until("cached library while verifying", |s| { + s.auth == AuthView::Verifying && view(s).is_some() + }) + .await; + let cached = profiles.current().expect("cached account profile"); + assert_eq!(cached.profile_id(), profile_id_for_account("u2")); + assert!(!cached.verified()); + + // The session belongs to a different account: the cached profile is fenced. + h.until("verified", |s| matches!(s.auth, AuthView::SignedIn { .. })) + .await; + let verified = profiles.current().expect("verified account profile"); + assert_eq!(verified.profile_id(), profile_id_for_account("u1")); + assert!(verified.verified()); + assert!(verified.epoch() > cached.epoch()); + assert!(!profiles.is_current(cached.epoch())); + + h.engine.dispatch(Input::SignOut); + h.until("signed out", |s| s.auth == AuthView::SignedOut) + .await; + assert!(profiles.current().is_none()); + assert!(!profiles.is_current(verified.epoch())); +} + +#[tokio::test(flavor = "multi_thread")] +async fn verifying_the_cached_account_keeps_its_plugin_profile() { + use crate::plugin_host::profile::PluginProfiles; + let api = FakeApi::new(); + *api.delay.lock().unwrap() = Duration::from_millis(300); + let mut h = harness(api, FakeCreds::with(Some("stored"))); + seed_cache(&h, Some(account("u1", "Ana"))); + let profiles = std::sync::Arc::new(PluginProfiles::default()); + h.engine.set_plugin_profiles(profiles.clone()); + h.engine.start(); + + h.until("cached library while verifying", |s| { + s.auth == AuthView::Verifying && view(s).is_some() + }) + .await; + let cached = profiles.current().expect("cached account profile"); + h.until("verified", |s| matches!(s.auth, AuthView::SignedIn { .. })) + .await; + let verified = profiles.current().expect("verified account profile"); + assert!(verified.verified()); + assert_eq!(verified.epoch(), cached.epoch()); + assert_eq!(verified.profile_id(), cached.profile_id()); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_rejected_restore_issues_no_plugin_profile() { + use crate::plugin_host::profile::PluginProfiles; + let api = FakeApi::new(); + *api.session.lock().unwrap() = Some(Err(SessionError::Rejected)); + let mut h = harness(api, FakeCreds::with(Some("stored"))); + seed_cache(&h, Some(account("u1", "Ana"))); + let profiles = std::sync::Arc::new(PluginProfiles::default()); + h.engine.set_plugin_profiles(profiles.clone()); + h.engine.start(); + + h.until("signed out", |s| s.auth == AuthView::SignedOut) + .await; + assert!(profiles.current().is_none()); +} + +#[tokio::test(flavor = "multi_thread")] +async fn extension_readiness_resolves_only_current_account_library_choices() { + use crate::plugin_host::{library::LibraryFeed, profile::PluginProfiles}; + let api = FakeApi::new(); + *api.lookup_result.lock().unwrap() = Some(Ok(vec![portal_2_match()])); + let mut h = harness(api, FakeCreds::with(None)); + let profiles = Arc::new(PluginProfiles::default()); + let feed = LibraryFeed::new(); + h.engine.set_plugin_profiles(profiles.clone()); + h.engine.set_library_feed(feed.clone()); + h.signed_out().await; + assert!(h.engine.extension_readiness_choices().is_empty()); + h.sign_in("token").await; + eventually("matched entry is selectable for readiness", || { + h.engine.extension_readiness_choices().len() == 1 + }) + .await; + + let choices = serde_json::to_value(h.engine.extension_readiness_choices()).unwrap(); + let choice = &choices[0]; + assert_eq!(choice["name"], "Portal 2"); + let selection = choice["selection"].clone(); + let resolve = |selection| { + h.engine + .resolve_extension_readiness(serde_json::from_value(selection).unwrap()) + }; + let target = resolve(selection.clone()).unwrap(); + assert_eq!(target.context.game_id, "7"); + assert_eq!( + target.context.profile_id, + profiles.require().unwrap().profile_id() + ); + assert!(target.is_current()); + + let mut foreign = selection.clone(); + foreign["installationId"] = "foreign-installation".into(); + assert!(resolve(foreign).is_err()); + + let (mut source, _) = feed.projected_entry("steam:620").unwrap(); + source.detected_target = Some((99, true, true)); + feed.sync(vec![source]); + assert!(!target.is_current()); + assert!(resolve(selection).is_err()); + + let choices = serde_json::to_value(h.engine.extension_readiness_choices()).unwrap(); + let selection = choices[0]["selection"].clone(); + profiles.update(Some("another-account"), true); + profiles.update(Some("u1"), true); + assert!(resolve(selection).is_err()); +} + +#[tokio::test(flavor = "multi_thread")] +async fn plugins_see_entries_with_a_durable_id_and_a_game_id_that_follows_the_match() { + use crate::plugin_host::library::LibraryFeed; + let api = FakeApi::new(); + *api.lookup_result.lock().unwrap() = Some(Ok(vec![portal_2_match()])); + let mut h = harness(api, FakeCreds::with(None)); + let feed = LibraryFeed::new(); + h.engine.set_library_feed(feed.clone()); + h.signed_out().await; + assert!(feed_entries(&feed).is_empty()); + h.sign_in("token").await; + + // The scan lists the entry, then the lookup matches it to game 7. + eventually("the entry is matched in the plugin projection", || { + feed_entries(&feed) + .first() + .is_some_and(|(_, game, _)| *game == Some(7)) + }) + .await; + let entries = feed_entries(&feed); + assert_eq!(entries.len(), 1); + let (id, game, name) = entries[0].clone(); + assert_eq!((game, name.as_str()), (Some(7), "Portal 2")); + // The id is the one the library store holds for the entry, and it is not derived from it. + assert_eq!( + h.store.installations.lock().unwrap().get("steam:620"), + Some(&id) + ); + assert!(!id.contains("620") && !id.contains("steam")); + + // A rescan and a forced re-sync keep the installation id. + h.engine + .library_input(gamenode_core::library::Input::ScanRequested); + h.until("rescanned", |s| view(s).is_some_and(|v| !v.scanning)) + .await; + assert_eq!(feed_entries(&feed)[0].0, id); + + // Signing out removes the entries from the plugin projection. + h.engine.dispatch(Input::SignOut); + h.until("signed out", |s| s.auth == AuthView::SignedOut) + .await; + eventually("the projection is emptied", || { + feed_entries(&feed).is_empty() + }) + .await; +} + +#[tokio::test(flavor = "multi_thread")] +async fn an_entry_stays_hidden_from_plugins_while_its_installation_id_cannot_be_stored() { + use crate::plugin_host::library::LibraryFeed; + let mut h = harness(FakeApi::new(), FakeCreds::with(None)); + h.store.installations_fail.store(true, Ordering::SeqCst); + let feed = LibraryFeed::new(); + h.engine.set_library_feed(feed.clone()); + h.signed_out().await; + h.sign_in("token").await; + h.until("listed in the library", |s| { + view(s).is_some_and(|v| v.rows.len() == 1 && !v.scanning) + }) + .await; + assert!(feed_entries(&feed).is_empty(), "no id, no projection"); + assert!(h.store.installations.lock().unwrap().is_empty()); +} + +/// A signed-in harness whose Portal 2 entry is matched to game 7 and projected to plugins, with +/// the plugin write side connected. +async fn plugin_library() -> ( + Harness, + std::sync::Arc, + std::sync::Arc, + String, +) { + use crate::plugin_host::library::LibraryFeed; + let api = FakeApi::new(); + *api.lookup_result.lock().unwrap() = Some(Ok(vec![portal_2_match()])); + let mut h = harness(api, FakeCreds::with(None)); + let feed = LibraryFeed::new(); + h.engine.set_library_feed(feed.clone()); + h.signed_out().await; + h.sign_in("token").await; + eventually("the entry is matched in the plugin projection", || { + feed_entries(&feed) + .first() + .is_some_and(|(_, game, _)| *game == Some(7)) + }) + .await; + let id = feed_entries(&feed)[0].0.clone(); + let host = feed.host().expect("the engine connected its host"); + (h, feed, host, id) +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_plugin_display_name_is_stored_shown_and_guarded_by_its_revision() { + use gamenode_core::library::DisplayWrite; + let (mut h, feed, host, id) = plugin_library().await; + h.until("the matched title", |s| row_title(s) == Some("Portal 2")) + .await; + assert_eq!(projected(&feed, &id).metadata_revision, 0); + + let written = host + .set_display_name( + "steam:620".into(), + 0, + Some("Portal Two".into()), + open_guard(), + ) + .await + .unwrap(); + assert_eq!(written, DisplayWrite::Applied { revision: 1 }); + // The write reached the database double, the library shows it, plugins read it back, and the + // detected facts are unchanged. + let stored = h.store.cache.lock().unwrap().display_overrides.clone(); + assert_eq!( + ( + stored[0].entry_key.as_str(), + stored[0].display_name.as_deref(), + stored[0].revision + ), + ("steam:620", Some("Portal Two"), 1) + ); + h.until("the override is the title", |s| { + row_title(s) == Some("Portal Two") + }) + .await; + let entry = projected(&feed, &id); + assert_eq!(entry.display_name.as_deref(), Some("Portal Two")); + assert_eq!(entry.metadata_revision, 1); + assert_eq!(entry.name, "Portal 2"); + assert_eq!(entry.installation_id, id); + + // An obsolete revision overwrites nothing. + let written = host + .set_display_name("steam:620".into(), 0, Some("Stale".into()), open_guard()) + .await + .unwrap(); + assert_eq!(written, DisplayWrite::Conflict { current: 1 }); + assert_eq!( + projected(&feed, &id).display_name.as_deref(), + Some("Portal Two") + ); + assert_eq!(h.store.cache.lock().unwrap().display_overrides.len(), 1); + + // The same value again changes nothing. + let written = host + .set_display_name( + "steam:620".into(), + 1, + Some("Portal Two".into()), + open_guard(), + ) + .await + .unwrap(); + assert_eq!(written, DisplayWrite::Unchanged { revision: 1 }); + assert_eq!(projected(&feed, &id).metadata_revision, 1); + + // Clearing restores the matched title; the revision keeps counting. + let written = host + .set_display_name("steam:620".into(), 1, None, open_guard()) + .await + .unwrap(); + assert_eq!(written, DisplayWrite::Applied { revision: 2 }); + h.until("the title is restored", |s| { + row_title(s) == Some("Portal 2") + }) + .await; + let entry = projected(&feed, &id); + assert_eq!((entry.display_name, entry.metadata_revision), (None, 2)); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_revoked_guard_stops_a_display_name_before_it_is_stored() { + let (mut h, feed, host, id) = plugin_library().await; + h.until("the matched title", |s| row_title(s) == Some("Portal 2")) + .await; + let before = projected(&feed, &id); + + let error = host + .set_display_name("steam:620".into(), 0, Some("Nope".into()), denying_guard()) + .await + .unwrap_err(); + assert_eq!(error.code(), tonic::Code::PermissionDenied); + assert!(h.store.cache.lock().unwrap().display_overrides.is_empty()); + assert_eq!(projected(&feed, &id), before); + assert_eq!(row_title(&h.engine.snapshot()), Some("Portal 2")); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_stored_display_name_and_its_revision_survive_a_restart() { + use crate::plugin_host::library::LibraryFeed; + use gamenode_core::library::{DisplayOverride, DisplayWrite}; + let api = FakeApi::new(); + *api.delay.lock().unwrap() = Duration::from_millis(100); + let mut h = harness(api, FakeCreds::with(Some("stored"))); + seed_cache(&h, Some(account("u1", "Ana"))); + h.store + .cache + .lock() + .unwrap() + .display_overrides + .push(DisplayOverride { + entry_key: "steam:620".to_owned(), + display_name: Some("Portal Two".to_owned()), + revision: 3, + }); + let feed = LibraryFeed::new(); + h.engine.set_library_feed(feed.clone()); + h.engine.start(); + + h.until("the cached override is the title", |s| { + row_title(s) == Some("Portal Two") + }) + .await; + eventually("the projection carries the stored revision", || { + feed_entries(&feed).len() == 1 + }) + .await; + let id = feed_entries(&feed)[0].0.clone(); + let entry = projected(&feed, &id); + assert_eq!(entry.display_name.as_deref(), Some("Portal Two")); + assert_eq!(entry.metadata_revision, 3); + + // The next write continues from the stored revision. + let host = feed.host().unwrap(); + assert_eq!( + host.set_display_name("steam:620".into(), 2, Some("Old".into()), open_guard()) + .await + .unwrap(), + DisplayWrite::Conflict { current: 3 } + ); + assert_eq!( + host.set_display_name("steam:620".into(), 3, Some("Again".into()), open_guard()) + .await + .unwrap(), + DisplayWrite::Applied { revision: 4 } + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_plugin_favorites_only_games_its_own_entries_are_matched_to() { + use crate::plugin_host::library::FavoriteWrite; + let (mut h, _feed, host, _id) = plugin_library().await; + let ok = || Ok(()); + let is_favorite = + |s: &Snapshot| view(s).is_some_and(|v| v.rows.first().is_some_and(|r| r.is_favorite)); + assert_eq!(host.favorites("steam"), [(7, false)]); + assert!( + host.favorites("gog").is_empty(), + "another provider's view is empty" + ); + + assert_eq!( + host.set_favorite("steam", 7, true, &ok).unwrap(), + FavoriteWrite::Applied + ); + h.until("the star appears", is_favorite).await; + assert_eq!(host.favorites("steam"), [(7, true)]); + // Setting the same state again is idempotent. + assert_eq!( + host.set_favorite("steam", 7, true, &ok).unwrap(), + FavoriteWrite::AlreadyApplied + ); + // A provider with no entry matched to the game, and a game nobody matches, are the same + // answer; neither changes anything. + assert_eq!( + host.set_favorite("gog", 7, false, &ok).unwrap(), + FavoriteWrite::NoMatchedEntry + ); + assert_eq!( + host.set_favorite("steam", 8, true, &ok).unwrap(), + FavoriteWrite::NoMatchedEntry + ); + assert_eq!(host.favorites("steam"), [(7, true)]); + + // A revoked guard changes nothing. + let denied = |_: ()| tonic::Status::permission_denied("revoked"); + let error = host + .set_favorite("steam", 7, false, &|| Err(denied(()))) + .unwrap_err(); + assert_eq!(error.code(), tonic::Code::PermissionDenied); + assert_eq!(host.favorites("steam"), [(7, true)]); + assert!(is_favorite(&h.engine.snapshot())); + + assert_eq!( + host.set_favorite("steam", 7, false, &ok).unwrap(), + FavoriteWrite::Applied + ); + h.until("the star is gone", |s| !is_favorite(s)).await; + assert_eq!(host.favorites("steam"), [(7, false)]); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_plugin_catalog_search_is_bounded_offers_its_games_and_opens_no_dialog() { + let (h, _feed, host, _id) = plugin_library().await; + *h.api.search_result.lock().unwrap() = Some(Ok(search_page(&[ + (40, "Defense of the Ancients"), + (41, "Dota Underlords"), + (42, "Dota 2"), + ]))); + + let found = host.search_catalog("dota".into(), 2).await.unwrap(); + assert_eq!( + found + .iter() + .map(|g| (g.id, g.release_year)) + .collect::>(), + [(40, Some(2013)), (41, Some(2013))] + ); + assert!( + view(&h.engine.snapshot()).unwrap().match_dialog.is_none(), + "a plugin search never touches the user's match dialog" + ); + // Only the games that were returned can be assigned. + let rev = h.engine.lock().library.plan_plugin_match("steam:620", 42); + assert_eq!(rev, gamenode_core::library::PluginMatch::UnknownGame); + let rev = h.engine.lock().library.plan_plugin_match("steam:620", 41); + assert_eq!(rev, gamenode_core::library::PluginMatch::Assign); +} + +#[tokio::test(flavor = "multi_thread")] +async fn an_unavailable_catalog_is_reported_without_changing_the_library() { + let (h, _feed, host, _id) = plugin_library().await; + *h.api.search_result.lock().unwrap() = Some(Err(ApiError::Failed)); + let error = host.search_catalog("dota".into(), 20).await.unwrap_err(); + assert_eq!(error.code(), tonic::Code::Unavailable); + assert_eq!( + h.engine.lock().library.plan_plugin_match("steam:620", 40), + gamenode_core::library::PluginMatch::UnknownGame + ); + + // Without a verified session the catalog is not asked at all. + let mut h = harness(FakeApi::new(), FakeCreds::with(None)); + let feed = crate::plugin_host::library::LibraryFeed::new(); + h.engine.set_library_feed(feed.clone()); + h.signed_out().await; + let host = feed.host().unwrap(); + let error = host.search_catalog("dota".into(), 20).await.unwrap_err(); + assert_eq!(error.code(), tonic::Code::Unavailable); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_plugin_assigns_its_own_entry_through_the_library_policy() { + use crate::plugin_host::library::MatchWrite; + use gamenode_core::library::{ChoiceSource, MatchSource, MatchStatus}; + let (mut h, feed, host, id) = plugin_library().await; + let ok = || Ok(()); + *h.api.search_result.lock().unwrap() = Some(Ok(search_page(&[(40, "Dota"), (41, "Dota Two")]))); + host.search_catalog("dota".into(), 20).await.unwrap(); + let before = projected(&feed, &id); + assert_eq!(before.game_id, Some(7)); + + // The entry's revision guards the write; a game nobody offered is refused first. + assert_eq!( + host.assign_match("steam:620", 40, before.revision + 5, &ok) + .unwrap(), + MatchWrite::Conflict { + current: before.revision + } + ); + assert_eq!( + host.assign_match("steam:620", 99, before.revision, &ok) + .unwrap(), + MatchWrite::UnknownGame + ); + assert!(h.store.chosen.lock().unwrap().is_empty()); + + let MatchWrite::Applied { revision } = host + .assign_match("steam:620", 40, before.revision, &ok) + .unwrap() + else { + panic!("assigned"); + }; + assert!(revision > before.revision); + let after = projected(&feed, &id); + assert_eq!((after.game_id, after.revision), (Some(40), revision)); + h.until("the library shows the plugin's choice", |s| { + view(s).is_some_and(|v| { + v.rows.first().is_some_and(|row| { + row.status + == MatchStatus::Matched { + game_id: 40, + source: MatchSource::Chosen, + } + }) + }) + }) + .await; + // The choice and the game it names are stored, marked as the plugin's. The storage worker + // writes them after the library view updates, so wait for the write. + eventually("the choice is stored", || { + !h.store.chosen.lock().unwrap().is_empty() + }) + .await; + let chosen = h.store.chosen.lock().unwrap().clone(); + assert_eq!(chosen.len(), 1); + assert_eq!(chosen[0].1.entry_key, "steam:620"); + assert_eq!(chosen[0].1.game_id, Some(40)); + assert_eq!(chosen[0].1.source, ChoiceSource::Plugin); + eventually("the game record is stored", || { + h.store + .games + .lock() + .unwrap() + .iter() + .any(|g| g.game_id == 40) + }) + .await; + + // The same assignment again changes nothing, whatever revision is named. + assert_eq!( + host.assign_match("steam:620", 40, 0, &ok).unwrap(), + MatchWrite::AlreadyApplied { revision } + ); + assert_eq!(h.store.chosen.lock().unwrap().len(), 1); + // The plugin may replace its own choice. + assert!(matches!( + host.assign_match("steam:620", 41, revision, &ok).unwrap(), + MatchWrite::Applied { .. } + )); + assert_eq!(projected(&feed, &id).game_id, Some(41)); + + // A revoked guard changes nothing. + let error = host + .assign_match("steam:620", 40, projected(&feed, &id).revision, &|| { + Err(tonic::Status::permission_denied("revoked")) + }) + .unwrap_err(); + assert_eq!(error.code(), tonic::Code::PermissionDenied); + assert_eq!(projected(&feed, &id).game_id, Some(41)); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_plugin_never_replaces_what_the_user_chose_in_the_match_dialog() { + use crate::plugin_host::library::MatchWrite; + use gamenode_core::library::{ChoiceSource, Input, SelectMode}; + let (mut h, feed, host, id) = plugin_library().await; + let ok = || Ok(()); + *h.api.search_result.lock().unwrap() = Some(Ok(search_page(&[(40, "Dota"), (41, "Two")]))); + h.engine.library_input(Input::Select { + key: "steam:620".into(), + mode: SelectMode::Replace, + }); + h.engine.library_input(Input::OpenMatch); + h.until("the dialog has results", |s| { + view(s) + .and_then(|v| v.match_dialog.as_ref()) + .is_some_and(|d| !d.searching && !d.results.is_empty()) + }) + .await; + h.engine.library_input(Input::PickMatch { + game_id: 40, + now: 1, + }); + eventually("the pick is stored as the user's", || { + h.store + .chosen + .lock() + .unwrap() + .iter() + .any(|(_, c)| c.game_id == Some(40) && c.source == ChoiceSource::User) + }) + .await; + host.search_catalog("dota".into(), 20).await.unwrap(); + let revision = projected(&feed, &id).revision; + assert_eq!( + host.assign_match("steam:620", 41, revision, &ok).unwrap(), + MatchWrite::UserChoice + ); + assert_eq!(projected(&feed, &id).game_id, Some(40)); + // The user's own game is simply already applied. + assert_eq!( + host.assign_match("steam:620", 40, revision, &ok).unwrap(), + MatchWrite::AlreadyApplied { revision } + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_plugin_cover_is_stored_shown_read_back_replaced_and_cleared() { + use gamenode_core::library::ArtworkWrite; + use gamenode_platform::plugin_artwork::file_name; + let (mut h, feed, host, id) = plugin_library().await; + h.until("the game's own cover", |s| row_cover(s) == Some("7.jpg")) + .await; + let dir = h.covers.path().to_owned(); + assert_eq!(projected(&feed, &id).artwork_revision, 0); + let own = host + .read_artwork("steam:620".into(), 1 << 20) + .await + .unwrap(); + assert_eq!( + (own.bytes.as_slice(), own.media_type, own.revision), + (b"jpeg".as_slice(), "image/jpeg", 0) + ); + + // Set: the image lands under a name this entry owns, the library shows it, plugins see its + // revision, and the game's own cover is untouched. + let (first, second) = (cover_of(10, 300, 450), cover_of(200, 300, 450)); + let first_name = file_name("steam:620", &first); + let before = projected(&feed, &id).revision; + let written = host + .set_artwork("steam:620".into(), 0, Some(first.clone()), open_guard()) + .await + .unwrap(); + assert_eq!( + written, + ArtworkWrite::Applied { + revision: 1, + replaced: None + } + ); + assert_eq!(files_in(&dir), ["7.jpg".to_owned(), first_name.clone()]); + assert_eq!(std::fs::read(dir.join("7.jpg")).unwrap(), b"jpeg"); + assert_eq!(std::fs::read(dir.join(&first_name)).unwrap(), first.bytes); + h.until("the override is the cover", |s| { + row_cover(s) == Some(first_name.as_str()) + }) + .await; + let entry = projected(&feed, &id); + assert_eq!(entry.artwork_revision, 1); + assert!(entry.revision > before, "the entry changed"); + let read = host + .read_artwork("steam:620".into(), 1 << 20) + .await + .unwrap(); + assert_eq!( + (read.bytes.as_slice(), read.media_type, read.revision), + (first.bytes.as_slice(), "image/jpeg", 1) + ); + + // Replace: the old file is deleted once the row points at the new one. + let second_name = file_name("steam:620", &second); + let written = host + .set_artwork("steam:620".into(), 1, Some(second.clone()), open_guard()) + .await + .unwrap(); + assert_eq!( + written, + ArtworkWrite::Applied { + revision: 2, + replaced: Some(first_name.clone()) + } + ); + assert_eq!(files_in(&dir), ["7.jpg".to_owned(), second_name.clone()]); + + // A stale revision overwrites nothing and leaves no file behind. + let third = cover_of(90, 300, 450); + let written = host + .set_artwork("steam:620".into(), 1, Some(third), open_guard()) + .await + .unwrap(); + assert_eq!(written, ArtworkWrite::Conflict { current: 2 }); + assert_eq!(files_in(&dir), ["7.jpg".to_owned(), second_name.clone()]); + + // The same picture again changes nothing and keeps its file. + let written = host + .set_artwork("steam:620".into(), 2, Some(second), open_guard()) + .await + .unwrap(); + assert_eq!(written, ArtworkWrite::Unchanged { revision: 2 }); + assert_eq!(files_in(&dir), ["7.jpg".to_owned(), second_name.clone()]); + + // Clear: the game's own cover is back, the file is gone and the revision keeps counting. + let written = host + .set_artwork("steam:620".into(), 2, None, open_guard()) + .await + .unwrap(); + assert_eq!( + written, + ArtworkWrite::Applied { + revision: 3, + replaced: Some(second_name) + } + ); + assert_eq!(files_in(&dir), ["7.jpg".to_owned()]); + h.until("the game's cover is back", |s| { + row_cover(s) == Some("7.jpg") + }) + .await; + assert_eq!(projected(&feed, &id).artwork_revision, 3); + let back = host + .read_artwork("steam:620".into(), 1 << 20) + .await + .unwrap(); + assert_eq!( + (back.bytes.as_slice(), back.revision), + (b"jpeg".as_slice(), 3) + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_revoked_guard_stops_a_cover_before_any_file_is_written() { + let (mut h, feed, host, id) = plugin_library().await; + h.until("the game's own cover", |s| row_cover(s) == Some("7.jpg")) + .await; + let before = projected(&feed, &id); + let error = host + .set_artwork( + "steam:620".into(), + 0, + Some(cover_of(10, 300, 450)), + denying_guard(), + ) + .await + .unwrap_err(); + assert_eq!(error.code(), tonic::Code::PermissionDenied); + assert!(h.store.cache.lock().unwrap().artwork_overrides.is_empty()); + assert_eq!(files_in(h.covers.path()), ["7.jpg".to_owned()]); + assert_eq!(projected(&feed, &id), before); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_cover_read_is_bounded_and_never_downloads_or_leaves_the_covers_folder() { + let (mut h, _feed, host, _id) = plugin_library().await; + h.until("the game's own cover", |s| row_cover(s) == Some("7.jpg")) + .await; + let fetched = h.api.covers_fetched.lock().unwrap().len(); + // 4 bytes is exactly the cover; one less is over the caller's budget. + assert!(host.read_artwork("steam:620".into(), 4).await.is_ok()); + let error = host.read_artwork("steam:620".into(), 3).await.unwrap_err(); + assert_eq!(error.code(), tonic::Code::ResourceExhausted); + // An entry the library does not know has no cover to read. + let error = host + .read_artwork("steam:nope".into(), 1 << 20) + .await + .unwrap_err(); + assert_eq!(error.code(), tonic::Code::NotFound); + // A cover the file system no longer has is not found, and nothing is fetched to fill it. + std::fs::remove_file(h.covers.path().join("7.jpg")).unwrap(); + let error = host + .read_artwork("steam:620".into(), 1 << 20) + .await + .unwrap_err(); + assert_eq!(error.code(), tonic::Code::NotFound); + assert_eq!(h.api.covers_fetched.lock().unwrap().len(), fetched); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_stored_cover_and_its_revision_survive_a_restart() { + use crate::plugin_host::library::LibraryFeed; + use gamenode_core::library::{ArtworkOverride, ArtworkWrite}; + let api = FakeApi::new(); + *api.delay.lock().unwrap() = Duration::from_millis(100); + let mut h = harness(api, FakeCreds::with(Some("stored"))); + seed_cache(&h, Some(account("u1", "Ana"))); + h.store + .cache + .lock() + .unwrap() + .artwork_overrides + .push(ArtworkOverride { + entry_key: "steam:620".to_owned(), + file: Some("plugin-aa-bb.jpg".to_owned()), + revision: 3, + }); + let feed = LibraryFeed::new(); + h.engine.set_library_feed(feed.clone()); + h.engine.start(); + + h.until("the cached override is the cover", |s| { + row_cover(s) == Some("plugin-aa-bb.jpg") + }) + .await; + eventually("the projection carries the stored revision", || { + feed_entries(&feed).len() == 1 + }) + .await; + let id = feed_entries(&feed)[0].0.clone(); + assert_eq!(projected(&feed, &id).artwork_revision, 3); + let host = feed.host().unwrap(); + assert_eq!( + host.set_artwork("steam:620".into(), 2, None, open_guard()) + .await + .unwrap(), + ArtworkWrite::Conflict { current: 3 } + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_plugin_starts_and_installs_through_the_users_own_path() { + use tonic::Code; + let (mut h, _feed, host, _id) = plugin_library().await; + + // What a launch would start is the same number until the target changes. + let first = host.launch_fingerprint("steam:620".into()).await.unwrap(); + assert_eq!( + first, + host.launch_fingerprint("steam:620".into()).await.unwrap() + ); + assert_eq!( + host.launch_fingerprint("steam:1".into()) + .await + .unwrap_err() + .code(), + Code::NotFound + ); + + // The same links the user's Play and Install open, and the launch status is cleared the same + // way once the operating system accepted them. + host.open_entry("steam:620".into(), false).await.unwrap(); + host.open_entry("steam:620".into(), true).await.unwrap(); + assert_eq!( + *h.uri.opened.lock().unwrap(), + ["steam://rungameid/620", "steam://nav/games/details/620"] + ); + h.until("cleared once the OS accepted the link", |s| { + s.launch.is_none() + }) + .await; + + // An entry that is not in the library is not found. + assert_eq!( + host.open_entry("steam:1".into(), false) + .await + .unwrap_err() + .code(), + Code::NotFound + ); + + // A refusal by the operating system is the user's own error too, and the plugin is told. + *h.uri.fail.lock().unwrap() = Some(UriError::NoHandler); + assert_eq!( + host.open_entry("steam:620".into(), false) + .await + .unwrap_err() + .code(), + Code::FailedPrecondition + ); + assert_eq!( + h.engine.snapshot().launch.unwrap().state, + LaunchState::Failed(LaunchError::NoHandler) + ); +} + #[tokio::test(flavor = "multi_thread")] async fn creating_a_collection_from_the_dialog_relists_and_selects_it() { use gamenode_core::library::{CollectionsView, Input as LibInput, SelectMode}; @@ -1932,6 +3052,41 @@ async fn creating_a_collection_from_the_dialog_relists_and_selects_it() { assert!(h.api.created.lock().unwrap().is_empty()); } +#[tokio::test(flavor = "multi_thread")] +async fn uninstalling_a_plugin_removes_its_provider_by_plugin_id_without_a_restart() { + let h = harness(FakeApi::new(), FakeCreds::with(None)); + assert!( + h.engine.lock().library.provider("steam").is_some(), + "the bundled provider is loaded before the uninstall" + ); + + // The command passes the installed plugin id; the provider id is `steam`. The store must + // leave the running library even though the two ids differ. + h.engine + .remove_library_provider("org.gamenode.plugin.steam-discovery"); + { + let state = h.engine.lock(); + assert!( + state.library.provider("steam").is_none(), + "the uninstalled store leaves the running library" + ); + assert!( + state.library.provider("packagekit").is_some(), + "the other stores stay loaded" + ); + } + + // A direct provider id still works, and an unknown id changes nothing. + h.engine.remove_library_provider("packagekit"); + h.engine.remove_library_provider("dev.example.unknown"); + let state = h.engine.lock(); + assert!(state.library.provider("packagekit").is_none()); + assert!( + state.library.providers().is_empty(), + "the unknown id added nothing" + ); +} + #[tokio::test(flavor = "multi_thread")] async fn the_shared_games_preference_updates_the_library_without_a_sync() { let mut h = harness(FakeApi::new(), FakeCreds::with(None)); @@ -1941,6 +3096,7 @@ async fn the_shared_games_preference_updates_the_library_without_a_sync() { provider: "steam".to_owned(), store_id: "900".to_owned(), name: Some("Family Game".to_owned()), + target: None, install_dir: "Family Game".to_owned(), fields: Default::default(), installed: false, diff --git a/crates/app/src/engine/tests/pc_ports.rs b/crates/app/src/engine/tests/pc_ports.rs index dbca7114c..7934b7279 100644 --- a/crates/app/src/engine/tests/pc_ports.rs +++ b/crates/app/src/engine/tests/pc_ports.rs @@ -762,6 +762,7 @@ async fn an_unverified_checksum_needs_the_request_flag() { wait_for_view(&rx, |view| view.catalog.state == PortCatalogState::Ready); let parent = tempfile::tempdir().unwrap(); let mut request = PortInstallRequest { + plugin_request_id: None, catalog_id: "qcat_lantern".into(), parent_folder: parent.path().to_string_lossy().into_owned(), supplied: Vec::new(), @@ -824,6 +825,7 @@ async fn a_package_install_without_its_required_update_is_blocked() { let error = service .prepare_install(&PortInstallRequest { + plugin_request_id: None, catalog_id: "qcat_lantern".into(), parent_folder: parent.path().to_string_lossy().into_owned(), supplied: vec![crate::engine::pc_ports::PortSuppliedChoice { @@ -866,6 +868,7 @@ async fn retry_reuses_the_stored_plan_and_its_supplied_sources() { let parent = tempfile::tempdir().unwrap(); let prepared = service .prepare_install(&PortInstallRequest { + plugin_request_id: None, catalog_id: "qcat_lantern".into(), parent_folder: parent.path().to_string_lossy().into_owned(), supplied: Vec::new(), @@ -897,6 +900,7 @@ async fn retry_reuses_the_stored_plan_and_its_supplied_sources() { .unwrap(); let retried = service .prepare_install(&PortInstallRequest { + plugin_request_id: None, catalog_id: "qcat_lantern".into(), parent_folder: parent.path().to_string_lossy().into_owned(), supplied: Vec::new(), @@ -1388,3 +1392,168 @@ async fn a_completed_install_appears_in_the_library_without_a_manual_rescan() { }) .await; } + +/// Records the exact host plan and exposes controlled native job transitions. +struct ReviewRunner { + store: Arc, + plans: Mutex>, +} +impl InstallRunner for ReviewRunner { + fn enqueue(&self, _: InstallJobRequest) -> Result<(), JobError> { + panic!("plugin install must use the guarded runner"); + } + fn enqueue_checked( + &self, + request: InstallJobRequest, + check: gamenode_platform::ports::job_runner::InstallAuthority, + ) -> Result<(), JobError> { + if !check() { + return Err(JobError::Closed); + } + self.store.save_job(&PortJobRow { + id: request.job_id.clone(), + catalog_id: request.plan.catalog_id.clone(), + slug: "fixture".into(), + port_name: "Fixture".into(), + release_version: None, + install_folder: Some(request.plan.target.clone()), + phase: PortJobPhase::Queued, + created_paths: vec![], + registration_id: None, + error: None, + failure_output: None, + seen: false, + created_at: 1, + updated_at: 1, + finished_at: None, + })?; + self.plans.lock().unwrap().push(request); + Ok(()) + } + fn cancel(&self, id: &str) -> bool { + if let Ok(Some(mut row)) = self.store.job(id) + && !row.phase.is_terminal() + { + row.phase = PortJobPhase::Cancelled; + self.store.save_job(&row).unwrap(); + return true; + } + false + } + fn complete_with_executable(&self, _: &str, _: &str) -> Result<(), JobError> { + Err(JobError::Closed) + } + fn awaiting_jobs(&self) -> Result, JobError> { + Ok(vec![]) + } + fn active_job(&self) -> Option { + None + } + fn queued_jobs(&self) -> Vec { + vec![] + } + fn is_active(&self, _: &str) -> bool { + false + } + fn shutdown(&self) {} +} + +#[tokio::test] +async fn plugin_guided_setup_keeps_the_host_plan_and_waits_for_native_completion() { + let _serial = serial().lock().await; + let db = database(); + let store: Arc = Arc::new(db.ports_store()); + let local: Arc = Arc::new(db.local_game_store()); + let catalog = Arc::new(FakeCatalog::new( + vec![entry()], + Some(entry()), + vec![release(Some(format!("sha256:{}", "a".repeat(64))), None)], + )); + let (service, events) = start(service_config(store.clone(), local, catalog)); + service.open(); + let view = wait_for_view(&events, |v| v.catalog.state == PortCatalogState::Ready); + let runner = Arc::new(ReviewRunner { + store: store.clone(), + plans: Mutex::new(vec![]), + }); + service.set_runner_for_test(runner.clone()); + let mut h = harness(FakeApi::new(), FakeCreds::with(None)); + Arc::get_mut(&mut h.engine.shared).unwrap().ports.pc_ports = Some(service.clone()); + h.engine.on_ports_event(PortsEvent::Changed { + view, + completion: None, + }); + let engine = h.engine.clone(); + let result = tokio::spawn(async move { + engine + .review_plugin_port( + "qcat_lantern".into(), + gamenode_core::ports::view::PortPluginRequest { + id: String::new(), + catalog_id: String::new(), + plugin_id: "fixture.plugin".into(), + publisher_fingerprint: "publisher".into(), + sources: vec![], + }, + Arc::new(|| Ok(())), + ) + .await + }); + let review = tokio::time::timeout(Duration::from_secs(5), async { + loop { + if let Some(r) = h.engine.snapshot().ports.plugin_request { + break r; + } + tokio::task::yield_now().await; + } + }) + .await + .unwrap(); + assert!(!result.is_finished()); + assert!(runner.plans.lock().unwrap().is_empty()); + let parent = tempfile::tempdir().unwrap(); + let mut request = PortInstallRequest { + plugin_request_id: Some("edited".into()), + catalog_id: review.catalog_id.clone(), + parent_folder: parent.path().to_string_lossy().into_owned(), + supplied: vec![], + accept_unverified_checksum: false, + accept_malware_flag: false, + retry_job_id: None, + }; + assert!(h.engine.ports_install(request.clone()).await.is_err()); + assert!(runner.plans.lock().unwrap().is_empty()); + request.plugin_request_id = None; + assert!( + h.engine + .plugin_port_install_check(&request) + .unwrap() + .is_none(), + "an unrelated manual install is not fenced by the open review" + ); + request.plugin_request_id = Some(review.id.clone()); + let native = h.engine.ports_install(request).await.unwrap().unwrap(); + h.engine.dismiss_plugin_port(review.id); + tokio::time::sleep(Duration::from_millis(300)).await; + assert!(!result.is_finished(), "queued is not completed"); + assert_eq!( + runner.plans.lock().unwrap()[0].plan.catalog_id, + "qcat_lantern" + ); + let mut row = store.job(&native).unwrap().unwrap(); + row.phase = PortJobPhase::AwaitingExecutable; + store.save_job(&row).unwrap(); + tokio::time::sleep(Duration::from_millis(300)).await; + assert!( + !result.is_finished(), + "executable selection is not completed" + ); + row.phase = PortJobPhase::Completed; + store.save_job(&row).unwrap(); + tokio::time::timeout(Duration::from_secs(5), result) + .await + .unwrap() + .unwrap() + .unwrap(); + service.shutdown(); +} diff --git a/crates/app/src/engine/tests/playtime.rs b/crates/app/src/engine/tests/playtime.rs index 2e402f9f0..770170c51 100644 --- a/crates/app/src/engine/tests/playtime.rs +++ b/crates/app/src/engine/tests/playtime.rs @@ -206,6 +206,241 @@ async fn internal_records_sessions_and_source_switch_preserves_histories() { ); h.engine.shutdown(); } + +#[tokio::test(flavor = "multi_thread")] +async fn disabling_plugin_playtime_preserves_measured_history_and_activation() { + use crate::plugin_host::profile::{PluginProfiles, PluginStateLayout}; + use gamenode_core::playtime::Session; + use std::sync::Arc; + + let h = ready_with_source(PlaytimeSource::Internal).await; + let state_dir = tempfile::tempdir().unwrap(); + let profiles = Arc::new(PluginProfiles::default()); + let layout = PluginStateLayout::new(state_dir.path().join("plugins")); + profiles.set_state_layout(layout.clone()); + h.engine.set_plugin_profiles(profiles.clone()); + + let profile = profiles.current().unwrap(); + layout + .open_activation(&profile) + .unwrap() + .set_enabled("org.example.emulator", true) + .unwrap(); + let existing = Session { + id: "previous-runtime-session".into(), + account_id: "u1".into(), + entry_key: "steam:620".into(), + game_id: Some(7), + source: "runtime:org.example.emulator".into(), + platform_id: 1, + started_at: 100, + checkpoint_at: 200, + ended_at: None, + }; + let store = h.engine.shared.ports.playtime.clone(); + store.open_session(&existing).unwrap(); + store + .close_session("u1", &existing.id, 200, Some(7)) + .unwrap(); + let history_before = store.sessions("u1").unwrap(); + assert_eq!(history_before.len(), 1); + assert_eq!(history_before[0].ended_at, Some(200)); + + h.engine + .set_plugin_playtime_accounting("org.example.emulator".into(), false) + .await + .unwrap(); + + assert!( + !profiles + .is_playtime_accounting_enabled("org.example.emulator") + .unwrap() + ); + assert!( + layout + .open_activation(&profile) + .unwrap() + .is_enabled("org.example.emulator") + ); + assert_eq!(store.sessions("u1").unwrap(), history_before); +} + +#[tokio::test(flavor = "multi_thread")] +async fn runtime_reports_account_for_confirmed_pauses_and_disable_fences_active_session() { + use crate::plugin_host::{ + grants::PluginIdentity, + namespace::ExternalNamespaceResolver, + profile::{PluginProfiles, PluginStateLayout}, + }; + use gamenode_core::library::{ApprovedFileReference, RuntimeContentBinding}; + use gamenode_plugin_protocol::proto::{ + RuntimeSessionOutcome, RuntimeSessionReport, RuntimeSessionTransition, + }; + use std::sync::Arc; + + let h = ready_with_source(PlaytimeSource::Internal).await; + let state_dir = tempfile::tempdir().unwrap(); + let profiles = Arc::new(PluginProfiles::default()); + let layout = PluginStateLayout::new(state_dir.path().join("plugins")); + profiles.set_state_layout(layout.clone()); + h.engine.set_plugin_profiles(profiles.clone()); + + let plugin_id = "org.example.emulator"; + let profile = profiles.current().unwrap(); + layout + .open_activation(&profile) + .unwrap() + .set_enabled(plugin_id, true) + .unwrap(); + let identity = PluginIdentity { + plugin_id: plugin_id.into(), + publisher_fingerprint: "ab".repeat(32), + profile_id: profile.profile_id().to_owned(), + }; + let namespace = ExternalNamespaceResolver::new(identity, None, profile.epoch()).unwrap(); + let owner_key = namespace.library_recipe_owner_key(); + h.store.runtime_bindings.lock().unwrap().insert( + (owner_key.clone(), 7, "steam:620".into()), + vec![RuntimeContentBinding { + game_id: 7, + installation_id: "steam:620".into(), + content_id: "rom:portal".into(), + content: ApprovedFileReference { + approval_id: "approved-content".into(), + relative_path: vec!["portal.rom".into()], + }, + content_kind: "fixture-rom".into(), + runtime_id: "runtime:emulator".into(), + supported_platforms: vec![std::env::consts::OS.into()], + revision: 1, + }], + ); + + let now = super::super::unix_now(); + let started_at = now - 5; + let paused_at = now - 4; + let resumed_at = now - 3; + let checkpoint_at = now - 2; + let received_at = Instant::now(); + let report = |sequence, observed_at, transition| RuntimeSessionReport { + correlation_id: format!("runtime-report-{sequence}"), + game_id: "7".into(), + installation_id: "steam:620".into(), + content_id: "rom:portal".into(), + runtime_id: "runtime:emulator".into(), + runtime_instance_id: "instance:one".into(), + reporter_session_id: "extension-session".into(), + sequence, + observed_at, + transition: transition as i32, + source_observation_id: format!("observation-{sequence}"), + runtime_context_id: String::new(), + }; + let store = h.engine.shared.ports.playtime.clone(); + + let started = h + .engine + .report_runtime_session( + plugin_id.into(), + owner_key.clone(), + report(1, started_at, RuntimeSessionTransition::Started), + false, + None, + received_at, + ) + .await; + assert_eq!(started.outcome, RuntimeSessionOutcome::Accepted as i32); + eventually(|| store.sessions("u1").unwrap().len() == 1).await; + + let paused = h + .engine + .report_runtime_session( + plugin_id.into(), + owner_key.clone(), + report(2, paused_at, RuntimeSessionTransition::Paused), + false, + None, + received_at, + ) + .await; + assert_eq!(paused.outcome, RuntimeSessionOutcome::Accepted as i32); + eventually(|| { + store + .sessions("u1") + .unwrap() + .iter() + .any(|session| session.ended_at == Some(paused_at)) + }) + .await; + + let resumed = h + .engine + .report_runtime_session( + plugin_id.into(), + owner_key.clone(), + report(3, resumed_at, RuntimeSessionTransition::Resumed), + false, + None, + received_at, + ) + .await; + assert_eq!(resumed.outcome, RuntimeSessionOutcome::Accepted as i32); + let checkpoint = h + .engine + .report_runtime_session( + plugin_id.into(), + owner_key.clone(), + report(4, checkpoint_at, RuntimeSessionTransition::Identified), + false, + None, + received_at, + ) + .await; + assert_eq!(checkpoint.outcome, RuntimeSessionOutcome::Accepted as i32); + + let sessions_before_disable = store.sessions("u1").unwrap(); + assert_eq!(sessions_before_disable.len(), 2); + assert_eq!(sessions_before_disable[0].ended_at, Some(paused_at)); + assert!(sessions_before_disable[1].ended_at.is_none()); + h.engine + .set_plugin_playtime_accounting(plugin_id.into(), false) + .await + .unwrap(); + eventually(|| { + store + .sessions("u1") + .unwrap() + .iter() + .any(|session| session.ended_at == Some(checkpoint_at)) + }) + .await; + let sessions_after_disable = store.sessions("u1").unwrap(); + assert_eq!(sessions_after_disable.len(), 2); + + let after_disable = h + .engine + .report_runtime_session( + plugin_id.into(), + owner_key, + report(5, now - 1, RuntimeSessionTransition::Ended), + false, + None, + received_at, + ) + .await; + assert_eq!( + after_disable.outcome, + RuntimeSessionOutcome::RejectedUnavailable as i32 + ); + assert_eq!(store.sessions("u1").unwrap(), sessions_after_disable); + assert!( + layout + .open_activation(&profile) + .unwrap() + .is_enabled(plugin_id) + ); +} + #[tokio::test(flavor = "multi_thread")] async fn quit_flushes_a_closed_session_and_signout_preserves_its_account() { for signout in [false, true] { diff --git a/crates/app/src/engine/tests/provider_runtime.rs b/crates/app/src/engine/tests/provider_runtime.rs index ab7cc34ce..a9e2a548f 100644 --- a/crates/app/src/engine/tests/provider_runtime.rs +++ b/crates/app/src/engine/tests/provider_runtime.rs @@ -22,14 +22,29 @@ use std::sync::{Arc, Mutex}; use tokio::sync::Semaphore; use tonic::Status; -static ACHIEVEMENT_ACTIVE: AtomicUsize = AtomicUsize::new(0); -pub(crate) static ACHIEVEMENT_MAX_ACTIVE: AtomicUsize = AtomicUsize::new(0); -pub(crate) static ACHIEVEMENT_FAIL_NEXT: AtomicBool = AtomicBool::new(false); +/// Achievement calls seen by one fixture `Runtime`. Each engine harness owns its own probe, so +/// tests running in parallel never observe each other's batches. +#[derive(Default)] +pub(crate) struct AchievementProbe { + active: AtomicUsize, + pub(crate) max_active: AtomicUsize, + pub(crate) fail_next: AtomicBool, +} + +/// Leaves the in-flight count even when the call is dropped mid-batch. +struct ActiveBatch<'a>(&'a AtomicUsize); + +impl Drop for ActiveBatch<'_> { + fn drop(&mut self) { + self.0.fetch_sub(1, AtomicOrdering::SeqCst); + } +} pub(crate) struct Runtime { files: Arc, roots: Arc, platform: Platform, + achievements: Arc, } struct Files(Arc); @@ -63,8 +78,12 @@ impl Runtime { files: ports.files.clone(), roots: ports.roots.clone(), platform: ports.platform, + achievements: Arc::default(), } } + pub(crate) fn achievement_probe(&self) -> Arc { + self.achievements.clone() + } fn manifest() -> discovery::Manifest { toml::from_str(include_str!("../../../../../providers/steam.toml")).unwrap() } @@ -97,11 +116,13 @@ impl ProviderRuntime for Runtime { _: &str, request: models::AchievementsRequest, ) -> Result { - if ACHIEVEMENT_FAIL_NEXT.swap(false, AtomicOrdering::SeqCst) { + let probe = &self.achievements; + if probe.fail_next.swap(false, AtomicOrdering::SeqCst) { return Err(Status::unavailable("fixture achievement failure")); } - let active = ACHIEVEMENT_ACTIVE.fetch_add(1, AtomicOrdering::SeqCst) + 1; - ACHIEVEMENT_MAX_ACTIVE.fetch_max(active, AtomicOrdering::SeqCst); + let active = probe.active.fetch_add(1, AtomicOrdering::SeqCst) + 1; + let _batch = ActiveBatch(&probe.active); + probe.max_active.fetch_max(active, AtomicOrdering::SeqCst); tokio::time::sleep(std::time::Duration::from_millis(5)).await; let outcomes = request .game_ids @@ -121,7 +142,6 @@ impl ProviderRuntime for Runtime { }], }) .collect(); - ACHIEVEMENT_ACTIVE.fetch_sub(1, AtomicOrdering::SeqCst); Ok(Completion::fixture_achievements(outcomes)) } async fn execute(&self, _: &str, operation: ProviderOperation) -> Result { @@ -153,6 +173,7 @@ impl ProviderRuntime for Runtime { name: r.name.unwrap_or_default(), install_dir: r.install_dir, fields: r.fields.into_iter().collect(), + target: None, }) .collect(), install_root: scan.install_root, @@ -467,6 +488,7 @@ fn entry(key: &str, name: &str, installed: bool, owned: bool, shared: bool) -> S }, fields: Default::default(), installed, + target: None, owned, shared, first_seen: 1, diff --git a/crates/app/src/engine/tests/tools.rs b/crates/app/src/engine/tests/tools.rs index 6eca4b5af..cdf1e93c2 100644 --- a/crates/app/src/engine/tests/tools.rs +++ b/crates/app/src/engine/tests/tools.rs @@ -6,6 +6,7 @@ use gamenode_core::tools::{ ToolRelease, ToolStore, optiscaler_descriptor, }; use std::collections::VecDeque; +use std::sync::atomic::AtomicBool; async fn eventually(mut predicate: impl FnMut() -> bool) { tokio::time::timeout(Duration::from_secs(5), async { @@ -106,6 +107,7 @@ fn tools_harness() -> ToolsHarness { }]; let ports = Ports { + discovery: None, achievements: super::test_achievement_store(), backups: None, local_games: None, @@ -167,6 +169,7 @@ fn tools_harness() -> ToolsHarness { Settings::default(), LibraryMachine::new(providers, Default::default()), nonce, + Arc::new(crate::plugin_host::resource_leases::ResourceLeases::default()), move |s| { let _ = tx.send(s); }, @@ -186,6 +189,8 @@ fn tools_harness() -> ToolsHarness { uri, covers, achievements: super::test_achievement_store(), + // Tools tests never read achievements; this probe is not wired to the engine. + achievement_probe: Arc::default(), }; ToolsHarness { @@ -880,6 +885,7 @@ async fn the_default_channel_preselects_the_install_channel() { th.harness .engine .open_tools(Some("manual:game1".to_string())); + eventually(|| th.harness.engine.snapshot().tools.modal.is_some()).await; let modal = th.harness.engine.snapshot().tools.modal.unwrap(); assert_eq!(modal.selected_channel, ToolChannel::Nightly); @@ -1140,3 +1146,144 @@ async fn clear_tool_cache_resets_bytes_and_archives() { "clearing the settings cache removes achievement icons" ); } + +fn plugin_review(remove: bool) -> gamenode_core::tools::ToolPluginRequest { + gamenode_core::tools::ToolPluginRequest { + plugin_id: "fixture.plugin".into(), + publisher_fingerprint: "publisher-fingerprint".into(), + remove, + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn plugin_tool_review_waits_for_user_selection_and_returns_the_real_operation_result() { + let th = tools_harness(); + add_test_game(&th, "plugin", "Fixture"); + let engine = th.harness.engine.clone(); + let review = tokio::spawn(async move { + engine + .review_plugin_tool( + "manual:plugin".into(), + "optiscaler".into(), + plugin_review(false), + Arc::new(|| Ok(())), + ) + .await + }); + eventually(|| { + th.harness + .engine + .snapshot() + .tools + .modal + .as_ref() + .is_some_and(|m| m.inspection.is_some() && !m.available_versions.is_empty()) + }) + .await; + let modal = th.harness.engine.snapshot().tools.modal.unwrap(); + assert_eq!( + modal.plugin_request.as_ref().unwrap().plugin_id, + "fixture.plugin" + ); + assert!(th.store.list_installations().unwrap().is_empty()); + th.harness.engine.uninstall_tool(); // An apply request never authorizes removal. + assert!( + th.harness + .engine + .snapshot() + .tools + .modal + .unwrap() + .operation + .is_none() + ); + th.harness.engine.set_tool_anticheat_confirmed(true); + th.harness.engine.install_or_update_tool(false); + review.await.unwrap().unwrap(); + assert_eq!(th.store.list_installations().unwrap().len(), 1); + th.harness.engine.close_tools(); + let engine = th.harness.engine.clone(); + let removal = tokio::spawn(async move { + engine + .review_plugin_tool( + "manual:plugin".into(), + "optiscaler".into(), + plugin_review(true), + Arc::new(|| Ok(())), + ) + .await + }); + eventually(|| { + th.harness + .engine + .snapshot() + .tools + .modal + .as_ref() + .is_some_and(|m| m.plugin_request.as_ref().is_some_and(|r| r.remove)) + }) + .await; + th.harness.engine.install_or_update_tool(true); // Removal never authorizes installation. + assert!( + th.harness + .engine + .snapshot() + .tools + .modal + .unwrap() + .operation + .is_none() + ); + th.harness.engine.uninstall_tool(); + removal.await.unwrap().unwrap(); + assert!(th.store.list_installations().unwrap().is_empty()); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_closed_or_revoked_plugin_tool_review_never_installs_and_another_request_cannot_replace_it() + { + for revoked in [false, true] { + let th = tools_harness(); + add_test_game(&th, "plugin", "Fixture"); + let allowed = Arc::new(AtomicBool::new(true)); + let flag = allowed.clone(); + let engine = th.harness.engine.clone(); + let review = tokio::spawn(async move { + engine + .review_plugin_tool( + "manual:plugin".into(), + "optiscaler".into(), + plugin_review(false), + Arc::new(move || { + if flag.load(Ordering::SeqCst) { + Ok(()) + } else { + Err(tonic::Status::permission_denied("revoked")) + } + }), + ) + .await + }); + eventually(|| th.harness.engine.snapshot().tools.modal.is_some()).await; + let other = th + .harness + .engine + .review_plugin_tool( + "manual:plugin".into(), + "optiscaler".into(), + plugin_review(true), + Arc::new(|| Ok(())), + ) + .await + .unwrap_err(); + assert_eq!(other.code(), tonic::Code::ResourceExhausted); + if revoked { + allowed.store(false, Ordering::SeqCst); + } else { + th.harness.engine.close_tools(); + } + assert!(review.await.unwrap().is_err()); + eventually(|| th.harness.engine.snapshot().tools.modal.is_none()).await; + assert!(th.store.list_installations().unwrap().is_empty()); + } +} diff --git a/crates/app/src/engine/tools.rs b/crates/app/src/engine/tools.rs index 2d815500f..3f21ddcaf 100644 --- a/crates/app/src/engine/tools.rs +++ b/crates/app/src/engine/tools.rs @@ -41,7 +41,207 @@ struct ToolModalGuard { channel: ToolChannel, } +pub(super) struct PluginToolRequest { + id: String, + entry_key: String, + tool_id: String, + review: gamenode_core::tools::ToolPluginRequest, + check: crate::plugin_host::jobs::Fence, + done: tokio::sync::oneshot::Sender>, + started: bool, +} + +struct ToolWait { + engine: Engine, + id: String, +} +impl Drop for ToolWait { + fn drop(&mut self) { + self.engine.cancel_plugin_tool(&self.id); + } +} + impl Engine { + pub(super) fn plugin_tools_list( + &self, + entry_key: &str, + ) -> Result, tonic::Status> { + let state = self.lock(); + if state.library.entry(entry_key).is_none() + && !state + .local + .registrations + .iter() + .any(|r| r.key() == entry_key && !r.removed) + { + return Err(tonic::Status::not_found("game not found")); + } + drop(state); + let installed = self + .shared + .ports + .tools + .as_ref() + .map(|s| s.list_for_entry(entry_key)) + .transpose() + .map_err(|_| tonic::Status::unavailable("tools state unavailable"))? + .unwrap_or_default(); + Ok(builtin_tools() + .into_iter() + .map(|d| { + let current = installed.iter().find(|i| i.tool_id == d.id); + gamenode_plugin_protocol::proto::ToolRecord { + tool_id: d.id.as_str().into(), + name: d.name, + version: current.map(|i| i.version.clone()).unwrap_or_default(), + availability: if !cfg!(windows) + || self.shared.ports.tool_installer.is_none() + || self.shared.ports.tool_catalog.is_none() + || self.shared.ports.tools.is_none() + { + "unavailable" + } else if current.is_some_and(|i| { + i.state == gamenode_core::tools::ToolInstallState::Installed + }) { + "installed" + } else if current.is_some() { + "busy" + } else { + "available" + } + .into(), + } + }) + .collect()) + } + + pub(super) async fn request_plugin_tool( + &self, + entry_key: String, + tool_id: String, + review: gamenode_core::tools::ToolPluginRequest, + check: crate::plugin_host::jobs::Fence, + ) -> Result<(), tonic::Status> { + if !cfg!(windows) { + return Err(tonic::Status::unavailable("tools are Windows-only")); + } + self.review_plugin_tool(entry_key, tool_id, review, check) + .await + } + + /// Platform-independent review coordinator; callers enforce platform availability. + pub(super) async fn review_plugin_tool( + &self, + entry_key: String, + tool_id: String, + review: gamenode_core::tools::ToolPluginRequest, + check: crate::plugin_host::jobs::Fence, + ) -> Result<(), tonic::Status> { + if self.shared.ports.tool_installer.is_none() + || self.shared.ports.tools.is_none() + || self.shared.ports.tool_catalog.is_none() + { + return Err(tonic::Status::unavailable("tools ports unavailable")); + } + if find_tool(&tool_id).is_none() { + return Err(tonic::Status::not_found("tool not found")); + } + check()?; + let id = gamenode_platform::random::session_id(); + let (done, mut result) = tokio::sync::oneshot::channel(); + { + let mut state = self.lock(); + if state.tools.modal.is_some() || state.plugin_tool_request.is_some() { + return Err(tonic::Status::resource_exhausted( + "tools window is already in use", + )); + } + state.plugin_tool_request = Some(PluginToolRequest { + id: id.clone(), + entry_key: entry_key.clone(), + tool_id: tool_id.clone(), + review, + check: check.clone(), + done, + started: false, + }); + } + let _wait = ToolWait { + engine: self.clone(), + id: id.clone(), + }; + let engine = self.clone(); + let request_id = id.clone(); + tokio::task::spawn_blocking(move || { + engine.open_tools_impl(Some(entry_key), ToolId::new(tool_id), Some(&request_id)) + }) + .await + .map_err(|_| tonic::Status::unavailable("tools review unavailable"))?; + if self.lock().tools.modal.is_none() { + return Err(tonic::Status::failed_precondition( + "tools target unavailable", + )); + } + let deadline = Instant::now() + Duration::from_secs(300); + loop { + tokio::select! { + answer = &mut result => return answer.unwrap_or_else(|_| Err(tonic::Status::cancelled("tools review closed"))), + () = tokio::time::sleep(Duration::from_millis(100)) => { + let started = self.lock().plugin_tool_request.as_ref().is_some_and(|r| r.id == id && r.started); + if !started { + check()?; + if Instant::now() >= deadline { return Err(tonic::Status::deadline_exceeded("tools review timed out")); } + } + } + } + } + } + + fn cancel_plugin_tool(&self, id: &str) { + let mut state = self.lock(); + if state + .plugin_tool_request + .as_ref() + .is_some_and(|r| r.id == id && !r.started) + { + state.plugin_tool_request.take(); + state.tools.modal = None; + self.publish(&mut state); + } + } + + fn plugin_tool_operation_allowed(&self, remove: bool) -> bool { + let state = self.lock(); + state + .plugin_tool_request + .as_ref() + .is_none_or(|r| !r.started && r.review.remove == remove && (r.check)().is_ok()) + } + + fn begin_plugin_tool( + &self, + remove: bool, + ) -> Result, ()> { + let mut state = self.lock(); + let Some(request) = state.plugin_tool_request.as_ref() else { + return Ok(None); + }; + if request.started + || request.review.remove != remove + || !state.tools.modal.as_ref().is_some_and(|m| { + m.entry_key == request.entry_key && m.active_tool_id.as_str() == request.tool_id + }) + { + return Err(()); + } + if (request.check)().is_err() { + return Err(()); + } + let request = state.plugin_tool_request.as_mut().unwrap(); + request.started = true; + Ok(Some(request.check.clone())) + } + /// Dispatches startup recovery of incomplete tool jobs and initializes installed tools /// and catalog state. pub fn recover_and_load_tools(&self) { @@ -363,6 +563,23 @@ impl Engine { /// Opens the tools modal for the specified `entry_key`. pub fn open_tools(&self, entry_key: Option) { + if self.lock().plugin_tool_request.is_some() { + return; + } + let engine = self.clone(); + self.shared.runtime.spawn_blocking(move || { + if engine.lock().plugin_tool_request.is_none() { + engine.open_tools_impl(entry_key, ToolId::new("optiscaler"), None); + } + }); + } + + fn open_tools_impl( + &self, + entry_key: Option, + active_tool_id: ToolId, + request_id: Option<&str>, + ) { let Some(entry_key) = entry_key else { return; }; @@ -393,6 +610,15 @@ impl Engine { } let mut state = self.lock(); + if match request_id { + Some(id) => !state + .plugin_tool_request + .as_ref() + .is_some_and(|r| r.id == id), + None => state.plugin_tool_request.is_some(), + } { + return; + } let existing_tools = state .tools .installed_by_entry @@ -400,7 +626,6 @@ impl Engine { .cloned() .unwrap_or_default(); - let active_tool_id = ToolId::new("optiscaler"); let installed_tool = existing_tools.iter().find(|t| t.tool_id == active_tool_id); let channel = installed_tool @@ -427,7 +652,9 @@ impl Engine { .map(|t| t.version.clone()) .or_else(|| cached_releases.first().map(|r| r.version.clone())); + let plugin_request = state.plugin_tool_request.as_ref().map(|r| r.review.clone()); state.tools.modal = Some(ToolModalView { + plugin_request, entry_key: entry_key.clone(), title: title.clone(), install_dir: install_dir.clone(), @@ -544,6 +771,11 @@ impl Engine { return; } state.tools.modal = None; + if let Some(request) = state.plugin_tool_request.take() { + let _ = request + .done + .send(Err(tonic::Status::cancelled("tools review declined"))); + } self.publish(&mut state); } @@ -801,6 +1033,9 @@ impl Engine { /// Executes transactional installation or version update of the active tool. pub fn install_or_update_tool(&self, is_update: bool) { + if !self.plugin_tool_operation_allowed(false) { + return; + } let (request, release, descriptor, install_dir) = { let mut state = self.lock(); let ( @@ -973,16 +1208,43 @@ impl Engine { return; }; + let Ok(fence) = self.begin_plugin_tool(false) else { + return; + }; let engine = self.clone(); self.shared.runtime.spawn_blocking(move || { - let result = installer.install_or_update( - &*store, - &*catalog, - &descriptor, - &release, - &request, - &install_dir, - ); + let check = || { + fence + .as_ref() + .map(|f| { + f().map_err(|_| { + gamenode_core::tools::ToolError::Failed( + "tool authorization ended".into(), + ) + }) + }) + .unwrap_or(Ok(())) + }; + let result = if fence.is_some() { + installer.install_or_update_checked( + &*store, + &*catalog, + &descriptor, + &release, + &request, + &install_dir, + &check, + ) + } else { + installer.install_or_update( + &*store, + &*catalog, + &descriptor, + &release, + &request, + &install_dir, + ) + }; match result { Ok(_installation) => { @@ -997,6 +1259,9 @@ impl Engine { /// Executes transactional uninstallation of the active tool. pub fn uninstall_tool(&self) { + if !self.plugin_tool_operation_allowed(true) { + return; + } let (entry_key, tool_id, install_dir) = { let mut state = self.lock(); let Some(modal) = &mut state.tools.modal else { @@ -1027,9 +1292,34 @@ impl Engine { return; }; + let Ok(fence) = self.begin_plugin_tool(true) else { + return; + }; let engine = self.clone(); self.shared.runtime.spawn_blocking(move || { - let result = installer.uninstall(&*store, &entry_key, tool_id.as_str(), &install_dir); + let check = || { + fence + .as_ref() + .map(|f| { + f().map_err(|_| { + gamenode_core::tools::ToolError::Failed( + "tool authorization ended".into(), + ) + }) + }) + .unwrap_or(Ok(())) + }; + let result = if fence.is_some() { + installer.uninstall_checked( + &*store, + &entry_key, + tool_id.as_str(), + &install_dir, + &check, + ) + } else { + installer.uninstall(&*store, &entry_key, tool_id.as_str(), &install_dir) + }; match result { Ok(()) => { engine.reload_tools_after_mutation(&entry_key, Ok(())); @@ -1131,6 +1421,23 @@ impl Engine { state.tools.cache_entries = cache_entries; state.tools.achievement_icon_cache_bytes = achievement_icon_cache_bytes; + if state + .plugin_tool_request + .as_ref() + .is_some_and(|r| r.entry_key == entry_key && r.started) + { + let request = state.plugin_tool_request.take().unwrap(); + let answer = outcome.as_ref().map(|_| ()).map_err(|_| { + tonic::Status::failed_precondition( + "tool operation failed; inspect Core tool status", + ) + }); + let _ = request.done.send(answer); + // The plugin request has ended. Keep errors visible, without leaving a live action. + if let Some(modal) = &mut state.tools.modal { + modal.plugin_request = None; + } + } if let Some(modal) = &mut state.tools.modal && modal.entry_key == entry_key { diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index 04d8c63aa..9a716b840 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -121,6 +121,12 @@ fn set_webview_visible(window: &tauri::WebviewWindow, visible: bool) { } fn main() -> Result<(), Box> { + #[cfg(target_os = "linux")] + if let Some(result) = + gamenode_app::plugin_host::launch_supervisor::run_linux_helper_if_requested() + { + return result; + } let runtime = tokio::runtime::Builder::new_multi_thread() .enable_all() .build()?; @@ -140,6 +146,7 @@ fn main() -> Result<(), Box> { let paths = DataPaths::resolve().ok_or("Could not locate your application data directory")?; paths.ensure_data_dir()?; + let plugin_updates = gamenode_app::plugin_host::updates::PluginUpdateService::open(&paths)?; let logging = gamenode_app::logging::init(&paths); tracing::info!( version = env!("CARGO_PKG_VERSION"), @@ -150,6 +157,7 @@ fn main() -> Result<(), Box> { "GameNode Desktop starting" ); let store = Arc::new(SqliteSettingsStore::open(&paths.database_file())?); + plugin_updates.set_bundle_store(store.bundle_store()); let initial_settings = store.load()?; // The lifecycle preferences decide the login value before any window exists. #[cfg(windows)] @@ -161,11 +169,14 @@ fn main() -> Result<(), Box> { let platform = gamenode_core::provider::Platform::current() .ok_or("GameNode Desktop supports Windows and Linux only")?; - let providers = gamenode_app::providers::load_bundled_with_plugins( - platform, - &gamenode_app::plugin_host::backends(platform), - ) - .providers; + // Official manifests keep their exact order and behavior; an installed third-party provider + // package that passed the reviewed import is appended here, before the library exists. The + // registry, trust and package inspection run on blocking workers inside the composition. + let providers = runtime + .block_on(gamenode_app::plugin_host::startup::load_library_providers( + platform, &paths, + )) + .providers; let library_store = Arc::new(store.library_store()); let layout = library_store.load_layout().unwrap_or_else(|error| { tracing::warn!(%error, "could not read the saved library layout; using the default"); @@ -194,8 +205,33 @@ fn main() -> Result<(), Box> { )?); let processes: Arc = Arc::new(gamenode_platform::processes::HostProcesses::new()); + // One coordinator instance is shared by supervised runtime launches and backup/restore jobs. + let custom_launch_leases = + Arc::new(gamenode_app::plugin_host::resource_leases::ResourceLeases::default()); - let plugin_api = gamenode_app::plugin_host::PluginApi::default(); + let plugin_api = gamenode_app::plugin_host::PluginApi { + shared_policies: Arc::new( + gamenode_app::plugin_host::sharing_policy::SharedSharingPolicies::open( + paths.plugin_data_dir().join("shared-data-policies"), + )?, + ), + storage: Arc::new(gamenode_app::plugin_host::storage::PluginStorage::new( + paths.plugin_data_dir(), + )), + shared_pool: Arc::new( + gamenode_app::plugin_host::shared_pool::DurableSharedPool::new(paths.data_dir()), + ), + // Nothing under the application data folder is reachable through file handles. The + // folder-approval dialog is connected with the settings UI (`FileAccess::set_approver`). + files: Arc::new(gamenode_app::plugin_host::files::FileAccess::new( + gamenode_platform::plugin_files::Reserved::new(&[paths.data_dir().to_path_buf()]), + )), + leases: custom_launch_leases.clone(), + processes: Some(processes.clone()), + ..Default::default() + }; + plugin_api + .set_state_layout(gamenode_app::plugin_host::profile::PluginStateLayout::managed(&paths)); #[cfg(target_os = "linux")] let plugin_api_server = match gamenode_app::plugin_host::PluginApiServer::start( runtime.handle(), @@ -240,6 +276,7 @@ fn main() -> Result<(), Box> { let provider_runtime = match runtime.block_on( gamenode_app::plugin_host::runtime::HostedProviders::bundled( plugin_api.providers.clone(), + plugin_api.intents.clone(), plugin_endpoint, paths.clone(), library_store.clone(), @@ -252,6 +289,12 @@ fn main() -> Result<(), Box> { None } }; + if let Some(provider_runtime) = provider_runtime.as_ref() { + provider_runtime + .lifecycle() + .set_private_storage(plugin_api.storage.clone()); + plugin_updates.set_lifecycle(provider_runtime.lifecycle()); + } let app_handle_slot = Arc::new(std::sync::Mutex::new(None::)); let slot_clone = app_handle_slot.clone(); @@ -263,6 +306,101 @@ fn main() -> Result<(), Box> { } }); + // A plugin's notification leaves on its own event and is shown by the window as plain text. + // It is an event, not state: with no window listening it is dropped. + struct NoticeSink(Arc>>); + impl gamenode_app::plugin_host::notifications::NotificationSink for NoticeSink { + fn deliver(&self, notice: gamenode_app::plugin_host::notifications::PluginNotice) { + if let Some(app) = self.0.lock().unwrap().as_ref() { + use tauri::Emitter; + let _ = app.emit(gamenode_app::plugin_host::notifications::EVENT, ¬ice); + } + } + } + plugin_api + .notifications + .set_sink(Arc::new(NoticeSink(app_handle_slot.clone()))); + + // Folder approvals are collected by the host, correlated through one-use ids, and answered + // by the shared React window. No plugin-suggested path is trusted until the user selects it + // and the host validates/canonicalizes it in the resource handler. + let root_approval_slot = app_handle_slot.clone(); + let root_approvals = Arc::new(gamenode_app::plugin_host::files::RootApprovalBridge::new( + Arc::new(move |signal| { + use gamenode_app::plugin_host::files::{ + ROOT_CLOSED_EVENT, ROOT_CONFIRM_EVENT, ROOT_SELECT_EVENT, RootApprovalSignal, + }; + use tauri::Emitter; + let guard = root_approval_slot.lock().unwrap(); + let Some(app) = guard.as_ref() else { + return false; + }; + match signal { + RootApprovalSignal::Select(prompt) => app.emit(ROOT_SELECT_EVENT, &prompt).is_ok(), + RootApprovalSignal::Confirm(prompt) => { + app.emit(ROOT_CONFIRM_EVENT, &prompt).is_ok() + } + RootApprovalSignal::Closed(id) => app.emit(ROOT_CLOSED_EVENT, id).is_ok(), + } + }), + )); + plugin_api.files.set_approver(root_approvals.clone()); + + // Runtime executable approvals use the same one-use prompt pattern. The plugin sends hints; + // the host shows its installed-program candidates and the user approves exactly one program. + let runtime_approval_slot = app_handle_slot.clone(); + let runtime_approvals = Arc::new( + gamenode_app::plugin_host::runtime_access::RuntimeApprovalBridge::new(Arc::new( + move |signal| { + use gamenode_app::plugin_host::runtime_access::{ + RUNTIME_CLOSED_EVENT, RUNTIME_SELECT_EVENT, RuntimeApprovalSignal, + }; + use tauri::Emitter; + let guard = runtime_approval_slot.lock().unwrap(); + let Some(app) = guard.as_ref() else { + return false; + }; + match signal { + RuntimeApprovalSignal::Select(prompt) => { + app.emit(RUNTIME_SELECT_EVENT, &prompt).is_ok() + } + RuntimeApprovalSignal::Closed(id) => app.emit(RUNTIME_CLOSED_EVENT, id).is_ok(), + } + }, + )), + ); + plugin_api + .files + .set_runtime_approver(runtime_approvals.clone()); + + // A plugin's request to launch or install a game is confirmed in the window: the bridge shows + // it with an event and takes the answer from a command. With no window listening, a request + // that needs the user fails instead of waiting. + let confirmation_slot = app_handle_slot.clone(); + let confirmations = Arc::new( + gamenode_app::plugin_host::confirmations::ConfirmationBridge::new(Arc::new( + move |signal| { + use gamenode_app::plugin_host::confirmations::{CLOSED_EVENT, EVENT, Signal}; + use tauri::Emitter; + let guard = confirmation_slot.lock().unwrap(); + let Some(app) = guard.as_ref() else { + return false; + }; + match signal { + Signal::Open(confirmation) => app.emit(EVENT, confirmation.as_ref()).is_ok(), + Signal::Closed(id) => app.emit(CLOSED_EVENT, &id).is_ok(), + } + }, + )), + ); + plugin_api.intents.set_prompter(confirmations.clone()); + let plugin_approvals = Arc::new( + gamenode_app::plugin_host::confirmations::PluginApprovals::new( + plugin_api.storage.clone(), + plugin_api.providers.profiles(), + ), + ); + // PC ports progress leaves on its own event; the engine coalesces ticks before they get here. let progress_app_slot = app_handle_slot.clone(); let port_progress = Arc::new(PortProgressPublisher::new( @@ -305,14 +443,22 @@ fn main() -> Result<(), Box> { let achievement_store = store.achievement_store(); let engine = Engine::new( Ports { + discovery: None, achievements: Arc::new(achievement_store), backups: Some(Arc::new(gamenode_platform::backups::Ludusavi::bundled( paths.data_dir(), )?)), local_games: Some(local_game_store), - installations: Some(Arc::new( - gamenode_platform::installations::WindowsInstallations, - )), + installations: Some(Arc::new({ + #[cfg(target_os = "windows")] + { + gamenode_platform::installations::WindowsInstallations + } + #[cfg(target_os = "linux")] + { + gamenode_platform::installations::LinuxInstallations + } + })), tools: Some(Arc::new(store.tool_store())), tool_catalog: Some(Arc::new( gamenode_platform::tools::catalog::GitHubToolCatalog::new(paths.tools_cache_dir())?, @@ -327,7 +473,7 @@ fn main() -> Result<(), Box> { processes, playtime: Arc::new(store.playtime_store()), playtime_api: client.clone(), - settings: store, + settings: store.clone(), credentials, api: client.clone(), browser: Arc::new(SystemBrowser), @@ -346,6 +492,7 @@ fn main() -> Result<(), Box> { initial_settings, library, Box::new(random::nonce), + custom_launch_leases.clone(), move |snapshot| { pub_clone.publish(snapshot); }, @@ -353,8 +500,41 @@ fn main() -> Result<(), Box> { if let Some(provider_runtime) = provider_runtime.clone() { engine.set_provider_runtime(provider_runtime); } + // HostedProviders owns the single profile lifecycle observer: it fences sessions, reaps old + // process trees, then restores only the new account's enabled plugins. + engine.set_plugin_profiles(plugin_api.providers.profiles()); + plugin_updates.set_profiles(plugin_api.providers.profiles()); + // Plugins read the library through a host-owned projection the engine keeps current. + engine.set_library_feed(plugin_api.library.clone()); + let folder_approvals = Arc::new( + gamenode_app::plugin_host::file_approvals::PluginFolderApprovals::new( + plugin_api.storage.clone(), + plugin_api.providers.profiles(), + plugin_api.files.clone(), + plugin_api.library.clone(), + root_approvals.clone(), + ), + ); + let shared_resources = Arc::new( + gamenode_app::plugin_host::shared_resources::PluginSharedResources::new( + plugin_api.storage.clone(), + plugin_api.providers.profiles(), + plugin_api.files.clone(), + plugin_api.library.clone(), + ), + ); + let runtime_approval_settings = Arc::new( + gamenode_app::plugin_host::runtime_approvals::PluginRuntimeApprovals::new( + plugin_api.storage.clone(), + plugin_api.providers.profiles(), + ), + ); + if let Some(server) = plugin_api_server.as_ref() { + engine.set_selected_launch_api(server.resource_api()); + } let mut builder = tauri::Builder::default(); + builder = builder.plugin(tauri_plugin_dialog::init()); builder = gamenode_app::protocol::register_asset_protocol( builder, paths.covers_dir(), @@ -362,6 +542,21 @@ fn main() -> Result<(), Box> { ); builder = builder.manage(engine.clone()); + builder = builder.manage(store.clone()); + builder = builder.manage(plugin_api.providers.clone()); + builder = builder.manage(plugin_api.shared_policies.clone()); + builder = builder.manage(plugin_api.data_broker.clone()); + if let Some(provider_runtime) = provider_runtime.as_ref() { + builder = builder.manage(provider_runtime.lifecycle()); + } + builder = builder.manage(confirmations); + builder = builder.manage(root_approvals); + builder = builder.manage(runtime_approvals); + builder = builder.manage(folder_approvals); + builder = builder.manage(runtime_approval_settings); + builder = builder.manage(shared_resources); + builder = builder.manage(plugin_approvals); + builder = builder.manage(plugin_updates.clone()); builder = builder.manage(logging.location().clone()); // Serves `gamenode-asset://localhost/port-art//`; without this state // every port artwork request is answered 404. @@ -371,6 +566,32 @@ fn main() -> Result<(), Box> { )), paths.data_dir(), )?); + let periodic_updates = plugin_updates.clone(); + let background_runtime = runtime.handle().clone(); + builder = builder.setup(move |app| { + let app = app.handle().clone(); + let updates = periodic_updates.clone(); + background_runtime.spawn(async move { + let mut interval = tokio::time::interval(Duration::from_secs(24 * 60 * 60)); + loop { + interval.tick().await; + if !updates.preferences().periodic_checks { + continue; + } + match updates.check_updates().await { + Ok(available) if !available.is_empty() => { + use tauri::Emitter; + if let Err(error) = app.emit("plugin:update-available", &available) { + tracing::warn!(%error, "could not notify the UI about plugin updates"); + } + } + Ok(_) => {} + Err(error) => tracing::debug!(%error, "periodic plugin update check failed"), + } + } + }); + Ok(()) + }); builder = builder.invoke_handler(tauri::generate_handler![ commands::get_snapshot, commands::get_app_info, @@ -386,7 +607,14 @@ fn main() -> Result<(), Box> { commands::library_input, commands::activate_entry, commands::open_entry, + commands::review_detected_target, + commands::launch_recipe_choices, + commands::select_launch_recipe, + commands::use_detected_default, + commands::repair_detected_target, commands::launch_selected, + commands::start_extension_action, + commands::available_plugin_extensions, commands::dismiss_launch, commands::rescan_library, commands::open_gamenode_page, @@ -441,12 +669,83 @@ fn main() -> Result<(), Box> { commands::open_tool_source, commands::clear_tool_cache, commands::plugin_inventory, + commands::plugin_import_review, + commands::plugin_import_confirm_publisher, + commands::plugin_import_install, + commands::plugin_import_license_text, + commands::plugin_bundle_import_review, + commands::plugin_bundle_import_confirm_publisher, + commands::plugin_bundle_import_install, + commands::plugin_bundle_permissions_replace, + commands::plugin_bundle_update_check, + commands::plugin_bundle_update_available, + commands::plugin_bundle_update_review, + commands::plugin_bundle_update_approve, + commands::plugin_bundle_update_decline, + commands::plugin_bundle_rollback_available, + commands::plugin_bundle_rollback_review, + commands::plugin_bundle_rollback_approve, + commands::plugin_permission_snapshot, + commands::plugin_permissions_replace, + commands::plugin_shared_data_snapshot, + commands::plugin_shared_data_replace, + commands::plugin_durable_usage, + commands::plugin_durable_delete, + commands::plugin_durable_reuse, + commands::plugin_private_reuse, + commands::plugin_storage_cleanup_review, + commands::plugin_storage_cleanup_apply, + commands::plugin_storage_locations, + gamenode_app::plugin_host::migration::plugin_publisher_migration_preview, + gamenode_app::plugin_host::migration::plugin_publisher_migration_apply, + gamenode_app::plugin_host::migration::plugin_publisher_migration_cancel, + gamenode_app::plugin_host::migration::plugin_publisher_migration_rollback, + commands::plugin_enable, + commands::plugin_disable, + commands::plugin_remove, + commands::plugin_bundle_uninstall, + commands::plugin_configuration_state, + commands::plugin_configuration_modes, + commands::plugin_configuration_open, + commands::plugin_settings_describe, + commands::plugin_settings_submit, + commands::plugin_settings_cancel, + commands::plugin_playtime_inventory, + commands::plugin_playtime_set_accounting, + commands::plugin_update_preferences, + commands::plugin_update_available, + commands::plugin_update_set_periodic_checks, + commands::plugin_update_check, + commands::plugin_update_review, + commands::plugin_rollback_available, + commands::plugin_rollback_review, + commands::plugin_update_retrust_publisher, + commands::plugin_rollback_approve, + commands::plugin_update_approve, + commands::plugin_update_decline, + commands::plugin_confirmation_answer, + commands::plugin_folder_selection_answer, + commands::plugin_folder_approval_answer, + commands::plugin_runtime_selection_answer, + commands::plugin_folder_approvals, + commands::plugin_folder_revoke, + commands::plugin_folder_change, + commands::plugin_library_root_set_watching, + commands::plugin_runtime_approvals, + commands::plugin_runtime_revoke, + commands::plugin_shared_resource_reviews, + commands::plugin_shared_resource_accept, + commands::plugin_shared_resource_revoke, + commands::plugin_remembered_confirmations, + commands::plugin_revoke_confirmation, commands::provider_sign_in, commands::provider_focus_sign_in, commands::provider_cancel_sign_in, commands::provider_sign_out, commands::provider_check, commands::plugin_stop, + commands::custom_launch_ids, + commands::custom_launch_stop, commands::plugin_start, commands::achievement_list, commands::open_achievements_page, @@ -459,6 +758,7 @@ fn main() -> Result<(), Box> { commands::ports_pick_parent, commands::ports_pick_supplied, commands::ports_install, + commands::ports_dismiss_plugin_setup, commands::ports_cancel, commands::ports_mark_seen, commands::ports_set_preferences, @@ -564,7 +864,10 @@ fn main() -> Result<(), Box> { eng_for_setup.start(); if let ipc::Message::AuthCallback { url } = incoming { - eng_for_setup.dispatch(Input::CallbackReceived(url)); + let engine = eng_for_setup.clone(); + tauri::async_runtime::spawn(async move { + engine.dispatch_on_worker(Input::CallbackReceived(url)).await; + }); } // Single-instance IPC listener @@ -573,7 +876,7 @@ fn main() -> Result<(), Box> { tauri::async_runtime::spawn(async move { while let Some(msg) = owner_messages.recv().await { if let ipc::Message::AuthCallback { url } = msg { - eng_for_ipc.dispatch(Input::CallbackReceived(url)); + eng_for_ipc.dispatch_on_worker(Input::CallbackReceived(url)).await; } let _ = win_for_ipc.unminimize(); let _ = win_for_ipc.show(); @@ -593,7 +896,7 @@ fn main() -> Result<(), Box> { let mut interval = tokio::time::interval(Duration::from_secs(1)); loop { interval.tick().await; - eng_for_ticker.dispatch(Input::Tick); + eng_for_ticker.dispatch_on_worker(Input::Tick).await; eng_for_ticker.maintenance(); let title = eng_for_ticker.running_title().unwrap_or_default(); diff --git a/crates/app/src/plugin_host.rs b/crates/app/src/plugin_host.rs index 9594e558d..bcb383dd9 100644 --- a/crates/app/src/plugin_host.rs +++ b/crates/app/src/plugin_host.rs @@ -16,22 +16,87 @@ use std::io; use tokio::sync::oneshot; use tonic::{Request, Response, Status, transport::Server}; +pub mod bundles; +pub mod cleanup; +pub mod compatibility; +pub mod confirmations; +pub mod file_approvals; +pub mod files; +pub mod fingerprints; +pub mod grants; +pub mod intents; +pub mod jobs; +pub mod launch_plan; +pub mod launch_supervisor; +pub mod library; pub mod login; +pub mod managed_packages; +pub mod migration; +pub mod namespace; +pub mod network; +pub mod notifications; +pub mod package; pub mod process; +pub mod profile; pub mod provider; +pub mod publisher_trust; +pub mod resource_leases; +pub mod resources; +pub mod retention; pub mod runtime; +pub mod runtime_access; +pub mod runtime_approvals; +pub mod saves; pub mod services; +pub mod shared_data; +pub mod shared_pool; +pub mod shared_resources; +pub mod sharing_policy; +pub mod startup; +pub mod storage; mod transport; +pub mod updates; // Generated by build.rs from `plugins/*.toml` and the login policies those files reference. include!(concat!(env!("OUT_DIR"), "/plugin_descriptors.rs")); -/// Read-only inventory of the bundled provider executables. +/// One component of an installed bundle as the inventory reports it. +/// +/// A bundle is one entry in the inventory, but each component keeps its own identity, status and +/// lifecycle. This is the display projection of a component; it carries no grants and never +/// replaces the component's own [`PluginInfo`] facts in the registry. +#[derive(Clone, Debug, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PluginBundleComponent { + pub plugin_id: String, + /// `provider` or `extension`. + pub plugin_kind: String, + pub name: String, + pub version: String, + /// Component status: `installed`, `unavailable`, `incompatible`, `missing` or `failed`. + pub status: String, + pub session: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub enabled: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub runtime_available: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub publisher_fingerprint: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub compatibility_details: Option, + #[serde(skip_serializing_if = "Vec::is_empty")] + pub native_access: Vec, +} + +/// Read-only inventory of official provider executables and installed community packages. #[derive(Clone, Debug, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct PluginInfo { pub provider_id: String, pub plugin_id: String, + /// Package execution kind from the verified manifest; bundled plugins are providers and an + /// aggregated bundle entry is `bundle`. + pub plugin_kind: String, pub name: String, /// The version declared by the trusted descriptor, or the build's package version. pub version: String, @@ -40,6 +105,35 @@ pub struct PluginInfo { pub capabilities: Vec, pub session: String, pub native_access: Vec, + #[serde(skip_serializing_if = "Option::is_none")] + pub enabled: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub runtime_available: Option, + /// The pinned publisher of a third-party plugin; `None` for the bundled ones. The settings + /// use it, with `plugin_id`, to find what the user allowed this plugin to start. An aggregated + /// bundle entry leaves it unset so bundle-wide actions never run as a single component. + #[serde(skip_serializing_if = "Option::is_none")] + pub publisher_fingerprint: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub compatibility_details: Option, + /// The bundle this entry belongs to; absent for a standalone package or an official plugin. + #[serde(skip_serializing_if = "Option::is_none")] + pub bundle_id: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub bundle_name: Option, + /// The bundle's distribution version, independent of each component's package version. + #[serde(skip_serializing_if = "Option::is_none")] + pub bundle_version: Option, + /// The component kind when the entry is a single installed component of a bundle. + #[serde(skip_serializing_if = "Option::is_none")] + pub bundle_component_kind: Option, + /// The bundle's pinned publisher fingerprint. Set only on the aggregated bundle entry, so the + /// row can show the publisher without offering single-component management. + #[serde(skip_serializing_if = "Option::is_none")] + pub bundle_publisher_fingerprint: Option, + /// Every component of the bundle and its current status, in bundle-manifest order. + #[serde(skip_serializing_if = "Option::is_none")] + pub bundle_components: Option>, } /// Resolving the current executable and checking sibling files touches disk; @@ -68,6 +162,7 @@ fn inventory_at( PluginInfo { provider_id: plugin.provider_id.clone(), plugin_id: plugin.plugin_id.clone(), + plugin_kind: "provider".to_owned(), name: plugin.name.clone(), version: plugin.version.clone(), source: "official".to_owned(), @@ -80,6 +175,16 @@ fn inventory_at( capabilities: plugin.capabilities.clone(), session: if connected { "active" } else { "stopped" }.into(), native_access: plugin.native_access.clone(), + enabled: None, + runtime_available: None, + publisher_fingerprint: None, + compatibility_details: None, + bundle_id: None, + bundle_name: None, + bundle_version: None, + bundle_component_kind: None, + bundle_publisher_fingerprint: None, + bundle_components: None, } }) .collect() @@ -487,6 +592,47 @@ pub fn backends(platform: Platform) -> Vec, + /// Shared published datasets; all provider sessions use the same broker. + pub data_broker: Arc, + /// Host-owned durable public pool; disabled until the host supplies its data folder. + pub shared_pool: Arc, + /// The library projection plugins read; the engine keeps it current. + pub library: Arc, + /// The plugins' private key/value storage. + pub storage: Arc, + /// File approvals, handles and the host folders no plugin may reach. + pub files: Arc, + /// Approved origins and limits for plugin network fetches. + pub network: Arc, + /// The notifications plugins ask Core to show. + pub notifications: Arc, + /// The long operations plugins started; each belongs to the plugin that started it. + pub jobs: jobs::Jobs, + /// What the user wanted to start, and the dialog that asks for it. + pub intents: Arc, + /// The grants that let a plugin use another plugin's save profiles (provisional). + pub saves: Arc, + /// The content fingerprints of approved places. + pub fingerprints: Arc, + /// Host-owned coordinator shared with supervised launches and backup/restore. + pub leases: Arc, + /// Platform process inspection; `None` makes external-use checks fail closed. + pub processes: Option>, +} + +impl PluginApi { + /// Connects the account-bound permission store to the host's resource adapters. + pub fn set_state_layout(&self, layout: profile::PluginStateLayout) { + self.providers.set_state_layout(layout.clone()); + self.providers.set_shared_pool(self.shared_pool.clone()); + self.network + .set_scopes(Arc::new(network::PersistedOriginScopes { + profiles: self.providers.profiles(), + layout, + })); + } } const MAX_CONNECTIONS: usize = 16; @@ -497,6 +643,10 @@ const MAX_ACHIEVEMENT_ICON_HOSTS: usize = 16; #[tonic::async_trait] impl plugin_host_server::PluginHost for PluginApi { + type WatchPermissionChangesStream = std::pin::Pin< + Box> + Send + 'static>, + >; + async fn open_session( &self, request: Request, @@ -514,10 +664,167 @@ impl plugin_host_server::PluginHost for PluginApi { "discovery results use the provider operation stream", )) } + + async fn describe_api( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + self.providers + .effective_permissions(&request.session_id, &request.session_credential)?; + Ok(Response::new(DescribeApiReply { + api_major: gamenode_plugin_protocol::API_MAJOR, + api_minor: gamenode_plugin_protocol::API_MINOR, + support_window: Some(SupportWindow { + minimum_api_minor: gamenode_plugin_protocol::MIN_API_MINOR, + maximum_api_minor: gamenode_plugin_protocol::API_MINOR, + support_ends_at: None, + policy: "supported by this GameNode build".into(), + }), + features: vec![ + ApiFeature { + id: capability::FEATURE_API_METADATA.into(), + introduced_minor: capability::THIRD_PARTY_API_MINOR, + permissions: vec![], + optional: true, + availability: "supported".into(), + }, + ApiFeature { + id: capability::FEATURE_PERMISSION_WATCH.into(), + introduced_minor: capability::THIRD_PARTY_API_MINOR, + permissions: vec![], + optional: true, + availability: "supported".into(), + }, + ApiFeature { + id: capability::FEATURE_EXTENSION_SESSION.into(), + introduced_minor: capability::THIRD_PARTY_API_MINOR, + permissions: vec![], + optional: true, + availability: "supported".into(), + }, + ], + methods: vec![ + ApiMethod { + service: "PluginHost".into(), + method: "DescribeApi".into(), + introduced_minor: capability::THIRD_PARTY_API_MINOR, + permissions: vec![], + ownership: "session".into(), + max_page_size: 0, + quota_bytes: 0, + idempotent: true, + }, + ApiMethod { + service: "PluginHost".into(), + method: "GetPermissions".into(), + introduced_minor: capability::THIRD_PARTY_API_MINOR, + permissions: vec![], + ownership: "authenticated plugin".into(), + max_page_size: 0, + quota_bytes: 0, + idempotent: true, + }, + ApiMethod { + service: "PluginHost".into(), + method: "WatchPermissionChanges".into(), + introduced_minor: capability::THIRD_PARTY_API_MINOR, + permissions: vec![], + ownership: "authenticated plugin".into(), + max_page_size: 0, + quota_bytes: 0, + idempotent: true, + }, + ] + .into_iter() + .chain( + resources::SERVED + .iter() + .map(|served| ("ResourceHost", served)) + .chain( + resources::SAVES_SERVED + .iter() + .map(|served| ("Saves", served)), + ) + .chain( + resources::LOCATIONS_SERVED + .iter() + .map(|served| ("Locations", served)), + ) + .chain( + resources::DIAGNOSTICS_SERVED + .iter() + .map(|served| ("StorageDiagnostics", served)), + ) + .chain( + resources::COMPUTER_SERVED + .iter() + .map(|served| ("Computer", served)), + ) + .chain( + resources::PRESENCE_SERVED + .iter() + .map(|served| ("GamePresence", served)), + ) + .chain( + resources::PERFORMANCE_SERVED + .iter() + .map(|served| ("GamePerformance", served)), + ) + .map(|(service, served)| ApiMethod { + service: service.into(), + method: served.method.into(), + introduced_minor: capability::THIRD_PARTY_API_MINOR, + // The jobs methods need the permission of the operation that made the job. + // Comma-separated when any one of several permissions will do. + permissions: served + .permission + .split(',') + .filter(|permission| !permission.is_empty()) + .map(Into::into) + .collect(), + ownership: served.ownership.into(), + max_page_size: if served.paged { + library::MAX_PAGE_SIZE as u32 + } else { + 0 + }, + quota_bytes: 0, + idempotent: true, + }), + ) + .collect(), + })) + } + + async fn get_permissions( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + let (revision, grants) = self + .providers + .effective_permissions(&request.session_id, &request.session_credential)?; + Ok(Response::new(GetPermissionsReply { revision, grants })) + } + + async fn watch_permission_changes( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + let stream = self.providers.watch_permissions( + &request.session_id, + &request.session_credential, + request.after_revision, + )?; + Ok(Response::new(Box::pin(stream))) + } } pub struct PluginApiServer { path: PathBuf, + resource_api: Arc, shutdown: Option>, task: tokio::task::JoinHandle<()>, } @@ -580,11 +887,55 @@ impl PluginApiServer { .buffer_unordered(MAX_CONNECTIONS) .filter_map(|item| async move { item }); + let resource_api = Arc::new( + resources::ResourceApi::new( + api.providers.clone(), + api.library.clone(), + api.storage.clone(), + api.files.clone(), + api.network.clone(), + api.notifications.clone(), + api.jobs.clone(), + api.intents.clone(), + api.saves.clone(), + api.fingerprints.clone(), + api.leases.clone(), + api.processes.clone(), + ) + .with_shared_data(api.data_broker.clone(), api.shared_policies.clone()) + .with_shared_pool(api.shared_pool.clone()), + ); + let service_resource_api = resource_api.clone(); let (shutdown_tx, shutdown_rx) = oneshot::channel(); let task = runtime.spawn(async move { let provider = provider_host_server::ProviderHostServer::new(api.providers.clone()) .max_decoding_message_size(MAX_MESSAGE_BYTES) .max_encoding_message_size(MAX_MESSAGE_BYTES); + let resource_api = (*service_resource_api).clone(); + let _root_monitoring = resource_api.monitor_library_roots(); + let saves = saves_server::SavesServer::new(resource_api.clone()) + .max_decoding_message_size(MAX_MESSAGE_BYTES) + .max_encoding_message_size(MAX_MESSAGE_BYTES); + let locations = locations_server::LocationsServer::new(resource_api.clone()) + .max_decoding_message_size(MAX_MESSAGE_BYTES) + .max_encoding_message_size(MAX_MESSAGE_BYTES); + let diagnostics = + storage_diagnostics_server::StorageDiagnosticsServer::new(resource_api.clone()) + .max_decoding_message_size(MAX_MESSAGE_BYTES) + .max_encoding_message_size(MAX_MESSAGE_BYTES); + let computer = computer_server::ComputerServer::new(resource_api.clone()) + .max_decoding_message_size(MAX_MESSAGE_BYTES) + .max_encoding_message_size(MAX_MESSAGE_BYTES); + let presence = game_presence_server::GamePresenceServer::new(resource_api.clone()) + .max_decoding_message_size(MAX_MESSAGE_BYTES) + .max_encoding_message_size(MAX_MESSAGE_BYTES); + let performance = + game_performance_server::GamePerformanceServer::new(resource_api.clone()) + .max_decoding_message_size(MAX_MESSAGE_BYTES) + .max_encoding_message_size(MAX_MESSAGE_BYTES); + let resources = resource_host_server::ResourceHostServer::new(resource_api) + .max_decoding_message_size(MAX_MESSAGE_BYTES) + .max_encoding_message_size(MAX_MESSAGE_BYTES); let host = plugin_host_server::PluginHostServer::new(api) .max_decoding_message_size(MAX_MESSAGE_BYTES) .max_encoding_message_size(MAX_MESSAGE_BYTES); @@ -593,6 +944,13 @@ impl PluginApiServer { .max_concurrent_streams(8) .add_service(host) .add_service(provider) + .add_service(resources) + .add_service(saves) + .add_service(locations) + .add_service(diagnostics) + .add_service(computer) + .add_service(presence) + .add_service(performance) .serve_with_incoming_shutdown(incoming, async move { let _ = shutdown_rx.await; }) @@ -603,6 +961,7 @@ impl PluginApiServer { }); Ok(Self { path, + resource_api, shutdown: Some(shutdown_tx), task, }) @@ -651,11 +1010,55 @@ impl PluginApiServer { } }, ); + let resource_api = Arc::new( + resources::ResourceApi::new( + api.providers.clone(), + api.library.clone(), + api.storage.clone(), + api.files.clone(), + api.network.clone(), + api.notifications.clone(), + api.jobs.clone(), + api.intents.clone(), + api.saves.clone(), + api.fingerprints.clone(), + api.leases.clone(), + api.processes.clone(), + ) + .with_shared_data(api.data_broker.clone(), api.shared_policies.clone()) + .with_shared_pool(api.shared_pool.clone()), + ); + let service_resource_api = resource_api.clone(); let (shutdown, stopped) = oneshot::channel(); let task = runtime.spawn(async move { let provider = provider_host_server::ProviderHostServer::new(api.providers.clone()) .max_decoding_message_size(MAX_MESSAGE_BYTES) .max_encoding_message_size(MAX_MESSAGE_BYTES); + let resource_api = (*service_resource_api).clone(); + let _root_monitoring = resource_api.monitor_library_roots(); + let saves = saves_server::SavesServer::new(resource_api.clone()) + .max_decoding_message_size(MAX_MESSAGE_BYTES) + .max_encoding_message_size(MAX_MESSAGE_BYTES); + let locations = locations_server::LocationsServer::new(resource_api.clone()) + .max_decoding_message_size(MAX_MESSAGE_BYTES) + .max_encoding_message_size(MAX_MESSAGE_BYTES); + let diagnostics = + storage_diagnostics_server::StorageDiagnosticsServer::new(resource_api.clone()) + .max_decoding_message_size(MAX_MESSAGE_BYTES) + .max_encoding_message_size(MAX_MESSAGE_BYTES); + let computer = computer_server::ComputerServer::new(resource_api.clone()) + .max_decoding_message_size(MAX_MESSAGE_BYTES) + .max_encoding_message_size(MAX_MESSAGE_BYTES); + let presence = game_presence_server::GamePresenceServer::new(resource_api.clone()) + .max_decoding_message_size(MAX_MESSAGE_BYTES) + .max_encoding_message_size(MAX_MESSAGE_BYTES); + let performance = + game_performance_server::GamePerformanceServer::new(resource_api.clone()) + .max_decoding_message_size(MAX_MESSAGE_BYTES) + .max_encoding_message_size(MAX_MESSAGE_BYTES); + let resources = resource_host_server::ResourceHostServer::new(resource_api) + .max_decoding_message_size(MAX_MESSAGE_BYTES) + .max_encoding_message_size(MAX_MESSAGE_BYTES); let host = plugin_host_server::PluginHostServer::new(api) .max_decoding_message_size(MAX_MESSAGE_BYTES) .max_encoding_message_size(MAX_MESSAGE_BYTES); @@ -664,6 +1067,13 @@ impl PluginApiServer { .max_concurrent_streams(8) .add_service(host) .add_service(provider) + .add_service(resources) + .add_service(saves) + .add_service(locations) + .add_service(diagnostics) + .add_service(computer) + .add_service(presence) + .add_service(performance) .serve_with_incoming_shutdown(incoming, async { let _ = stopped.await; }) @@ -674,6 +1084,7 @@ impl PluginApiServer { }); Ok(Self { path, + resource_api, shutdown: Some(shutdown), task, }) @@ -685,6 +1096,10 @@ impl PluginApiServer { &self.path } + pub fn resource_api(&self) -> Arc { + self.resource_api.clone() + } + pub async fn shutdown(mut self) { if let Some(shutdown) = self.shutdown.take() { let _ = shutdown.send(()); diff --git a/crates/app/src/plugin_host/bundles.rs b/crates/app/src/plugin_host/bundles.rs new file mode 100644 index 000000000..74c4c3580 --- /dev/null +++ b/crates/app/src/plugin_host/bundles.rs @@ -0,0 +1,6134 @@ +//! Per-component inspection and staged installation of a verified bundle. +//! +//! A bundle is only a distribution envelope. Every component is staged through the ordinary +//! bounded package extractor and evaluated with the same signature, manifest and compatibility +//! code a standalone import uses, so a component is never trusted merely because the bundle +//! verified. Installation re-stages the reviewed archive, verifies it again and compares every +//! component hash with the review before the registry changes, so the reviewed bytes are the +//! installed bytes. +//! +//! The two failure modes stay separate: +//! +//! - A structural failure (bad envelope, corrupt component archive, signature failure, invalid +//! manifest) rejects the whole bundle: [`inspect_bundle_candidate`] returns an error and no +//! component report, and [`install_bundle_candidate`] leaves no component and no mapping. +//! - A component that is only incompatible with the current platform or API is reported as +//! [`BundleComponentAvailability::Unavailable`] while compatible siblings remain available. +//! Installed, that component is disabled; the bundle is not rejected. +//! +//! Duplicate identities are publisher-checked. An active component already installed at the +//! reviewed version under the bundle publisher's key is adopted into the mapping without being +//! reinstalled, and rollback never removes it. An active package that does not verify under that +//! key, or a plugin already owned by another bundle, aborts the whole bundle as a conflict before +//! any registry write; an existing installation is never silently overwritten. +//! +//! Removal is the exact inverse of the mapping: every component with an active package is stopped +//! with the ordinary bounded grace, then the recorded `package_version` of each component is +//! deleted, and finally the mapping row of every component whose package is actually gone. Other +//! installed versions of the same plugin id, grants and library history are never touched. When one +//! component cannot be deleted, its mapping row stays so the uninstall can be retried, while the +//! rows of the components that were removed disappear: a partial removal never leaves a mapping +//! that names a package which no longer exists. + +use std::{ + fs, + future::Future, + io, + path::{Path, PathBuf}, + pin::Pin, +}; + +use gamenode_platform::{ + plugin_bundle_db::{BundleComponentRecord, BundleRecord, SqlitePluginBundleStore}, + plugin_bundles::{BundleError, VerifiedBundle, VerifiedBundleComponent, stage_bundle_archive}, + plugin_environment::{EmulationPolicy, PluginEnvironment}, + plugin_packages::{stage_package_archive, verify_package_directory}, + plugin_registry::{InstallSignedError, InstalledPluginVersion, PluginPackageRegistry}, + plugin_storage::{archive_namespace, namespace_dir}, +}; +use thiserror::Error; + +use super::{ + grants::PluginIdentity, + managed_packages::{ + PackageCandidateReport, PackageCompatibilityReview, PackageLifecycleError, + inspect_staged_package, inspect_staged_package_blocking, lock_publisher_identity, + }, + package::{Manifest, PluginKind}, + process::ProviderProcesses, + profile::{PluginProfiles, PluginStateLayout}, + publisher_trust::key_fingerprint, + retention::{DataRetention, DurableRetentionOutcome, DurableRetentionSink}, +}; + +/// Bundle-level identity shown once for the whole review. +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct BundleIdentity { + pub id: String, + pub name: String, + pub version: String, + pub publisher_key_id: String, + pub publisher_fingerprint: String, +} + +/// Whether one component can be selected for this execution environment. +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", tag = "status")] +pub enum BundleComponentAvailability { + Available, + /// Platform or API incompatible. The component is reported, not installed as usable, and + /// does not block its siblings. + Unavailable { + reason: BundleUnavailabilityReason, + }, +} + +/// The compatibility evaluator's cause for an unavailable component. +#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum BundleUnavailabilityReason { + /// No declared target matched the detected OS, architecture, ABI, libc or emulation state. + NoCompatibleTarget, + /// More than one declared target matched, so no target is selected implicitly. + AmbiguousTarget, +} + +/// One component's verified identity, compatibility verdict and existing review details. +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct BundleComponentInspection { + pub plugin_id: String, + pub kind: String, + pub version: String, + /// Package-relative path inside the bundle, e.g. `components/provider.gnplugin`. + pub archive_path: String, + /// Lowercase SHA-256 of the exact component archive bytes declared by the bundle. + pub sha256: String, + pub availability: BundleComponentAvailability, + pub compatibility: PackageCompatibilityReview, +} + +/// The complete per-component inspection of one bundle. +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct BundleCandidateReport { + pub bundle: BundleIdentity, + pub components: Vec, +} + +#[derive(Debug, Error)] +pub enum BundleInspectionError { + #[error("bundle verification failed: {0}")] + Bundle(#[from] BundleError), + #[error("bundle inspection staging failed: {0}")] + Staging(String), + /// Structural: the component cannot be installed at all, so the bundle is rejected. + #[error("bundle component {plugin_id} failed package validation: {error}")] + Component { plugin_id: String, error: String }, + #[error("bundle component {plugin_id} does not match the verified bundle manifest")] + ComponentIdentityMismatch { plugin_id: String }, + #[error("bundle inspection worker failed")] + WorkerFailed, +} + +/// The verified per-component data that only the import review needs: the public inspection plus +/// the ordinary staged-package report the shared review builder reads its manifest from. +#[derive(Clone, Debug)] +pub(crate) struct BundleReviewComponent { + pub inspection: BundleComponentInspection, + pub report: PackageCandidateReport, +} + +/// A bundle staged for import review. The publisher key is the authority every component +/// verified under, so the review pins one fingerprint for the whole bundle. +#[derive(Clone, Debug)] +pub(crate) struct BundleReviewCandidate { + pub bundle: BundleIdentity, + pub publisher_key: [u8; 32], + pub components: Vec, +} + +/// Verify a bundle archive, stage every component through the bounded package extractor and run +/// the ordinary candidate inspection on each one. No package code is executed and all file I/O +/// runs on blocking workers; the private staging directory is removed before this returns. +pub async fn inspect_bundle_candidate( + archive_path: impl AsRef, + emulation_policy: EmulationPolicy, +) -> Result { + let candidate = inspect_bundle_review(archive_path, emulation_policy).await?; + Ok(BundleCandidateReport { + bundle: candidate.bundle, + components: candidate + .components + .into_iter() + .map(|component| component.inspection) + .collect(), + }) +} + +/// The same staged, verified inspection as [`inspect_bundle_candidate`], keeping each component's +/// package report so the import review can reuse the standalone per-package review builder. +pub(crate) async fn inspect_bundle_review( + archive_path: impl AsRef, + emulation_policy: EmulationPolicy, +) -> Result { + let archive_path = archive_path.as_ref().to_owned(); + let work = tokio::task::spawn_blocking(BundleWorkDir::create) + .await + .map_err(|_| BundleInspectionError::WorkerFailed)? + .map_err(|error| BundleInspectionError::Staging(error.to_string()))?; + let staging_root = work.path.clone(); + let verified = + tokio::task::spawn_blocking(move || stage_bundle_archive(&archive_path, &staging_root)) + .await + .map_err(|_| BundleInspectionError::WorkerFailed)??; + let publisher_key = verified.manifest.publisher_key()?; + let bundle = BundleIdentity { + id: verified.manifest.id.clone(), + name: verified.manifest.name.clone(), + version: verified.manifest.version.clone(), + publisher_key_id: verified.manifest.publisher.key_id.clone(), + publisher_fingerprint: key_fingerprint(&publisher_key), + }; + + let mut components = Vec::with_capacity(verified.components.len()); + for (index, component) in verified.components.iter().enumerate() { + let archive = work.path.join(&component.path); + let package_root = work.path.join("packages").join(index.to_string()); + let plugin_id = component.plugin_id.clone(); + let package_for_worker = package_root.clone(); + tokio::task::spawn_blocking(move || { + stage_package_archive(&archive, &package_for_worker, &publisher_key) + }) + .await + .map_err(|_| BundleInspectionError::WorkerFailed)? + .map_err(|error| BundleInspectionError::Component { + plugin_id: plugin_id.clone(), + error: error_chain(&error), + })?; + + let report = inspect_staged_package(&package_root, publisher_key, emulation_policy) + .await + .map_err(|error| BundleInspectionError::Component { + plugin_id: component.plugin_id.clone(), + error: error.to_string(), + })?; + if report.manifest.id != component.plugin_id + || report.manifest.version != component.version + || !kind_matches(report.manifest.kind, &component.kind) + { + return Err(BundleInspectionError::ComponentIdentityMismatch { + plugin_id: component.plugin_id.clone(), + }); + } + components.push(BundleReviewComponent { + inspection: BundleComponentInspection { + plugin_id: report.manifest.id.clone(), + kind: component.kind.clone(), + version: report.manifest.version.clone(), + archive_path: component.path.clone(), + sha256: component.sha256.clone(), + availability: availability(&report), + compatibility: report.compatibility_review(), + }, + report, + }); + } + + Ok(BundleReviewCandidate { + bundle, + publisher_key, + components, + }) +} + +/// One component whose package this bundle install wrote into the registry. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct InstalledBundleComponent { + pub plugin_id: String, + pub kind: String, + pub version: String, + pub package_path: PathBuf, + /// False when the component was installed for its identity but cannot run on this host. + pub active: bool, +} + +/// The recorded bundle mapping plus what the install did to each component package. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct InstalledBundle { + pub bundle: BundleRecord, + pub components: Vec, +} + +#[derive(Debug, Error)] +pub enum BundleInstallError { + #[error("bundle verification failed: {0}")] + Bundle(#[from] BundleError), + #[error("bundle install staging failed: {0}")] + Staging(String), + /// The archive on disk is not the bundle the user reviewed; nothing was installed. + #[error("the bundle archive no longer matches the reviewed bundle: {0}")] + ChangedSinceReview(String), + /// A component's active installation exists but does not verify under the bundle publisher's + /// key. Adoption is publisher-checked, so the bundle is rejected before any registry write + /// instead of replacing the existing package. + #[error( + "plugin {plugin_id} is already installed by a different or unverifiable publisher; remove it before importing this bundle" + )] + PublisherConflict { plugin_id: String }, + /// A component is already owned by a bundle mapping, so claiming it would silently move it + /// between bundles. + #[error( + "plugin {plugin_id} already belongs to bundle {bundle_id}; remove that bundle before importing this one" + )] + BundleConflict { + plugin_id: String, + bundle_id: String, + }, + /// Structural: the component could not be installed, so every component of this bundle was + /// rolled back. + #[error("bundle component {plugin_id} failed to install: {error}")] + Component { plugin_id: String, error: String }, + #[error("the bundle mapping could not be recorded: {0}")] + Mapping(String), + /// A failure was reported and undoing the partial install did not fully succeed. + #[error("{cause}; rollback was incomplete: {problems}")] + Rollback { cause: String, problems: String }, + #[error("execution environment detection failed: {0}")] + Environment(String), + #[error("bundle install worker failed")] + WorkerFailed, +} + +/// Install every component of a reviewed bundle, then record the bundle mapping. +/// +/// `reviewed` must be the report [`inspect_bundle_candidate`] returned for `archive_path`. The +/// archive is verified and every component hash is compared with that report before the registry +/// changes, so the reviewed bytes are the installed bytes; a changed archive fails without +/// touching the registry. Each component is staged through the bounded package extractor and +/// installed through the ordinary signed registry path. No package code is executed. +/// +/// `installed_at` is the caller's clock (Unix seconds); the store never substitutes its own. +/// Before anything is written, each component's active installation is verified with the bundle +/// publisher's key: a component already active under that key and version is adopted into the +/// mapping without being reinstalled, while an active package under another publisher — or a +/// plugin already mapped to a bundle — is an explicit conflict and leaves the registry untouched. +/// Every step runs on one blocking worker, and a failure removes the component versions this call +/// created (restoring any previous active version) without touching adopted components, and leaves +/// no bundle mapping. +pub async fn install_bundle_candidate( + archive_path: impl AsRef, + reviewed: BundleCandidateReport, + registry: PluginPackageRegistry, + bundles: SqlitePluginBundleStore, + emulation_policy: EmulationPolicy, + installed_at: i64, +) -> Result { + let archive_path = archive_path.as_ref().to_owned(); + let environment = gamenode_platform::plugin_environment::detect() + .await + .map_err(BundleInstallError::Environment)?; + tokio::task::spawn_blocking(move || { + install_bundle_blocking( + archive_path, + &reviewed, + ®istry, + &bundles, + emulation_policy, + &environment, + installed_at, + ) + }) + .await + .map_err(|_| BundleInstallError::WorkerFailed)? +} + +/// A component this call published to the registry, or an existing installation it adopted, with +/// the state needed to undo only what this call created. +struct PendingComponent { + installed: InstalledPluginVersion, + kind: String, + /// Whether the component can be activated on this host. + available: bool, + /// The version that was active before this install, if any. + previous_active: Option, + /// True when the bundle claimed an existing active installation under the same publisher key. + /// An adopted component was not published by this call and must never be removed by rollback. + adopted: bool, +} + +fn install_bundle_blocking( + archive_path: PathBuf, + reviewed: &BundleCandidateReport, + registry: &PluginPackageRegistry, + bundles: &SqlitePluginBundleStore, + emulation_policy: EmulationPolicy, + environment: &PluginEnvironment, + installed_at: i64, +) -> Result { + let work = + BundleWorkDir::create().map_err(|error| BundleInstallError::Staging(error.to_string()))?; + let verified = stage_bundle_archive(&archive_path, &work.path)?; + confirm_reviewed_bundle(reviewed, &verified)?; + let publisher_key = verified.manifest.publisher_key()?; + + // Registry writes for one install are serialized against other imports and updates. + let _publisher = lock_publisher_identity(); + // Publisher and ownership checks happen before any component is published, so a conflict + // cannot leave an earlier component of the same bundle behind. + let adoptable = preflight_components(&verified, &publisher_key, registry, bundles)?; + let record = BundleRecord { + bundle_id: verified.manifest.id.clone(), + name: verified.manifest.name.clone(), + version: verified.manifest.version.clone(), + publisher_fingerprint: key_fingerprint(&publisher_key), + manifest_sha256: verified.manifest_sha256.clone(), + installed_at, + components: verified + .components + .iter() + .zip(&adoptable) + .map(|(component, adopted)| BundleComponentRecord { + plugin_id: component.plugin_id.clone(), + kind: component.kind.clone(), + component_sha256: component.sha256.clone(), + package_version: adopted.as_ref().map_or_else( + || component.version.clone(), + |installed| installed.version.clone(), + ), + }) + .collect(), + }; + + let mut pending = Vec::with_capacity(verified.components.len()); + let mut failure = None; + for (index, component) in verified.components.iter().enumerate() { + // An adopted component is already installed and active; claiming it must not reinstall, + // replace or (on a later failure) remove it. + if let Some(installed) = adoptable[index].clone() { + pending.push(PendingComponent { + installed, + kind: component.kind.clone(), + available: true, + previous_active: None, + adopted: true, + }); + continue; + } + match install_component( + &work.path, + index, + component, + &publisher_key, + registry, + emulation_policy, + environment, + ) { + Ok(installed) => pending.push(installed), + Err(error) => { + failure = Some(error); + break; + } + } + } + // Activate only after every package is published, so a failure leaves the previous pointer + // untouched and the whole install can be undone without a half-active bundle. + if failure.is_none() { + for component in &pending { + if component.adopted || !component.available { + continue; + } + if let Err(error) = + registry.set_active(&component.installed.plugin_id, &component.installed.version) + { + failure = Some(BundleInstallError::Component { + plugin_id: component.installed.plugin_id.clone(), + error: error.to_string(), + }); + break; + } + } + } + if failure.is_none() + && let Err(error) = bundles.record_bundle(&record) + { + failure = Some(mapping_failure(bundles, &verified, error.to_string())); + } + if let Some(error) = failure { + let problems = rollback_install(registry, &pending); + if !problems.is_empty() { + return Err(BundleInstallError::Rollback { + cause: error.to_string(), + problems: problems.join("; "), + }); + } + return Err(error); + } + Ok(InstalledBundle { + bundle: record, + components: pending + .into_iter() + .map(|component| InstalledBundleComponent { + plugin_id: component.installed.plugin_id, + kind: component.kind, + version: component.installed.version, + package_path: component.installed.package_path, + active: component.available, + }) + .collect(), + }) +} + +/// Decide, before any registry write, which components this install may adopt and which are +/// conflicts. +/// +/// A component whose active version is already installed and verifies with the bundle publisher's +/// key is adoptable only for the exact reviewed version; the bundle claims it into its mapping +/// instead of publishing an identical immutable version again. Any other active package that does +/// not verify with that key is a publisher conflict, and a plugin already owned by a bundle +/// mapping is an ownership conflict. Both abort the whole bundle with a typed error, leaving the +/// existing installation untouched. +fn preflight_components( + verified: &VerifiedBundle, + publisher_key: &[u8; 32], + registry: &PluginPackageRegistry, + bundles: &SqlitePluginBundleStore, +) -> Result>, BundleInstallError> { + let mut adoptable = Vec::with_capacity(verified.components.len()); + for component in &verified.components { + let plugin_id = component.plugin_id.clone(); + if let Some(mapped) = bundles + .bundle_for_plugin(&plugin_id) + .map_err(|error| BundleInstallError::Mapping(error.to_string()))? + { + return Err(BundleInstallError::BundleConflict { + plugin_id, + bundle_id: mapped.bundle_id, + }); + } + match registry.verify_active_package(&plugin_id, publisher_key) { + Ok(Some(installed)) if installed.version == component.version => { + adoptable.push(Some(installed)); + } + Ok(_) => adoptable.push(None), + // Integrity covers the publisher signature check: an active package that does not + // verify under this bundle's key is never replaced silently. + Err(InstallSignedError::Integrity(_)) => { + return Err(BundleInstallError::PublisherConflict { plugin_id }); + } + Err(error) => { + return Err(BundleInstallError::Component { + plugin_id, + error: error.to_string(), + }); + } + } + } + Ok(adoptable) +} + +/// A rejected mapping write is normally a duplicate bundle id; when a component was mapped to +/// another bundle after the preflight, report that ownership conflict instead of a generic store +/// failure. +fn mapping_failure( + bundles: &SqlitePluginBundleStore, + verified: &VerifiedBundle, + error: String, +) -> BundleInstallError { + for component in &verified.components { + if let Ok(Some(mapped)) = bundles.bundle_for_plugin(&component.plugin_id) { + return BundleInstallError::BundleConflict { + plugin_id: component.plugin_id.clone(), + bundle_id: mapped.bundle_id, + }; + } + } + BundleInstallError::Mapping(error) +} + +/// Stage, validate and publish one component without activating it. Activation is a separate +/// step so a component install can never leave a newly active package behind on failure. +fn install_component( + work_root: &Path, + index: usize, + component: &VerifiedBundleComponent, + publisher_key: &[u8; 32], + registry: &PluginPackageRegistry, + emulation_policy: EmulationPolicy, + environment: &PluginEnvironment, +) -> Result { + let plugin_id = component.plugin_id.clone(); + let failed = |error: String| BundleInstallError::Component { + plugin_id: plugin_id.clone(), + error, + }; + let archive = work_root.join(&component.path); + let package_root = work_root.join("packages").join(index.to_string()); + stage_package_archive(&archive, &package_root, publisher_key) + .map_err(|error| failed(error_chain(&error)))?; + let report = inspect_staged_package_blocking( + &package_root, + *publisher_key, + emulation_policy, + environment, + ) + .map_err(|error| failed(error.to_string()))?; + if report.manifest.id != component.plugin_id + || report.manifest.version != component.version + || !kind_matches(report.manifest.kind, &component.kind) + { + return Err(failed( + "the staged component identity does not match the bundle manifest".into(), + )); + } + let previous_active = registry + .active(&plugin_id) + .map_err(|error| failed(error.to_string()))? + .map(|installed| installed.version); + let already_published = registry + .versions(&plugin_id) + .map_err(|error| failed(error.to_string()))? + .iter() + .any(|installed| installed.version == component.version); + let entrypoint = report + .selected_target() + .ok() + .map(|target| target.target.entrypoint.clone()); + let installed = match &entrypoint { + Some(entrypoint) => registry.install_signed_with_entrypoint( + &plugin_id, + &component.version, + &package_root, + publisher_key, + entrypoint, + false, + ), + None => registry.install_signed( + &plugin_id, + &component.version, + &package_root, + publisher_key, + false, + ), + } + .map_err(|error| { + // A failure after the immutable version was published (for example during entrypoint + // preparation) must not leak a package this call created, and a cleanup failure must be + // reported rather than left for a later install to discover. + let mut text = error.to_string(); + if !already_published + && let Err(cleanup) = registry.remove_version(&plugin_id, &component.version) + { + text.push_str(&format!( + "; cleanup of the published version failed: {cleanup}" + )); + } + failed(text) + })?; + Ok(PendingComponent { + installed, + kind: component.kind.clone(), + available: entrypoint.is_some(), + previous_active, + adopted: false, + }) +} + +/// Undo the components this call published, newest first: removing a version also clears the +/// active pointer that names it, and any version that was active before is restored afterwards. +/// Adopted components were never published by this call, so they and their active pointer survive +/// any failure. +fn rollback_install(registry: &PluginPackageRegistry, pending: &[PendingComponent]) -> Vec { + let mut problems = Vec::new(); + for component in pending.iter().rev() { + if component.adopted { + continue; + } + let plugin_id = &component.installed.plugin_id; + let version = &component.installed.version; + if let Err(error) = registry.remove_version(plugin_id, version) { + problems.push(format!("remove {plugin_id} {version}: {error}")); + continue; + } + if let Some(previous) = &component.previous_active + && let Err(error) = registry.set_active(plugin_id, previous) + { + problems.push(format!("reactivate {plugin_id} {previous}: {error}")); + } + } + problems +} + +/// Account state needed to revalidate grants during a bundle update or rollback. Grants are per +/// profile and per component identity, so a bundle update intersects each component's existing +/// grants with its new manifest rather than carrying or widening them. When no profile is active +/// there is nothing to revalidate and activation never creates a grant. +#[derive(Clone)] +pub struct BundleGrantContext { + pub layout: PluginStateLayout, + pub profiles: std::sync::Arc, +} + +/// One component that changed during a bundle update or rollback. +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct UpdatedBundleComponent { + pub plugin_id: String, + pub kind: String, + pub previous_version: String, + pub version: String, + /// Whether the component was activated on this host after the swap. + pub active: bool, +} + +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct BundleUpdateOutcome { + pub bundle_id: String, + pub previous_version: String, + pub version: String, + pub components: Vec, +} + +#[derive(Debug, Error)] +pub enum BundleUpdateError { + #[error("bundle verification failed: {0}")] + Bundle(#[from] BundleError), + #[error("bundle update staging failed: {0}")] + Staging(String), + #[error("the bundle archive no longer matches the reviewed bundle: {0}")] + ChangedSinceReview(String), + #[error("bundle {bundle_id} is not installed")] + UnknownBundle { bundle_id: String }, + #[error("the bundle mapping could not be read: {0}")] + Mapping(String), + #[error("the reviewed bundle does not match the installed bundle identity")] + IdentityChanged, + #[error("the bundle publisher changed; a bundle update cannot replace its publisher")] + PublisherChanged, + #[error( + "the update changes which components this bundle owns; its component set must stay the same" + )] + ComponentSetChanged, + #[error("bundle component {plugin_id} could not be updated: {error}")] + Component { plugin_id: String, error: String }, + #[error("bundle component {plugin_id} could not be activated: {error}")] + Activation { plugin_id: String, error: String }, + #[error("a component's permission grants could not be revalidated: {0}")] + Grants(String), + #[error("{cause}; rollback was incomplete: {problems}")] + Rollback { cause: String, problems: String }, + #[error("execution environment detection failed: {0}")] + Environment(String), + #[error("bundle update worker failed")] + WorkerFailed, +} + +/// A staged component of one bundle update: the new package is installed (or was already installed +/// with the reviewed bytes) but not yet active. +struct UpdateComponentPlan { + plugin_id: String, + kind: String, + previous_version: String, + installed: InstalledPluginVersion, + previous_manifest: Manifest, + candidate_manifest: Manifest, + available: bool, + /// False when this call reused a version that already existed, which rollback must not remove. + created: bool, +} + +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct BundleRollbackOutcome { + pub bundle_id: String, + pub previous_version: String, + pub version: String, + pub components: Vec, +} + +#[derive(Debug, Error)] +pub enum BundleRollbackError { + #[error("bundle {bundle_id} is not installed")] + UnknownBundle { bundle_id: String }, + #[error("bundle {bundle_id} has no installed version {version} to roll back to")] + VersionUnavailable { bundle_id: String, version: String }, + #[error("the bundle mapping could not be read: {0}")] + Mapping(String), + #[error("bundle component {plugin_id} version {version} is no longer installed")] + ComponentMissing { plugin_id: String, version: String }, + #[error("bundle component {plugin_id} could not be restored: {error}")] + Component { plugin_id: String, error: String }, + #[error("a component's permission grants could not be revalidated: {0}")] + Grants(String), + #[error("{cause}; the previous active set could not be fully restored: {problems}")] + Restore { cause: String, problems: String }, + #[error("bundle rollback worker failed")] + WorkerFailed, +} + +/// Replace every component of one installed bundle with the reviewed component set, atomically. +/// +/// The archive is staged and re-verified against `reviewed` before the registry changes, every new +/// component package is installed but not activated, and only then does one blocking step activate +/// the whole set, revalidate each component's grants against its new manifest and write the new +/// mapping. If staging, installation, activation, grant revalidation or the mapping write fails, +/// the versions this call created are removed, the previous active pointers are restored and the +/// previous mapping remains current. A component version that is already installed is reused only +/// when its verified files equal the reviewed package. No package code is executed. +#[allow(clippy::too_many_arguments)] // The reviewed candidate, storage handles and policy context. +pub async fn apply_bundle_update( + archive_path: impl AsRef, + reviewed: BundleCandidateReport, + installed: BundleRecord, + registry: PluginPackageRegistry, + bundles: SqlitePluginBundleStore, + stopper: &dyn BundleComponentStopper, + grants: BundleGrantContext, + emulation_policy: EmulationPolicy, + installed_at: i64, +) -> Result { + let archive_path = archive_path.as_ref().to_owned(); + let environment = gamenode_platform::plugin_environment::detect() + .await + .map_err(BundleUpdateError::Environment)?; + let work = { + let archive_path = archive_path.clone(); + let reviewed = reviewed.clone(); + let installed = installed.clone(); + let registry = registry.clone(); + tokio::task::spawn_blocking(move || { + let work = BundleWorkDir::create() + .map_err(|error| BundleUpdateError::Staging(error.to_string()))?; + let verified = stage_bundle_archive(&archive_path, &work.path)?; + confirm_reviewed_bundle(&reviewed, &verified).map_err(|error| match error { + BundleInstallError::ChangedSinceReview(reason) => { + BundleUpdateError::ChangedSinceReview(reason) + } + other => BundleUpdateError::Staging(other.to_string()), + })?; + confirm_update_identity(&reviewed, &installed, &verified)?; + let publisher_key = verified.manifest.publisher_key()?; + let _publisher = lock_publisher_identity(); + let plans = prepare_update_components( + &work.path, + &verified, + &installed, + &publisher_key, + ®istry, + emulation_policy, + &environment, + )?; + Ok::<_, BundleUpdateError>((work, verified, publisher_key, plans)) + }) + .await + .map_err(|_| BundleUpdateError::WorkerFailed)?? + }; + let (work, verified, publisher_key, plans) = work; + + // Stop every component that is running at its recorded old version before the active pointer + // moves, so no supervised process keeps running against a package that is about to be replaced. + stop_components_at(&installed, ®istry, stopper).await?; + + let publisher_fingerprint = key_fingerprint(&publisher_key); + let record = BundleRecord { + bundle_id: verified.manifest.id.clone(), + name: verified.manifest.name.clone(), + version: verified.manifest.version.clone(), + publisher_fingerprint: publisher_fingerprint.clone(), + manifest_sha256: verified.manifest_sha256.clone(), + installed_at, + components: verified + .components + .iter() + .zip(&plans) + .map(|(component, plan)| BundleComponentRecord { + plugin_id: component.plugin_id.clone(), + kind: component.kind.clone(), + component_sha256: component.sha256.clone(), + package_version: plan.installed.version.clone(), + }) + .collect(), + }; + let previous_version = installed.version.clone(); + let bundle_id = record.bundle_id.clone(); + let version = record.version.clone(); + let outcome = tokio::task::spawn_blocking(move || { + finish_update( + bundle_id, + previous_version, + version, + record, + plans, + publisher_fingerprint, + ®istry, + &bundles, + &grants, + installed_at, + ) + }) + .await + .map_err(|_| BundleUpdateError::WorkerFailed)?; + drop(work); + outcome +} + +/// Confirm the candidate is the same bundle identity and publisher as the mapping being updated, +/// and that it keeps exactly the same component plugin ids and kinds. A bundle update is a version +/// swap, not a new product: adding, removing or re-kinding a component is an explicit error. +fn confirm_update_identity( + reviewed: &BundleCandidateReport, + installed: &BundleRecord, + verified: &VerifiedBundle, +) -> Result<(), BundleUpdateError> { + if verified.manifest.id != installed.bundle_id || reviewed.bundle.id != installed.bundle_id { + return Err(BundleUpdateError::IdentityChanged); + } + if key_fingerprint(&verified.manifest.publisher_key()?) != installed.publisher_fingerprint { + return Err(BundleUpdateError::PublisherChanged); + } + let mapped = installed + .components + .iter() + .map(|component| (component.plugin_id.as_str(), component.kind.as_str())) + .collect::>(); + let candidate = verified + .components + .iter() + .map(|component| (component.plugin_id.as_str(), component.kind.as_str())) + .collect::>(); + if mapped != candidate { + return Err(BundleUpdateError::ComponentSetChanged); + } + Ok(()) +} + +fn prepare_update_components( + work_root: &Path, + verified: &VerifiedBundle, + installed: &BundleRecord, + publisher_key: &[u8; 32], + registry: &PluginPackageRegistry, + emulation_policy: EmulationPolicy, + environment: &PluginEnvironment, +) -> Result, BundleUpdateError> { + let mut plans = Vec::with_capacity(verified.components.len()); + let mut created: Vec<(String, String)> = Vec::new(); + let result = (|| { + for (index, component) in verified.components.iter().enumerate() { + let previous = installed + .components + .iter() + .find(|mapped| mapped.plugin_id == component.plugin_id) + .ok_or(BundleUpdateError::ComponentSetChanged)?; + match prepare_update_component( + work_root, + index, + component, + &previous.package_version, + publisher_key, + registry, + emulation_policy, + environment, + ) { + Ok(plan) => { + if plan.created { + created.push((plan.plugin_id.clone(), plan.installed.version.clone())); + } + plans.push(plan); + } + Err(error) => return Err(error), + } + } + Ok(()) + })(); + if let Err(error) = result { + rollback_prepared(registry, &created); + return Err(error); + } + Ok(plans) +} + +#[allow(clippy::too_many_arguments)] +fn prepare_update_component( + work_root: &Path, + index: usize, + component: &VerifiedBundleComponent, + previous_version: &str, + publisher_key: &[u8; 32], + registry: &PluginPackageRegistry, + emulation_policy: EmulationPolicy, + environment: &PluginEnvironment, +) -> Result { + let plugin_id = component.plugin_id.clone(); + let failed = |error: String| BundleUpdateError::Component { + plugin_id: plugin_id.clone(), + error, + }; + let previous_installed = registry + .versions(&plugin_id) + .map_err(|error| failed(error.to_string()))? + .into_iter() + .find(|installed| installed.version == previous_version) + .ok_or_else(|| { + failed("the previously installed component version is missing".to_owned()) + })?; + let archive = work_root.join(&component.path); + let package_root = work_root.join("packages").join(index.to_string()); + stage_package_archive(&archive, &package_root, publisher_key) + .map_err(|error| failed(error_chain(&error)))?; + let report = inspect_staged_package_blocking( + &package_root, + *publisher_key, + emulation_policy, + environment, + ) + .map_err(|error| failed(error.to_string()))?; + if report.manifest.id != component.plugin_id + || report.manifest.version != component.version + || !kind_matches(report.manifest.kind, &component.kind) + { + return Err(failed( + "the staged component identity does not match the bundle manifest".into(), + )); + } + let previous = inspect_staged_package_blocking( + &previous_installed.package_path, + *publisher_key, + emulation_policy, + environment, + ) + .map_err(|error| { + failed(format!( + "the installed component no longer verifies: {error}" + )) + })?; + if previous.manifest.id != plugin_id || previous.manifest.version != previous_version { + return Err(failed( + "the installed component identity does not match the bundle mapping".into(), + )); + } + let existing = registry + .versions(&plugin_id) + .map_err(|error| failed(error.to_string()))? + .into_iter() + .find(|installed| installed.version == component.version); + let (installed, created) = match existing { + Some(existing) => { + same_package_files(&package_root, &existing.package_path, publisher_key) + .map_err(failed)?; + (existing, false) + } + None => { + let entrypoint = report + .selected_target() + .ok() + .map(|target| target.target.entrypoint.clone()); + let installed = match &entrypoint { + Some(entrypoint) => registry.install_signed_with_entrypoint( + &plugin_id, + &component.version, + &package_root, + publisher_key, + entrypoint, + false, + ), + None => registry.install_signed( + &plugin_id, + &component.version, + &package_root, + publisher_key, + false, + ), + } + .map_err(|error| { + let mut text = error.to_string(); + if let Err(cleanup) = registry.remove_version(&plugin_id, &component.version) { + text.push_str(&format!( + "; cleanup of the published version failed: {cleanup}" + )); + } + failed(text) + })?; + (installed, true) + } + }; + let available = report.selected_target().is_ok(); + Ok(UpdateComponentPlan { + plugin_id: component.plugin_id.clone(), + kind: component.kind.clone(), + previous_version: previous_version.to_owned(), + installed, + previous_manifest: previous.manifest, + candidate_manifest: report.manifest, + available, + created, + }) +} + +fn same_package_files(left: &Path, right: &Path, publisher_key: &[u8; 32]) -> Result<(), String> { + let left = verify_package_directory(left, publisher_key).map_err(|error| error.to_string())?; + let right = + verify_package_directory(right, publisher_key).map_err(|error| error.to_string())?; + if left.files.0 != right.files.0 { + return Err("an installed component version differs from the reviewed package".to_owned()); + } + Ok(()) +} + +fn rollback_prepared(registry: &PluginPackageRegistry, created: &[(String, String)]) { + for (plugin_id, version) in created.iter().rev() { + let _ = registry.remove_version(plugin_id, version); + } +} + +#[allow(clippy::too_many_arguments)] +fn finish_update( + bundle_id: String, + previous_version: String, + version: String, + record: BundleRecord, + plans: Vec, + publisher_fingerprint: String, + registry: &PluginPackageRegistry, + bundles: &SqlitePluginBundleStore, + grants: &BundleGrantContext, + installed_at: i64, +) -> Result { + let mut previous_active = Vec::with_capacity(plans.len()); + for plan in &plans { + previous_active.push(registry.active(&plan.plugin_id).map_err(|error| { + BundleUpdateError::Activation { + plugin_id: plan.plugin_id.clone(), + error: error.to_string(), + } + })?); + } + let result = (|| { + for plan in &plans { + if !plan.available { + continue; + } + registry + .set_active(&plan.plugin_id, &plan.installed.version) + .map_err(|error| BundleUpdateError::Activation { + plugin_id: plan.plugin_id.clone(), + error: error.to_string(), + })?; + } + revalidate_bundle_grants(&plans, grants, &publisher_fingerprint)?; + bundles + .update_bundle(&record, installed_at) + .map_err(|error| BundleUpdateError::Mapping(error.to_string()))?; + Ok(BundleUpdateOutcome { + bundle_id, + previous_version, + version, + components: plans + .iter() + .map(|plan| UpdatedBundleComponent { + plugin_id: plan.plugin_id.clone(), + kind: plan.kind.clone(), + previous_version: plan.previous_version.clone(), + version: plan.installed.version.clone(), + active: plan.available, + }) + .collect(), + }) + })(); + match result { + Ok(outcome) => Ok(outcome), + Err(error) => { + let problems = restore_previous_update(registry, &plans, &previous_active); + if problems.is_empty() { + Err(error) + } else { + Err(BundleUpdateError::Rollback { + cause: error.to_string(), + problems: problems.join("; "), + }) + } + } + } +} + +/// Intersect each component's stored grants with the reviewed manifest. Activation itself never +/// grants anything; narrowing can only remove a grant whose scope disappeared or widened. +fn revalidate_bundle_grants( + plans: &[UpdateComponentPlan], + grants: &BundleGrantContext, + publisher_fingerprint: &str, +) -> Result<(), BundleUpdateError> { + let Some(profile) = grants.profiles.current() else { + return Ok(()); + }; + let mut store = grants + .layout + .open_grants(&profile) + .map_err(|error| BundleUpdateError::Grants(error.to_string()))?; + for plan in plans { + let identity = PluginIdentity { + plugin_id: plan.plugin_id.clone(), + publisher_fingerprint: publisher_fingerprint.to_owned(), + profile_id: profile.profile_id().to_owned(), + }; + store + .intersect_with_selected_manifest( + &identity, + &plan.previous_manifest, + &plan.candidate_manifest, + ) + .map_err(|error| BundleUpdateError::Grants(error.to_string()))?; + } + Ok(()) +} + +fn restore_previous_update( + registry: &PluginPackageRegistry, + plans: &[UpdateComponentPlan], + previous_active: &[Option], +) -> Vec { + let mut problems = Vec::new(); + for (plan, previous) in plans.iter().zip(previous_active).rev() { + if plan.created + && let Err(error) = registry.remove_version(&plan.plugin_id, &plan.installed.version) + { + problems.push(format!( + "remove {} {}: {error}", + plan.plugin_id, plan.installed.version + )); + } + if let Some(previous) = previous + && let Err(error) = registry.set_active(&plan.plugin_id, &previous.version) + { + problems.push(format!( + "reactivate {} {}: {error}", + plan.plugin_id, previous.version + )); + } + } + problems +} + +/// Stop every component that is active at the version recorded by the bundle mapping. +async fn stop_components_at( + record: &BundleRecord, + registry: &PluginPackageRegistry, + stopper: &dyn BundleComponentStopper, +) -> Result<(), BundleUpdateError> { + for component in &record.components { + let registry = registry.clone(); + let plugin_id = component.plugin_id.clone(); + let version = component.package_version.clone(); + let active = tokio::task::spawn_blocking(move || { + registry + .active(&plugin_id) + .map(|installed| installed.is_some_and(|active| active.version == version)) + }) + .await + .map_err(|_| BundleUpdateError::WorkerFailed)? + .map_err(|error| BundleUpdateError::Activation { + plugin_id: component.plugin_id.clone(), + error: error.to_string(), + })?; + if active { + stopper.stop_component(&component.plugin_id).await; + } + } + Ok(()) +} + +/// Restore an archived bundle version: stop the components running at the current versions, +/// reactivate the archived versions that are still installed, revalidate each component's grants +/// against the archived manifest (never widening them) and make the archived mapping current. A +/// missing component version fails before anything changes; any later failure restores the +/// previously active pointers and leaves the current mapping in place. +#[allow(clippy::too_many_arguments)] // The archived mapping, storage handles and policy context. +pub async fn rollback_bundle_version( + bundle_id: impl Into, + version: impl Into, + registry: PluginPackageRegistry, + bundles: SqlitePluginBundleStore, + stopper: &dyn BundleComponentStopper, + grants: BundleGrantContext, + emulation_policy: EmulationPolicy, + archived_at: i64, +) -> Result { + let bundle_id = bundle_id.into(); + let version = version.into(); + let current = { + let store = bundles.clone(); + let lookup = bundle_id.clone(); + tokio::task::spawn_blocking(move || store.bundle(&lookup)) + .await + .map_err(|_| BundleRollbackError::WorkerFailed)? + .map_err(|error| BundleRollbackError::Mapping(error.to_string()))? + .ok_or_else(|| BundleRollbackError::UnknownBundle { + bundle_id: bundle_id.clone(), + })? + }; + let target = { + let store = bundles.clone(); + let lookup = bundle_id.clone(); + let wanted = version.clone(); + tokio::task::spawn_blocking(move || store.previous_bundle(&lookup, &wanted)) + .await + .map_err(|_| BundleRollbackError::WorkerFailed)? + .map_err(|error| BundleRollbackError::Mapping(error.to_string()))? + .ok_or_else(|| BundleRollbackError::VersionUnavailable { + bundle_id: bundle_id.clone(), + version: version.clone(), + })? + }; + // A bundle rollback only restores the same components; a history row with a different set is + // corrupt and must not silently change what the bundle owns. + let current_ids = current + .components + .iter() + .map(|component| component.plugin_id.as_str()) + .collect::>(); + let target_ids = target + .components + .iter() + .map(|component| component.plugin_id.as_str()) + .collect::>(); + if current_ids != target_ids { + return Err(BundleRollbackError::Mapping( + "the archived bundle version has a different component set".into(), + )); + } + let environment = gamenode_platform::plugin_environment::detect() + .await + .map_err(|error| BundleRollbackError::Component { + plugin_id: bundle_id.clone(), + error: error.to_string(), + })?; + stop_components_at(¤t, ®istry, stopper) + .await + .map_err(|error| BundleRollbackError::Component { + plugin_id: bundle_id.clone(), + error: error.to_string(), + })?; + let previous_version = current.version.clone(); + let outcome = { + let current = current.clone(); + let target = target.clone(); + let registry = registry.clone(); + let bundles = bundles.clone(); + let bundle_id = bundle_id.clone(); + let version = version.clone(); + tokio::task::spawn_blocking(move || { + rollback_bundle_blocking( + bundle_id, + version, + previous_version, + current, + target, + ®istry, + &bundles, + &grants, + &environment, + emulation_policy, + archived_at, + ) + }) + .await + .map_err(|_| BundleRollbackError::WorkerFailed)? + }?; + Ok(outcome) +} + +#[allow(clippy::too_many_arguments)] +fn rollback_bundle_blocking( + bundle_id: String, + version: String, + previous_version: String, + current: BundleRecord, + target: BundleRecord, + registry: &PluginPackageRegistry, + bundles: &SqlitePluginBundleStore, + grants: &BundleGrantContext, + environment: &PluginEnvironment, + emulation_policy: EmulationPolicy, + archived_at: i64, +) -> Result { + let mut prepared = Vec::with_capacity(target.components.len()); + for component in &target.components { + let installed = registry + .versions(&component.plugin_id) + .map_err(|error| BundleRollbackError::Component { + plugin_id: component.plugin_id.clone(), + error: error.to_string(), + })? + .into_iter() + .find(|installed| installed.version == component.package_version) + .ok_or_else(|| BundleRollbackError::ComponentMissing { + plugin_id: component.plugin_id.clone(), + version: component.package_version.clone(), + })?; + let key = package_key_of(&installed.package_path).map_err(|error| { + BundleRollbackError::Component { + plugin_id: component.plugin_id.clone(), + error, + } + })?; + let target_report = inspect_staged_package_blocking( + &installed.package_path, + key, + emulation_policy, + environment, + ) + .map_err(|error| BundleRollbackError::Component { + plugin_id: component.plugin_id.clone(), + error: error.to_string(), + })?; + let current_version = current + .components + .iter() + .find(|mapped| mapped.plugin_id == component.plugin_id) + .map(|mapped| mapped.package_version.clone()) + .ok_or_else(|| { + BundleRollbackError::Mapping( + "the current bundle mapping is missing a component".into(), + ) + })?; + let current_installed = registry + .versions(&component.plugin_id) + .map_err(|error| BundleRollbackError::Component { + plugin_id: component.plugin_id.clone(), + error: error.to_string(), + })? + .into_iter() + .find(|installed| installed.version == current_version); + let current_manifest = match current_installed { + Some(installed) => { + let key = package_key_of(&installed.package_path).map_err(|error| { + BundleRollbackError::Component { + plugin_id: component.plugin_id.clone(), + error, + } + })?; + inspect_staged_package_blocking( + &installed.package_path, + key, + emulation_policy, + environment, + ) + .map(|report| report.manifest) + .map_err(|error| BundleRollbackError::Component { + plugin_id: component.plugin_id.clone(), + error: error.to_string(), + })? + } + None => target_report.manifest.clone(), + }; + prepared.push(( + component.clone(), + installed, + key, + target_report, + current_manifest, + )); + } + + let mut previous_active = Vec::with_capacity(prepared.len()); + for (component, _, _, _, _) in &prepared { + previous_active.push(registry.active(&component.plugin_id).map_err(|error| { + BundleRollbackError::Component { + plugin_id: component.plugin_id.clone(), + error: error.to_string(), + } + })?); + } + let result = (|| { + for (component, installed, _, target_report, _) in &prepared { + if target_report.selected_target().is_ok() { + registry + .set_active(&component.plugin_id, &installed.version) + .map_err(|error| BundleRollbackError::Component { + plugin_id: component.plugin_id.clone(), + error: error.to_string(), + })?; + } + } + if let Some(profile) = grants.profiles.current() { + let mut store = grants + .layout + .open_grants(&profile) + .map_err(|error| BundleRollbackError::Grants(error.to_string()))?; + for (component, _, key, target_report, current_manifest) in &prepared { + let identity = PluginIdentity { + plugin_id: component.plugin_id.clone(), + publisher_fingerprint: key_fingerprint(key), + profile_id: profile.profile_id().to_owned(), + }; + store + .intersect_with_selected_manifest( + &identity, + current_manifest, + &target_report.manifest, + ) + .map_err(|error| BundleRollbackError::Grants(error.to_string()))?; + } + } + bundles + .restore_bundle_version(&bundle_id, &version, archived_at) + .map_err(|error| BundleRollbackError::Mapping(error.to_string()))? + .ok_or_else(|| BundleRollbackError::VersionUnavailable { + bundle_id: bundle_id.clone(), + version: version.clone(), + })?; + Ok(BundleRollbackOutcome { + bundle_id: bundle_id.clone(), + previous_version: previous_version.clone(), + version: version.clone(), + components: prepared + .iter() + .map( + |(component, installed, _, target_report, _)| UpdatedBundleComponent { + plugin_id: component.plugin_id.clone(), + kind: component.kind.clone(), + previous_version: current + .components + .iter() + .find(|mapped| mapped.plugin_id == component.plugin_id) + .map(|mapped| mapped.package_version.clone()) + .unwrap_or_default(), + version: installed.version.clone(), + active: target_report.selected_target().is_ok(), + }, + ) + .collect(), + }) + })(); + match result { + Ok(outcome) => Ok(outcome), + Err(error) => { + let mut problems = Vec::new(); + for ((component, _, _, _, _), previous) in prepared.iter().zip(&previous_active).rev() { + if let Some(previous) = previous + && let Err(error) = registry.set_active(&component.plugin_id, &previous.version) + { + problems.push(format!( + "reactivate {} {}: {error}", + component.plugin_id, previous.version + )); + } + } + if problems.is_empty() { + Err(error) + } else { + Err(BundleRollbackError::Restore { + cause: error.to_string(), + problems: problems.join("; "), + }) + } + } + } +} + +fn package_key_of(path: &Path) -> Result<[u8; 32], String> { + super::updates::package_key(path) +} + +/// Stops the supervised processes of one bundle component before its packages are deleted. +/// +/// Production uses [`ProviderProcesses`], whose termination path waits for the child with the +/// existing bounded grace. A component that is installed but inactive or unavailable has no active +/// package and therefore no process, so [`remove_installed_bundle`] never asks it to stop and an +/// implementation must also treat an idle component as a successful no-op. +pub trait BundleComponentStopper: Send + Sync { + fn stop_component<'a>( + &'a self, + plugin_id: &'a str, + ) -> Pin + Send + 'a>>; +} + +impl BundleComponentStopper for ProviderProcesses { + fn stop_component<'a>( + &'a self, + plugin_id: &'a str, + ) -> Pin + Send + 'a>> { + Box::pin(self.stop_plugin(plugin_id)) + } +} + +/// Production bundle updates and rollbacks stop components through the lifecycle, which also +/// disconnects provider sessions before the active package changes. +impl BundleComponentStopper for super::runtime::ThirdPartyPluginLifecycle { + fn stop_component<'a>( + &'a self, + plugin_id: &'a str, + ) -> Pin + Send + 'a>> { + Box::pin(self.stop_bundle_component(plugin_id)) + } +} + +/// One component whose recorded package version this removal deleted. +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct RemovedBundleComponent { + pub plugin_id: String, + pub version: String, + /// True when the component had an active package and its supervised process was stopped first. + pub stopped: bool, +} + +/// One component whose package could not be deleted. Its mapping row is retained, so the bundle +/// uninstall can be retried instead of forgetting a package that is still installed. +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct BundleRemovalFailure { + pub plugin_id: String, + pub version: String, + pub error: String, +} + +/// A fully removed bundle: the mapping that was read and every component package it deleted. +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct RemovedBundle { + pub bundle: BundleRecord, + pub components: Vec, +} + +#[derive(Debug, Error)] +pub enum BundleRemovalError { + #[error("bundle {bundle_id} is not installed")] + UnknownBundle { bundle_id: String }, + #[error("the bundle mapping could not be read: {0}")] + Mapping(String), + /// The component packages were removed but the mapping could not be updated. The whole + /// mapping was deleted as a fallback so no row keeps naming a deleted package. + #[error("the bundle mapping could not be updated after removal: {0}")] + MappingUpdate(String), + #[error("plugin package state is unavailable: {0}")] + Registry(String), + /// Some packages could not be deleted. The components that were removed are no longer mapped; + /// the failures keep their mapping row so the uninstall can be retried. + #[error( + "bundle {bundle_id} was only partly removed; the remaining components stay mapped: {problems}" + )] + PartialRemoval { + bundle_id: String, + removed: Vec, + failures: Vec, + problems: String, + }, + #[error("bundle removal worker failed")] + WorkerFailed, +} + +/// Remove one installed bundle: stop every component that is active at its recorded version, delete +/// exactly the recorded package version of each component, then delete the removed components from +/// the bundle mapping. +/// +/// The removal is deliberately narrower than an uninstall. It never deletes another installed +/// version of the same plugin id (a standalone version, or a newer one adopted by another bundle), +/// and it never touches grants, activation, private data or library history; the caller owns the +/// retention and session choices. Components are stopped before any package is deleted, so no +/// process keeps running against a package that is already gone. +/// +/// A component that cannot be removed keeps its mapping row and is reported, while the components +/// that were removed lose theirs. A mapping therefore never names a package that does not exist; a +/// retry removes what is left. File and database work runs on blocking workers. +pub async fn remove_installed_bundle( + bundle_id: impl Into, + registry: PluginPackageRegistry, + bundles: SqlitePluginBundleStore, + stopper: &dyn BundleComponentStopper, +) -> Result { + let bundle_id = bundle_id.into(); + let bundle = { + let store = bundles.clone(); + let lookup = bundle_id.clone(); + tokio::task::spawn_blocking(move || store.bundle(&lookup)) + .await + .map_err(|_| BundleRemovalError::WorkerFailed)? + .map_err(|error| BundleRemovalError::Mapping(error.to_string()))? + .ok_or_else(|| BundleRemovalError::UnknownBundle { + bundle_id: bundle_id.clone(), + })? + }; + + // Which components are active at the recorded version, and therefore have a supervised process + // to stop. An installed-but-inactive (for example unavailable) component has nothing to stop, + // and neither does one whose plugin id is only active at another standalone version. + let mut active = Vec::with_capacity(bundle.components.len()); + for component in &bundle.components { + let registry = registry.clone(); + let plugin_id = component.plugin_id.clone(); + let version = component.package_version.clone(); + let installed = tokio::task::spawn_blocking(move || registry.active(&plugin_id)) + .await + .map_err(|_| BundleRemovalError::WorkerFailed)? + .map_err(|error| BundleRemovalError::Registry(error.to_string()))?; + active.push(installed.is_some_and(|active| active.version == version)); + } + // Stop before any package removal, so a failure below cannot leave a process running against + // half-removed files. + for (component, active) in bundle.components.iter().zip(&active) { + if *active { + stopper.stop_component(&component.plugin_id).await; + } + } + + let components = bundle.components.clone(); + let (removed, failures) = tokio::task::spawn_blocking(move || { + let mut removed = Vec::with_capacity(components.len()); + let mut failures = Vec::new(); + for (component, active) in components.into_iter().zip(active) { + match registry.remove_version(&component.plugin_id, &component.package_version) { + Ok(()) => removed.push(RemovedBundleComponent { + plugin_id: component.plugin_id, + version: component.package_version, + stopped: active, + }), + Err(error) => failures.push(BundleRemovalFailure { + plugin_id: component.plugin_id, + version: component.package_version, + error: error.to_string(), + }), + } + } + (removed, failures) + }) + .await + .map_err(|_| BundleRemovalError::WorkerFailed)?; + + if !removed.is_empty() { + let plugin_ids: Vec = removed + .iter() + .map(|component| component.plugin_id.clone()) + .collect(); + let store = bundles.clone(); + let lookup = bundle_id.clone(); + let updated = tokio::task::spawn_blocking(move || { + store.remove_bundle_components(&lookup, &plugin_ids) + }) + .await + .map_err(|_| BundleRemovalError::WorkerFailed)?; + if let Err(error) = updated { + // The packages are gone, so the mapping must not keep naming them. Deleting the whole + // mapping is the safe fallback: the failed components become ordinary standalone + // packages instead of a mapping that points at deleted versions. + let store = bundles; + let lookup = bundle_id.clone(); + let fallback = tokio::task::spawn_blocking(move || store.remove_bundle(&lookup)) + .await + .map_err(|_| BundleRemovalError::WorkerFailed)?; + return Err(BundleRemovalError::MappingUpdate(match fallback { + Ok(_) => format!("{error}; the whole bundle mapping was deleted instead"), + Err(fallback) => { + format!("{error}; deleting the whole mapping also failed: {fallback}") + } + })); + } + } + + if failures.is_empty() { + return Ok(RemovedBundle { + bundle, + components: removed, + }); + } + let problems = failures + .iter() + .map(|failure| { + format!( + "{} {}: {}", + failure.plugin_id, failure.version, failure.error + ) + }) + .collect::>() + .join("; "); + Err(BundleRemovalError::PartialRemoval { + bundle_id, + removed, + failures, + problems, + }) +} + +/// What the bundle uninstall does with each component's private data after the packages are gone. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum BundleDataRetention { + /// Keep private storage, grants, and every other account record (the package-only uninstall). + Keep, + /// Also delete each removed component's private data for one account profile. + Delete, +} + +impl BundleDataRetention { + fn as_str(self) -> &'static str { + match self { + Self::Keep => "kept", + Self::Delete => "deleted", + } + } +} + +/// The account profile whose private plugin data a bundle uninstall may delete. Library history, +/// grants and activation never live here; only the plugin's own durable namespace does. +#[derive(Clone, Copy, Debug)] +pub struct BundlePrivateData<'a> { + /// The OS-user `plugin-data` root. + pub root: &'a Path, + /// The signed-in account profile whose namespaces this uninstall may delete. + pub profile_id: &'a str, +} + +/// The result of one bundle uninstall. A partial failure is reported here instead of as a generic +/// error: the removed components are listed with the ones that could not be removed. +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct BundleUninstallOutcome { + pub bundle_id: String, + pub removed: Vec, + /// Components whose package, account state or private data could not be removed. Each one + /// stays mapped when its package remains installed, so the uninstall can be retried. + pub failures: Vec, + /// `kept` or `deleted`, matching the retention choice this uninstall applied. + pub data_retention: String, +} + +#[derive(Debug, Error)] +pub enum BundleUninstallError { + #[error("bundle {bundle_id} is not installed")] + UnknownBundle { bundle_id: String }, + #[error("the bundle mapping could not be read: {0}")] + Mapping(String), + #[error("sign in to uninstall a plugin bundle")] + SignInRequired, + #[error(transparent)] + Removal(#[from] BundleRemovalError), + #[error("bundle uninstall worker failed")] + WorkerFailed, +} + +/// Uninstall one installed bundle: stop and remove every mapped component through +/// [`remove_installed_bundle`], then apply one persistence-retention choice to the components that +/// were actually removed. +/// +/// Partial package removal is not turned into an error. The returned outcome lists what was +/// removed and what failed, so the UI can name every remaining component instead of showing a +/// generic failure; callers must treat a non-empty `failures` as incomplete. Private data is only +/// deleted when the caller names the profile and the retention choice is +/// [`BundleDataRetention::Delete`]. Grants, activation and library history are never touched here; +/// the lifecycle wrapper removes the account state. +pub async fn uninstall_bundle( + bundle_id: impl Into, + registry: PluginPackageRegistry, + bundles: SqlitePluginBundleStore, + stopper: &dyn BundleComponentStopper, + retention: BundleDataRetention, + private_data: Option>, +) -> Result { + let bundle_id = bundle_id.into(); + let record = { + let store = bundles.clone(); + let lookup = bundle_id.clone(); + tokio::task::spawn_blocking(move || store.bundle(&lookup)) + .await + .map_err(|_| BundleUninstallError::WorkerFailed)? + .map_err(|error| BundleUninstallError::Mapping(error.to_string()))? + .ok_or_else(|| BundleUninstallError::UnknownBundle { + bundle_id: bundle_id.clone(), + })? + }; + let (removed, mut failures) = + match remove_installed_bundle(bundle_id.clone(), registry, bundles, stopper).await { + Ok(removed) => (removed.components, Vec::new()), + Err(BundleRemovalError::PartialRemoval { + removed, failures, .. + }) => (removed, failures), + Err(error) => return Err(BundleUninstallError::Removal(error)), + }; + + let mut applied_retention = BundleDataRetention::Keep; + if let Some(private_data) = private_data { + let root = private_data.root.to_owned(); + let publisher = record.publisher_fingerprint.clone(); + let profile = private_data.profile_id.to_owned(); + let components = removed.clone(); + let delete = retention == BundleDataRetention::Delete; + if delete { + applied_retention = BundleDataRetention::Delete; + } + let data_failures = tokio::task::spawn_blocking(move || { + let mut problems = Vec::new(); + for component in components { + let result = if delete { + remove_private_namespace(&root, &publisher, &component.plugin_id, &profile) + .map(|_| ()) + } else { + // Keep now means the same as a single-plugin Keep: the entries stay on disk + // with their provenance but become inert until a reviewed reuse. + archive_private_namespace(&root, &publisher, &component.plugin_id, &profile) + .map(|_| ()) + }; + if let Err(error) = result { + problems.push(BundleRemovalFailure { + plugin_id: component.plugin_id, + version: component.version, + error, + }); + } + } + problems + }) + .await + .map_err(|_| BundleUninstallError::WorkerFailed)?; + failures.extend(data_failures); + } + + // The mapping check above already proved the bundle existed; `record` only supplies the id in + // the outcome and keeps the publisher decision visible to callers. + debug_assert_eq!(record.bundle_id, bundle_id); + Ok(BundleUninstallOutcome { + bundle_id, + removed, + failures, + data_retention: applied_retention.as_str().to_owned(), + }) +} + +/// Archives the private durable entries of one plugin for one account profile after a bundle +/// Keep. Only that profile's store changes; the rows stay attributed and are inert until a +/// reviewed reuse. +fn archive_private_namespace( + root: &Path, + publisher_fingerprint: &str, + plugin_id: &str, + profile_id: &str, +) -> Result { + archive_namespace(root, publisher_fingerprint, plugin_id, profile_id) + .map(|archived| archived.is_some_and(|outcome| outcome.records > 0)) + .map_err(|error| format!("private data could not be archived: {error}")) +} + +/// Deletes the private durable namespace of one plugin for one account profile. Only the profile +/// directory is removed, never the plugin or publisher directories that may hold other profiles, +/// and symlinks are refused instead of followed. +fn remove_private_namespace( + root: &Path, + publisher_fingerprint: &str, + plugin_id: &str, + profile_id: &str, +) -> Result { + let dir = namespace_dir(root, publisher_fingerprint, plugin_id, profile_id); + // `namespace_dir` only sanitizes components; this keeps a future call site that passes a path + // from escaping the plugin-data root. + if !dir.starts_with(root) { + return Err("private data path escapes the plugin-data root".to_owned()); + } + let metadata = match fs::symlink_metadata(&dir) { + Ok(metadata) => metadata, + Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(false), + Err(error) => return Err(format!("private data could not be read: {error}")), + }; + if metadata.file_type().is_symlink() || !metadata.is_dir() { + return Err("private data is not a regular directory".to_owned()); + } + fs::remove_dir_all(&dir) + .map_err(|error| format!("private data could not be removed: {error}"))?; + Ok(true) +} + +/// One component whose durable shared records could not be retained or deleted. +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct BundleDurableRetentionFailure { + pub plugin_id: String, + pub version: String, + pub error: String, +} + +/// One retention choice applied to every component a package-only removal removed. +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct BundleDurableRetentionResult { + /// `kept` or `deleted`, matching the choice applied to every removed component. + pub data_retention: &'static str, + pub retained: Vec, + pub failures: Vec, +} + +/// A package-only removal plus the durable-retention result for its removed components. +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct RemovedBundleWithRetention { + pub removed: RemovedBundle, + pub durable: BundleDurableRetentionResult, +} + +/// Applies one keep-or-delete choice to every component a bundle removal actually deleted. +/// +/// The bundle mapping is package-only, so retention is a separate host decision. Keeping archives +/// each component's rows under its own owner; deleting removes only that owner's rows. A failure +/// for one component is reported by plugin id and does not change another component's data. +pub async fn apply_bundle_durable_retention( + removed: &[RemovedBundleComponent], + retention: DataRetention, + sink: &dyn DurableRetentionSink, +) -> BundleDurableRetentionResult { + let mut retained = Vec::with_capacity(removed.len()); + let mut failures = Vec::new(); + for component in removed { + match sink.apply(&component.plugin_id, retention).await { + Ok(outcome) => retained.push(outcome), + Err(error) => failures.push(BundleDurableRetentionFailure { + plugin_id: component.plugin_id.clone(), + version: component.version.clone(), + error, + }), + } + } + BundleDurableRetentionResult { + data_retention: retention.as_str(), + retained, + failures, + } +} + +/// Remove one installed bundle and apply one durable-retention choice to the components whose +/// packages were removed. The mapping, grants, activation and private stores are still left to +/// the caller, exactly as in [`remove_installed_bundle`]. A partial package removal returns its +/// error before any retention is applied; retry the removal to finish it. +pub async fn remove_installed_bundle_with_retention( + bundle_id: impl Into, + registry: PluginPackageRegistry, + bundles: SqlitePluginBundleStore, + stopper: &dyn BundleComponentStopper, + retention: DataRetention, + sink: &dyn DurableRetentionSink, +) -> Result { + let removed = remove_installed_bundle(bundle_id, registry, bundles, stopper).await?; + let durable = apply_bundle_durable_retention(&removed.components, retention, sink).await; + Ok(RemovedBundleWithRetention { removed, durable }) +} + +/// The archive must still be the exact bundle the user reviewed. Byte-level comparison is the +/// per-component SHA-256 the review carried; the bundle fields are compared as well so a +/// re-signed manifest cannot slip a different identity past the review. +fn confirm_reviewed_bundle( + reviewed: &BundleCandidateReport, + verified: &VerifiedBundle, +) -> Result<(), BundleInstallError> { + let publisher_key = verified.manifest.publisher_key()?; + let identity_matches = reviewed.bundle.id == verified.manifest.id + && reviewed.bundle.name == verified.manifest.name + && reviewed.bundle.version == verified.manifest.version + && reviewed.bundle.publisher_key_id == verified.manifest.publisher.key_id + && reviewed.bundle.publisher_fingerprint == key_fingerprint(&publisher_key); + if !identity_matches { + return Err(BundleInstallError::ChangedSinceReview( + "the bundle identity differs from the review".into(), + )); + } + if reviewed.components.len() != verified.components.len() { + return Err(BundleInstallError::ChangedSinceReview( + "the bundle component count differs from the review".into(), + )); + } + for (reviewed_component, component) in reviewed.components.iter().zip(&verified.components) { + if reviewed_component.archive_path != component.path + || reviewed_component.plugin_id != component.plugin_id + || reviewed_component.kind != component.kind + || reviewed_component.version != component.version + || reviewed_component.sha256 != component.sha256 + { + return Err(BundleInstallError::ChangedSinceReview(format!( + "component {} differs from the review", + component.plugin_id + ))); + } + } + Ok(()) +} + +/// Flatten an error and its causes so a staging failure says why it failed. +fn error_chain(error: &(dyn std::error::Error + 'static)) -> String { + let mut text = error.to_string(); + let mut source = error.source(); + while let Some(cause) = source { + text.push_str(&format!(": {cause}")); + source = cause.source(); + } + text +} + +fn kind_matches(kind: PluginKind, declared: &str) -> bool { + matches!( + (kind, declared), + (PluginKind::Provider, "provider") | (PluginKind::Extension, "extension") + ) +} + +/// Only the compatibility evaluator's selection decides availability; package validation +/// failures are already structural errors and never reach this function. +pub(crate) fn availability(report: &PackageCandidateReport) -> BundleComponentAvailability { + match report.selected_target() { + Ok(_) => BundleComponentAvailability::Available, + // `selected_target` currently reports exactly these two causes; anything else also fails + // target selection, so it must not be shown as available. + Err(PackageLifecycleError::AmbiguousTarget) => BundleComponentAvailability::Unavailable { + reason: BundleUnavailabilityReason::AmbiguousTarget, + }, + Err(_) => BundleComponentAvailability::Unavailable { + reason: BundleUnavailabilityReason::NoCompatibleTarget, + }, + } +} + +/// Private staging root for one bundle inspection or install. It is created with owner-only +/// permissions and removed on drop, including when a component fails validation or installation. +struct BundleWorkDir { + path: PathBuf, +} + +impl BundleWorkDir { + fn create() -> io::Result { + for _ in 0..8 { + let mut nonce = [0u8; 16]; + getrandom::fill(&mut nonce).map_err(io::Error::other)?; + let name = nonce + .iter() + .map(|byte| format!("{byte:02x}")) + .collect::(); + let path = std::env::temp_dir().join(format!("gamenode-plugin-bundle-{name}")); + match fs::create_dir(&path) { + Ok(()) => { + restrict_private(&path)?; + if let Err(error) = fs::create_dir(path.join("packages")) { + let _ = fs::remove_dir_all(&path); + return Err(error); + } + return Ok(Self { path }); + } + Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue, + Err(error) => return Err(error), + } + } + Err(io::Error::new( + io::ErrorKind::AlreadyExists, + "could not reserve bundle staging", + )) + } +} + +impl Drop for BundleWorkDir { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.path); + } +} + +#[cfg(unix)] +fn restrict_private(path: &Path) -> io::Result<()> { + use std::os::unix::fs::PermissionsExt; + fs::set_permissions(path, fs::Permissions::from_mode(0o700)) +} + +#[cfg(not(unix))] +fn restrict_private(_: &Path) -> io::Result<()> { + Ok(()) +} + +/// The real Dolphin development artifact shared by the 7.1 import/uninstall acceptance and the +/// durable-read acceptance. Absent unless `DOLPHIN_BUNDLE_PATH` names the signed archive. +#[cfg(all(test, target_os = "linux"))] +pub(crate) fn dolphin_bundle_artifact() -> Option { + let Some(path) = std::env::var_os("DOLPHIN_BUNDLE_PATH") else { + eprintln!( + "skipping the real Dolphin bundle acceptance: set DOLPHIN_BUNDLE_PATH to \ + gamenode-plugin-dolphin-emu/dist/dolphin-emu-0.1.0-linux-x64.gnbundle" + ); + return None; + }; + let path = PathBuf::from(path); + assert!( + path.is_file(), + "DOLPHIN_BUNDLE_PATH must point at the signed .gnbundle artifact: {path:?}" + ); + Some(path) +} + +#[cfg(all(test, target_os = "linux"))] +mod tests { + use super::*; + use crate::plugin_host::{ + PluginApi, PluginApiServer, + compatibility::CompatibilityState, + grants::{ + GrantScope, PermissionDecision, PermissionGrantStore, PermissionRequest, + PermissionState, PluginIdentity, + }, + managed_packages::ManagedPackageLifecycle, + process::ProviderProcesses, + profile::PluginStateLayout, + publisher_trust, + runtime::{HostedProviders, PluginPermissionSnapshot, ThirdPartyPluginLifecycle}, + updates::{ + BundleComponentDeniedPermissions, BundleComponentPermissionSubmission, + PluginUpdateService, + }, + }; + use base64::Engine as _; + use gamenode_core::{library::LibraryStore as _, provider::Record}; + use gamenode_platform::{ + db::{self, SqliteSettingsStore}, + paths::DataPaths, + plugin_registry::PluginPackageRegistry, + plugin_updates::UpdateRelease, + }; + use std::{ + collections::{BTreeMap, BTreeSet}, + io::{Read, Write}, + path::PathBuf, + sync::{Arc, Mutex}, + }; + use zip::{ZipWriter, write::SimpleFileOptions}; + + /// Runs the repository pack tool; the fixture key and every archive are real tool output. + fn package_tool(work: &Path, args: &[&str]) -> String { + let script = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../scripts/plugin-package.py"); + assert!(script.is_file(), "missing plugin package tool: {script:?}"); + let output = std::process::Command::new("python3") + .arg(&script) + .args(args) + .current_dir(work) + .output() + .expect("python3 with the cryptography package must run the bundle fixture tooling"); + assert!( + output.status.success(), + "plugin-package.py {args:?} failed: {}", + String::from_utf8_lossy(&output.stderr) + ); + String::from_utf8(output.stdout).unwrap() + } + + struct Fixture { + dir: tempfile::TempDir, + key: PathBuf, + public_key: String, + } + + impl Fixture { + fn new() -> Self { + let dir = tempfile::tempdir().unwrap(); + let key = dir.path().join("fixture-dev.pem"); + let output = package_tool( + dir.path(), + &[ + "keygen", + "--development", + "--private-key", + key.to_str().unwrap(), + ], + ); + let public_key = output + .lines() + .find_map(|line| line.strip_prefix("publisher.public_key (base64): ")) + .expect("keygen prints the fixture publisher key") + .to_owned(); + Self { + dir, + key, + public_key, + } + } + + fn base64_key(&self) -> [u8; 32] { + base64::engine::general_purpose::STANDARD + .decode(&self.public_key) + .unwrap() + .try_into() + .unwrap() + } + + #[allow(clippy::too_many_arguments)] + fn component( + &self, + file: &str, + kind: &str, + id: &str, + version: &str, + os: &str, + abi: &str, + api_min: &str, + ) -> PathBuf { + self.component_with_permissions(file, kind, id, version, os, abi, api_min, vec![]) + } + + /// A component that declares the given signed permission requests, so the import review + /// and the grouped consent flow can be exercised with real manifests. + #[allow(clippy::too_many_arguments)] + fn component_with_permissions( + &self, + file: &str, + kind: &str, + id: &str, + version: &str, + os: &str, + abi: &str, + api_min: &str, + permissions: Vec, + ) -> PathBuf { + self.component_with_platforms( + file, + kind, + id, + version, + os, + abi, + api_min, + permissions, + vec![], + ) + } + + /// The same fixture with signed content-platform disclosures. + #[allow(clippy::too_many_arguments)] + fn component_with_platforms( + &self, + file: &str, + kind: &str, + id: &str, + version: &str, + os: &str, + abi: &str, + api_min: &str, + permissions: Vec, + supported_platforms: Vec<&str>, + ) -> PathBuf { + let source = self.dir.path().join(format!("{file}-source")); + fs::create_dir_all(source.join("bin")).unwrap(); + fs::create_dir_all(source.join("licenses")).unwrap(); + fs::write(source.join("bin/plugin"), b"fixture executable").unwrap(); + fs::write(source.join("licenses/LICENSE"), b"fixture license").unwrap(); + let mut manifest = serde_json::json!({ + "schema": 1, + "id": id, + "kind": kind, + "name": format!("{id} fixture"), + "version": version, + "api": { "min": api_min, "max": "1.6.0" }, + "targets": [{ + "os": os, + "arch": "x86_64", + "abi": abi, + "entrypoint": "bin/plugin" + }], + "publisher": { + "key_id": "dolphin-dev", + "public_key": self.public_key + }, + "license": { "expression": "MIT", "files": ["licenses/LICENSE"] } + }); + if kind == "provider" { + manifest["provider_id"] = serde_json::json!("dolphin-fixture"); + } + manifest["permissions"] = permissions.into(); + if !supported_platforms.is_empty() { + manifest["supported_platforms"] = serde_json::json!(supported_platforms); + } + fs::write( + source.join("plugin.json"), + serde_json::to_vec(&manifest).unwrap(), + ) + .unwrap(); + let output = self.dir.path().join(format!("{file}.gnplugin")); + package_tool( + self.dir.path(), + &[ + "pack", + "--source", + source.to_str().unwrap(), + "--output", + output.to_str().unwrap(), + "--private-key", + self.key.to_str().unwrap(), + ], + ); + output + } + + fn bundle(&self, components: &[&Path]) -> PathBuf { + self.bundle_version(components, "0.1.0") + } + + /// A bundle with the same id and name at the given distribution version, so one fixture + /// can model an update of the same product. + fn bundle_version(&self, components: &[&Path], version: &str) -> PathBuf { + let output = self.dir.path().join(format!("fixture-{version}.gnbundle")); + let mut args = vec!["bundle"]; + for component in components { + args.push("--component"); + args.push(component.to_str().unwrap()); + } + args.extend([ + "--id", + "org.example.dolphin", + "--name", + "Dolphin GameCube and Wii", + "--version", + version, + "--output", + output.to_str().unwrap(), + "--private-key", + self.key.to_str().unwrap(), + ]); + package_tool(self.dir.path(), &args); + output + } + } + + fn component<'a>( + report: &'a BundleCandidateReport, + plugin_id: &str, + ) -> &'a BundleComponentInspection { + report + .components + .iter() + .find(|component| component.plugin_id == plugin_id) + .unwrap_or_else(|| panic!("missing component report for {plugin_id}")) + } + + #[tokio::test] + async fn a_valid_bundle_reports_every_component_with_its_own_review() { + let fixture = Fixture::new(); + let provider = fixture.component( + "provider", + "provider", + "org.example.dolphin", + "0.1.0", + "linux", + "gnu", + "1.6.0", + ); + let launch = fixture.component( + "launch", + "extension", + "org.example.dolphin.launch", + "0.2.0", + "linux", + "gnu", + "1.6.0", + ); + let bundle = fixture.bundle(&[&provider, &launch]); + + let report = inspect_bundle_candidate(&bundle, EmulationPolicy::RequireNative) + .await + .unwrap(); + assert_eq!(report.bundle.id, "org.example.dolphin"); + assert_eq!(report.bundle.name, "Dolphin GameCube and Wii"); + assert_eq!(report.bundle.version, "0.1.0"); + assert_eq!(report.bundle.publisher_key_id, "dolphin-dev"); + assert_eq!( + report.bundle.publisher_fingerprint, + publisher_trust::key_fingerprint(&fixture.base64_key()) + ); + assert_eq!(report.components.len(), 2); + + let provider = component(&report, "org.example.dolphin"); + assert_eq!(provider.kind, "provider"); + assert_eq!(provider.version, "0.1.0"); + assert_eq!(provider.archive_path, "components/provider.gnplugin"); + assert_eq!( + provider.availability, + BundleComponentAvailability::Available + ); + assert_eq!(provider.compatibility.state, CompatibilityState::Compatible); + assert!(!provider.compatibility.targets.is_empty()); + + let launch = component(&report, "org.example.dolphin.launch"); + assert_eq!(launch.kind, "extension"); + assert_eq!(launch.version, "0.2.0"); + assert_eq!(launch.archive_path, "components/launch.gnplugin"); + assert_eq!(launch.availability, BundleComponentAvailability::Available); + assert_eq!(launch.compatibility.state, CompatibilityState::Compatible); + } + + #[tokio::test] + async fn an_incompatible_component_is_unavailable_and_its_sibling_stays_usable() { + let fixture = Fixture::new(); + let provider = fixture.component( + "provider", + "provider", + "org.example.dolphin", + "0.1.0", + "linux", + "gnu", + "1.6.0", + ); + // No Windows target can match the Linux test host; the package itself is valid. + let launch = fixture.component( + "launch", + "extension", + "org.example.dolphin.launch", + "0.2.0", + "windows", + "msvc", + "1.6.0", + ); + let bundle = fixture.bundle(&[&provider, &launch]); + + let report = inspect_bundle_candidate(&bundle, EmulationPolicy::RequireNative) + .await + .unwrap(); + assert_eq!(report.components.len(), 2); + assert_eq!( + component(&report, "org.example.dolphin").availability, + BundleComponentAvailability::Available + ); + let launch = component(&report, "org.example.dolphin.launch"); + assert_eq!( + launch.availability, + BundleComponentAvailability::Unavailable { + reason: BundleUnavailabilityReason::NoCompatibleTarget + } + ); + assert_eq!(launch.compatibility.state, CompatibilityState::Incompatible); + } + + #[tokio::test] + async fn a_corrupt_component_fails_the_whole_bundle_structurally() { + let fixture = Fixture::new(); + let provider = fixture.component( + "provider", + "provider", + "org.example.dolphin", + "0.1.0", + "linux", + "gnu", + "1.6.0", + ); + let launch = fixture.component( + "launch", + "extension", + "org.example.dolphin.launch", + "0.2.0", + "linux", + "gnu", + "1.6.0", + ); + let bundle = fixture.bundle(&[&provider, &launch]); + + // Rewrite the outer envelope with one extra payload byte in the provider archive. The + // bundle still parses, but the declared component hash no longer matches. + let corrupt = fixture.dir.path().join("corrupt.gnbundle"); + let mut source = zip::ZipArchive::new(fs::File::open(&bundle).unwrap()).unwrap(); + let mut writer = ZipWriter::new(fs::File::create(&corrupt).unwrap()); + for index in 0..source.len() { + let mut entry = source.by_index(index).unwrap(); + let name = entry.name().to_owned(); + let mut data = Vec::new(); + entry.read_to_end(&mut data).unwrap(); + if name == "components/provider.gnplugin" { + data.push(0); + } + writer + .start_file(name, SimpleFileOptions::default()) + .unwrap(); + writer.write_all(&data).unwrap(); + } + writer.finish().unwrap(); + + let result = inspect_bundle_candidate(&corrupt, EmulationPolicy::RequireNative).await; + assert!( + matches!( + result, + Err(BundleInspectionError::Bundle(BundleError::InvalidComponent)) + ), + "{result:?}" + ); + } + + #[tokio::test] + async fn a_component_that_fails_package_validation_rejects_the_bundle() { + let fixture = Fixture::new(); + let provider = fixture.component( + "provider", + "provider", + "org.example.dolphin", + "0.1.0", + "linux", + "gnu", + "1.6.0", + ); + // The pack tool does not evaluate the API range, so this archive verifies as a bundle + // component but the host's full manifest validator rejects it. + let launch = fixture.component( + "launch", + "extension", + "org.example.dolphin.launch", + "0.2.0", + "linux", + "gnu", + "not-semver", + ); + let bundle = fixture.bundle(&[&provider, &launch]); + + let result = inspect_bundle_candidate(&bundle, EmulationPolicy::RequireNative).await; + assert!( + matches!( + result, + Err(BundleInspectionError::Component { ref plugin_id, .. }) + if plugin_id == "org.example.dolphin.launch" + ), + "{result:?}" + ); + } + + /// A fresh database and registry for one bundle install test. + fn install_target(fixture: &Fixture) -> (PluginPackageRegistry, SqliteSettingsStore) { + let registry = PluginPackageRegistry::at(fixture.dir.path().join("registry")).unwrap(); + let settings = + SqliteSettingsStore::open(&fixture.dir.path().join("state.sqlite3")).unwrap(); + (registry, settings) + } + + #[tokio::test] + async fn a_valid_bundle_installs_every_component_and_records_the_mapping() { + let fixture = Fixture::new(); + let provider = fixture.component( + "provider", + "provider", + "org.example.dolphin", + "0.1.0", + "linux", + "gnu", + "1.6.0", + ); + let launch = fixture.component( + "launch", + "extension", + "org.example.dolphin.launch", + "0.2.0", + "linux", + "gnu", + "1.6.0", + ); + let bundle = fixture.bundle(&[&provider, &launch]); + let report = inspect_bundle_candidate(&bundle, EmulationPolicy::RequireNative) + .await + .unwrap(); + let (registry, settings) = install_target(&fixture); + + let installed_at = 1_700_000_000; + let installed = install_bundle_candidate( + &bundle, + report.clone(), + registry.clone(), + settings.bundle_store(), + EmulationPolicy::RequireNative, + installed_at, + ) + .await + .unwrap(); + + assert_eq!(installed.bundle.bundle_id, "org.example.dolphin"); + assert_eq!(installed.bundle.name, "Dolphin GameCube and Wii"); + assert_eq!(installed.bundle.version, "0.1.0"); + assert_eq!( + installed.bundle.publisher_fingerprint, + report.bundle.publisher_fingerprint + ); + assert_eq!(installed.bundle.installed_at, installed_at); + assert_eq!(installed.bundle.manifest_sha256.len(), 64); + assert_eq!(installed.bundle.components.len(), 2); + assert_eq!(installed.components.len(), 2); + assert!( + installed + .components + .iter() + .all(|component| component.active), + "{:?}", + installed.components + ); + + let key = fixture.base64_key(); + let stored = settings + .bundle_store() + .bundle("org.example.dolphin") + .unwrap() + .expect("the mapping is stored"); + assert_eq!(stored, installed.bundle); + assert_eq!( + settings + .bundle_store() + .bundle_for_plugin("org.example.dolphin.launch") + .unwrap(), + Some(installed.bundle.clone()) + ); + for inspected in &report.components { + let recorded = installed + .bundle + .components + .iter() + .find(|component| component.plugin_id == inspected.plugin_id) + .expect("every inspected component is recorded"); + assert_eq!(recorded.component_sha256, inspected.sha256); + assert_eq!(recorded.package_version, inspected.version); + } + + let provider_active = registry.active("org.example.dolphin").unwrap().unwrap(); + assert_eq!(provider_active.version, "0.1.0"); + assert_eq!( + registry + .verify_active_package("org.example.dolphin", &key) + .unwrap(), + Some(provider_active) + ); + let launch_active = registry + .active("org.example.dolphin.launch") + .unwrap() + .unwrap(); + assert_eq!(launch_active.version, "0.2.0"); + assert_eq!( + registry + .verify_active_package("org.example.dolphin.launch", &key) + .unwrap(), + Some(launch_active) + ); + } + + #[tokio::test] + async fn an_approved_bundle_review_installs_every_component_and_consumes_its_token() { + let fixture = Fixture::new(); + let provider = fixture.component( + "provider", + "provider", + "org.example.dolphin", + "0.1.0", + "linux", + "gnu", + "1.6.0", + ); + let launch = fixture.component( + "launch", + "extension", + "org.example.dolphin.launch", + "0.2.0", + "linux", + "gnu", + "1.6.0", + ); + let bundle = fixture.bundle(&[&provider, &launch]); + let paths = DataPaths::at(fixture.dir.path().join("app-data")); + let api = PluginApi::default(); + let state = PluginStateLayout::managed(&paths); + api.set_state_layout(state.clone()); + api.providers + .profiles() + .update(Some("bundle-account"), true); + let registry = PluginPackageRegistry::open(&paths).unwrap(); + let service = review_service(&api, &paths, &state, ®istry); + let settings = + SqliteSettingsStore::open(&fixture.dir.path().join("bundles.sqlite3")).unwrap(); + service.set_bundle_store(settings.bundle_store()); + + let review = service.bundle_import_review(bundle.clone()).await.unwrap(); + assert_eq!(review.components.len(), 2); + // An unconfirmed review cannot install anything. + let refused = service + .bundle_import_install(&review.token, true, &[]) + .await + .expect_err("the publisher decision comes before installation"); + assert!( + refused.contains("confirm the bundle publisher fingerprint"), + "{refused}" + ); + + service + .bundle_import_confirm_publisher(&review.token, &review.bundle.publisher_fingerprint) + .await + .unwrap(); + let outcome = service + .bundle_import_install(&review.token, true, &[]) + .await + .unwrap(); + assert_eq!(outcome.bundle_id, "org.example.dolphin"); + assert_eq!(outcome.components.len(), 2); + assert!( + outcome.components.iter().all(|component| component.active), + "{:?}", + outcome.components + ); + let stored = settings + .bundle_store() + .bundle("org.example.dolphin") + .unwrap() + .expect("the approved install records the mapping"); + assert_eq!(stored.components.len(), 2); + assert_eq!( + registry + .active("org.example.dolphin") + .unwrap() + .map(|installed| installed.version), + Some("0.1.0".to_owned()) + ); + + // The approved review is single-use; a replay cannot install again. + let replay = service + .bundle_import_install(&review.token, true, &[]) + .await + .expect_err("the token is consumed by the install"); + assert!(replay.contains("expired"), "{replay}"); + } + + /// The bundle review inherits each component's signed platform and permission-impact + /// disclosures, and the install applies one component's denial without touching its sibling. + #[tokio::test] + async fn bundle_import_install_applies_per_component_permission_decisions() { + let fixture = Fixture::new(); + let provider = fixture.component_with_platforms( + "provider", + "provider", + "org.example.dolphin", + "0.1.0", + "linux", + "gnu", + "1.6.0", + vec![ + serde_json::json!({ + "id": "provider.context.read", "required": true, + "scope": "provider session", "reason": "Open a provider session" + }), + serde_json::json!({ + "id": "storage.persist", "required": false, "scope": "own-provider", + "reason": "Store plugin preferences", + "impact_if_disabled": "Preferences are lost between sessions" + }), + serde_json::json!({ + "id": "network.fetch", "required": false, + "scope": "https://api.example.com", "reason": "Fetch remote metadata", + "impact_if_disabled": "Remote metadata stays unavailable" + }), + ], + vec!["gamecube", "wii"], + ); + let launch = fixture.component_with_permissions( + "launch", + "extension", + "org.example.dolphin.launch", + "0.2.0", + "linux", + "gnu", + "1.6.0", + vec![serde_json::json!({ + "id": "game.launch", "required": false, + "scope": "approved-game-session", "reason": "Launch a game", + "impact_if_disabled": "Launching from the plugin is unavailable" + })], + ); + let bundle = fixture.bundle(&[&provider, &launch]); + + let paths = DataPaths::at(fixture.dir.path().join("app-data")); + let api = PluginApi::default(); + let state = PluginStateLayout::managed(&paths); + api.set_state_layout(state.clone()); + api.providers + .profiles() + .update(Some("bundle-account"), true); + let registry = PluginPackageRegistry::open(&paths).unwrap(); + let service = review_service(&api, &paths, &state, ®istry); + let settings = + SqliteSettingsStore::open(&fixture.dir.path().join("bundles.sqlite3")).unwrap(); + service.set_bundle_store(settings.bundle_store()); + + let review = service.bundle_import_review(bundle).await.unwrap(); + let provider_review = review + .components + .iter() + .find(|component| component.review.plugin_id == "org.example.dolphin") + .expect("the provider is reviewed"); + assert_eq!( + provider_review.review.supported_platforms, + ["gamecube", "wii"] + ); + assert_eq!( + provider_review.review.requested_permissions[1] + .impact_if_disabled + .as_deref(), + Some("Preferences are lost between sessions") + ); + let launch_review = review + .components + .iter() + .find(|component| component.review.plugin_id == "org.example.dolphin.launch") + .expect("the extension is reviewed"); + assert_eq!( + launch_review.review.requested_permissions[0] + .impact_if_disabled + .as_deref(), + Some("Launching from the plugin is unavailable") + ); + + service + .bundle_import_confirm_publisher(&review.token, &review.bundle.publisher_fingerprint) + .await + .unwrap(); + + // A denial must name a reviewed component and an optional permission of that component. + for (denials, message) in [ + ( + vec![BundleComponentDeniedPermissions { + plugin_id: "org.example.other".into(), + denied_permission_ids: vec![], + }], + "not part of this bundle review", + ), + ( + vec![BundleComponentDeniedPermissions { + plugin_id: "org.example.dolphin".into(), + denied_permission_ids: vec!["provider.context.read".into()], + }], + "required permission", + ), + ( + vec![BundleComponentDeniedPermissions { + plugin_id: "org.example.dolphin".into(), + denied_permission_ids: vec!["files.read".into()], + }], + "not requested", + ), + ] { + let error = service + .bundle_import_install(&review.token, false, &denials) + .await + .unwrap_err(); + assert!(error.contains(message), "{error}"); + assert!( + registry.active("org.example.dolphin").unwrap().is_none(), + "a rejected denial must not install anything" + ); + } + + let outcome = service + .bundle_import_install( + &review.token, + false, + &[ + BundleComponentDeniedPermissions { + plugin_id: "org.example.dolphin".into(), + denied_permission_ids: vec!["network.fetch".into()], + }, + BundleComponentDeniedPermissions { + plugin_id: "org.example.dolphin.launch".into(), + denied_permission_ids: vec!["game.launch".into()], + }, + ], + ) + .await + .unwrap(); + assert_eq!(outcome.components.len(), 2); + assert!( + outcome + .components + .iter() + .all(|component| component.permission_error.is_none()), + "{:?}", + outcome.components + ); + + let profile = api.providers.profiles().require().unwrap(); + let grants = state.open_grants(&profile).unwrap(); + let state_of = |plugin_id: &str, permission_id: &str| { + grants + .effective_grants(&PluginIdentity { + plugin_id: plugin_id.to_owned(), + publisher_fingerprint: review.bundle.publisher_fingerprint.clone(), + profile_id: profile.profile_id().to_owned(), + }) + .into_iter() + .find(|grant| grant.permission_id == permission_id) + .map(|grant| grant.state) + }; + assert_eq!( + state_of("org.example.dolphin", "provider.context.read"), + Some(PermissionState::Granted) + ); + assert_eq!( + state_of("org.example.dolphin", "storage.persist"), + Some(PermissionState::Granted) + ); + assert_eq!( + state_of("org.example.dolphin", "network.fetch"), + Some(PermissionState::Denied) + ); + assert_eq!( + state_of("org.example.dolphin.launch", "game.launch"), + Some(PermissionState::Denied) + ); + } + + /// An unavailable component is installed without an active pointer, so its denial is reported + /// for that component while the compatible sibling still receives its reviewed grants. + #[tokio::test] + async fn bundle_import_install_reports_a_denial_for_an_inactive_component() { + let fixture = Fixture::new(); + let provider = fixture.component_with_permissions( + "provider", + "provider", + "org.example.dolphin", + "0.1.0", + "linux", + "gnu", + "1.6.0", + vec![serde_json::json!({ + "id": "storage.persist", "required": false, "scope": "own-provider", + "reason": "Store plugin preferences" + })], + ); + // No Windows target matches the Linux host, so this component installs unavailable. + let launch = fixture.component_with_permissions( + "launch", + "extension", + "org.example.dolphin.launch", + "0.2.0", + "windows", + "msvc", + "1.6.0", + vec![serde_json::json!({ + "id": "game.launch", "required": false, + "scope": "approved-game-session", "reason": "Launch a game" + })], + ); + let bundle = fixture.bundle(&[&provider, &launch]); + + let paths = DataPaths::at(fixture.dir.path().join("app-data")); + let api = PluginApi::default(); + let state = PluginStateLayout::managed(&paths); + api.set_state_layout(state.clone()); + api.providers + .profiles() + .update(Some("bundle-account"), true); + let registry = PluginPackageRegistry::open(&paths).unwrap(); + let service = review_service(&api, &paths, &state, ®istry); + let settings = + SqliteSettingsStore::open(&fixture.dir.path().join("bundles.sqlite3")).unwrap(); + service.set_bundle_store(settings.bundle_store()); + + let review = service.bundle_import_review(bundle).await.unwrap(); + service + .bundle_import_confirm_publisher(&review.token, &review.bundle.publisher_fingerprint) + .await + .unwrap(); + let outcome = service + .bundle_import_install( + &review.token, + false, + &[BundleComponentDeniedPermissions { + plugin_id: "org.example.dolphin.launch".into(), + denied_permission_ids: vec!["game.launch".into()], + }], + ) + .await + .unwrap(); + let installed_provider = outcome + .components + .iter() + .find(|component| component.plugin_id == "org.example.dolphin") + .expect("the provider installed"); + assert!(installed_provider.active); + assert!(installed_provider.permission_error.is_none()); + let installed_launch = outcome + .components + .iter() + .find(|component| component.plugin_id == "org.example.dolphin.launch") + .expect("the unavailable component is still listed"); + assert!(!installed_launch.active); + assert!( + installed_launch + .permission_error + .as_deref() + .is_some_and(|error| error.contains("not active")), + "{installed_launch:?}" + ); + assert!( + serde_json::to_value(installed_launch).unwrap()["permissionError"] + .as_str() + .is_some_and(|error| error.contains("not active")), + "the IPC boundary names the per-component failure" + ); + + let profile = api.providers.profiles().require().unwrap(); + let grants = state.open_grants(&profile).unwrap(); + assert!( + grants + .effective_grants(&PluginIdentity { + plugin_id: "org.example.dolphin".into(), + publisher_fingerprint: review.bundle.publisher_fingerprint.clone(), + profile_id: profile.profile_id().to_owned(), + }) + .iter() + .any(|grant| grant.permission_id == "storage.persist" + && grant.state == PermissionState::Granted), + "the compatible sibling keeps its reviewed grants" + ); + } + + #[tokio::test] + async fn a_component_failure_rolls_back_and_keeps_the_previous_installation() { + let fixture = Fixture::new(); + let provider = fixture.component( + "provider", + "provider", + "org.example.dolphin", + "0.1.0", + "linux", + "gnu", + "1.6.0", + ); + // The bundle's extension version is installed standalone but inactive, while an older + // standalone version is active. Adoption only claims the active version, so publishing the + // bundle's version collides with the installed immutable version path. + let launch = fixture.component( + "launch", + "extension", + "org.example.dolphin.launch", + "0.2.0", + "linux", + "gnu", + "1.6.0", + ); + let launch_previous = fixture.component( + "launch-previous", + "extension", + "org.example.dolphin.launch", + "0.1.9", + "linux", + "gnu", + "1.6.0", + ); + let bundle = fixture.bundle(&[&provider, &launch]); + let report = inspect_bundle_candidate(&bundle, EmulationPolicy::RequireNative) + .await + .unwrap(); + let key = fixture.base64_key(); + let (registry, settings) = install_target(&fixture); + + let staged_previous = fixture.dir.path().join("standalone-launch-previous"); + stage_package_archive(&launch_previous, &staged_previous, &key).unwrap(); + let previous = registry + .install_signed( + "org.example.dolphin.launch", + "0.1.9", + &staged_previous, + &key, + true, + ) + .unwrap(); + let staged = fixture.dir.path().join("standalone-launch"); + stage_package_archive(&launch, &staged, &key).unwrap(); + registry + .install_signed("org.example.dolphin.launch", "0.2.0", &staged, &key, false) + .unwrap(); + assert_eq!( + registry.active("org.example.dolphin.launch").unwrap(), + Some(previous.clone()) + ); + + let result = install_bundle_candidate( + &bundle, + report, + registry.clone(), + settings.bundle_store(), + EmulationPolicy::RequireNative, + 1_700_000_000, + ) + .await; + assert!( + matches!( + result, + Err(BundleInstallError::Component { ref plugin_id, .. }) + if plugin_id == "org.example.dolphin.launch" + ), + "{result:?}" + ); + + // The provider was published before the failure and is rolled back completely. + assert!(registry.versions("org.example.dolphin").unwrap().is_empty()); + assert!(registry.active("org.example.dolphin").unwrap().is_none()); + // Both standalone versions are untouched and the previous one is still active. + assert_eq!( + registry + .versions("org.example.dolphin.launch") + .unwrap() + .iter() + .map(|installed| installed.version.as_str()) + .collect::>(), + vec!["0.1.9", "0.2.0"] + ); + assert_eq!( + registry.active("org.example.dolphin.launch").unwrap(), + Some(previous.clone()) + ); + assert_eq!( + registry + .verify_active_package("org.example.dolphin.launch", &key) + .unwrap(), + Some(previous) + ); + // No bundle mapping survives the failed install. + let store = settings.bundle_store(); + assert_eq!(store.bundle("org.example.dolphin").unwrap(), None); + assert_eq!( + store.bundle_for_plugin("org.example.dolphin").unwrap(), + None + ); + } + + #[tokio::test] + async fn a_standalone_component_with_the_same_publisher_is_adopted() { + let fixture = Fixture::new(); + let provider = fixture.component( + "provider", + "provider", + "org.example.dolphin", + "0.1.0", + "linux", + "gnu", + "1.6.0", + ); + let launch = fixture.component( + "launch", + "extension", + "org.example.dolphin.launch", + "0.2.0", + "linux", + "gnu", + "1.6.0", + ); + let bundle = fixture.bundle(&[&provider, &launch]); + let report = inspect_bundle_candidate(&bundle, EmulationPolicy::RequireNative) + .await + .unwrap(); + let key = fixture.base64_key(); + let (registry, settings) = install_target(&fixture); + + // The extension was imported standalone first and is the active installation. + let staged = fixture.dir.path().join("standalone-launch"); + stage_package_archive(&launch, &staged, &key).unwrap(); + let previous = registry + .install_signed("org.example.dolphin.launch", "0.2.0", &staged, &key, true) + .unwrap(); + assert_eq!( + registry.active("org.example.dolphin.launch").unwrap(), + Some(previous.clone()) + ); + + let installed = install_bundle_candidate( + &bundle, + report.clone(), + registry.clone(), + settings.bundle_store(), + EmulationPolicy::RequireNative, + 1_700_000_000, + ) + .await + .unwrap(); + assert_eq!(installed.components.len(), 2); + + // Adoption must not publish a second version or move the active pointer. + assert_eq!( + registry.versions("org.example.dolphin.launch").unwrap(), + vec![previous.clone()] + ); + assert_eq!( + registry.active("org.example.dolphin.launch").unwrap(), + Some(previous.clone()) + ); + assert_eq!( + registry + .verify_active_package("org.example.dolphin.launch", &key) + .unwrap(), + Some(previous) + ); + + // The provider was newly installed and activated. + assert_eq!( + registry + .active("org.example.dolphin") + .unwrap() + .unwrap() + .version, + "0.1.0" + ); + + // The mapping records the existing version and the bundle's declared component hash. + let recorded = settings + .bundle_store() + .bundle("org.example.dolphin") + .unwrap() + .expect("the mapping is stored"); + let launch_record = recorded + .components + .iter() + .find(|component| component.plugin_id == "org.example.dolphin.launch") + .expect("the adopted component is mapped"); + assert_eq!(launch_record.package_version, "0.2.0"); + assert_eq!( + launch_record.component_sha256, + component(&report, "org.example.dolphin.launch").sha256 + ); + } + + #[tokio::test] + async fn a_component_from_another_publisher_aborts_before_any_write() { + // The standalone installation is signed by the first publisher. + let installed_fixture = Fixture::new(); + let standalone_launch = installed_fixture.component( + "launch", + "extension", + "org.example.dolphin.launch", + "0.2.0", + "linux", + "gnu", + "1.6.0", + ); + + // The bundle and both of its components are signed by a different publisher. + let bundle_fixture = Fixture::new(); + let provider = bundle_fixture.component( + "provider", + "provider", + "org.example.dolphin", + "0.1.0", + "linux", + "gnu", + "1.6.0", + ); + let launch = bundle_fixture.component( + "launch", + "extension", + "org.example.dolphin.launch", + "0.2.0", + "linux", + "gnu", + "1.6.0", + ); + let bundle = bundle_fixture.bundle(&[&provider, &launch]); + let report = inspect_bundle_candidate(&bundle, EmulationPolicy::RequireNative) + .await + .unwrap(); + let key = installed_fixture.base64_key(); + let (registry, settings) = install_target(&installed_fixture); + + let staged = installed_fixture.dir.path().join("standalone-launch"); + stage_package_archive(&standalone_launch, &staged, &key).unwrap(); + let previous = registry + .install_signed("org.example.dolphin.launch", "0.2.0", &staged, &key, true) + .unwrap(); + + let result = install_bundle_candidate( + &bundle, + report, + registry.clone(), + settings.bundle_store(), + EmulationPolicy::RequireNative, + 1_700_000_000, + ) + .await; + assert!( + matches!( + result, + Err(BundleInstallError::PublisherConflict { ref plugin_id }) + if plugin_id == "org.example.dolphin.launch" + ), + "{result:?}" + ); + + // The conflict is detected before the provider is published, and the existing + // installation is untouched. + assert!(registry.versions("org.example.dolphin").unwrap().is_empty()); + assert!(registry.active("org.example.dolphin").unwrap().is_none()); + assert_eq!( + registry.versions("org.example.dolphin.launch").unwrap(), + vec![previous.clone()] + ); + assert_eq!( + registry.active("org.example.dolphin.launch").unwrap(), + Some(previous.clone()) + ); + assert_eq!( + registry + .verify_active_package("org.example.dolphin.launch", &key) + .unwrap(), + Some(previous) + ); + let store = settings.bundle_store(); + assert_eq!(store.bundle("org.example.dolphin").unwrap(), None); + assert_eq!( + store + .bundle_for_plugin("org.example.dolphin.launch") + .unwrap(), + None + ); + } + + #[tokio::test] + async fn a_failure_after_adoption_rolls_back_only_the_created_component() { + let fixture = Fixture::new(); + let provider = fixture.component( + "provider", + "provider", + "org.example.dolphin", + "0.1.0", + "linux", + "gnu", + "1.6.0", + ); + let launch = fixture.component( + "launch", + "extension", + "org.example.dolphin.launch", + "0.2.0", + "linux", + "gnu", + "1.6.0", + ); + let bundle = fixture.bundle(&[&provider, &launch]); + let report = inspect_bundle_candidate(&bundle, EmulationPolicy::RequireNative) + .await + .unwrap(); + let key = fixture.base64_key(); + let (registry, settings) = install_target(&fixture); + + let staged = fixture.dir.path().join("standalone-launch"); + stage_package_archive(&launch, &staged, &key).unwrap(); + let previous = registry + .install_signed("org.example.dolphin.launch", "0.2.0", &staged, &key, true) + .unwrap(); + + // Occupy the bundle id with an unrelated mapping so the mapping write fails only after the + // provider was installed and the extension was adopted. + let store = settings.bundle_store(); + let existing = BundleRecord { + bundle_id: "org.example.dolphin".to_owned(), + name: "Existing mapping".to_owned(), + version: "9.9.9".to_owned(), + publisher_fingerprint: "sha256:existing".to_owned(), + manifest_sha256: "b".repeat(64), + installed_at: 1, + components: vec![BundleComponentRecord { + plugin_id: "org.example.other".to_owned(), + kind: "provider".to_owned(), + component_sha256: "c".repeat(64), + package_version: "1.0.0".to_owned(), + }], + }; + store.record_bundle(&existing).unwrap(); + + let result = install_bundle_candidate( + &bundle, + report, + registry.clone(), + settings.bundle_store(), + EmulationPolicy::RequireNative, + 1_700_000_000, + ) + .await; + assert!( + matches!(result, Err(BundleInstallError::Mapping(_))), + "{result:?}" + ); + + // The provider this call created is rolled back. + assert!(registry.versions("org.example.dolphin").unwrap().is_empty()); + assert!(registry.active("org.example.dolphin").unwrap().is_none()); + // The adopted extension keeps its version, active pointer and verifiable payload. + assert_eq!( + registry.versions("org.example.dolphin.launch").unwrap(), + vec![previous.clone()] + ); + assert_eq!( + registry.active("org.example.dolphin.launch").unwrap(), + Some(previous.clone()) + ); + assert_eq!( + registry + .verify_active_package("org.example.dolphin.launch", &key) + .unwrap(), + Some(previous) + ); + // The pre-existing mapping is unchanged and the bundle did not claim any component. + assert_eq!(store.bundle("org.example.dolphin").unwrap(), Some(existing)); + assert_eq!( + store + .bundle_for_plugin("org.example.dolphin.launch") + .unwrap(), + None + ); + } + + #[tokio::test] + async fn a_component_already_mapped_to_another_bundle_is_an_explicit_conflict() { + let fixture = Fixture::new(); + let provider = fixture.component( + "provider", + "provider", + "org.example.dolphin", + "0.1.0", + "linux", + "gnu", + "1.6.0", + ); + let launch = fixture.component( + "launch", + "extension", + "org.example.dolphin.launch", + "0.2.0", + "linux", + "gnu", + "1.6.0", + ); + let bundle = fixture.bundle(&[&provider, &launch]); + let report = inspect_bundle_candidate(&bundle, EmulationPolicy::RequireNative) + .await + .unwrap(); + let (registry, settings) = install_target(&fixture); + let store = settings.bundle_store(); + let other = BundleRecord { + bundle_id: "org.example.other-bundle".to_owned(), + name: "Other bundle".to_owned(), + version: "1.0.0".to_owned(), + publisher_fingerprint: "sha256:other".to_owned(), + manifest_sha256: "d".repeat(64), + installed_at: 2, + components: vec![BundleComponentRecord { + plugin_id: "org.example.dolphin.launch".to_owned(), + kind: "extension".to_owned(), + component_sha256: "e".repeat(64), + package_version: "0.1.0".to_owned(), + }], + }; + store.record_bundle(&other).unwrap(); + + let result = install_bundle_candidate( + &bundle, + report, + registry.clone(), + settings.bundle_store(), + EmulationPolicy::RequireNative, + 1_700_000_000, + ) + .await; + assert!( + matches!( + result, + Err(BundleInstallError::BundleConflict { + ref plugin_id, + ref bundle_id, + }) if plugin_id == "org.example.dolphin.launch" + && bundle_id == "org.example.other-bundle" + ), + "{result:?}" + ); + + // Nothing is installed and the other mapping still owns its component. + assert!(registry.versions("org.example.dolphin").unwrap().is_empty()); + assert!(registry.active("org.example.dolphin").unwrap().is_none()); + assert_eq!(store.bundle("org.example.dolphin").unwrap(), None); + assert_eq!( + store.bundle("org.example.other-bundle").unwrap(), + Some(other) + ); + } + + #[tokio::test] + async fn an_unavailable_component_is_installed_but_left_inactive() { + let fixture = Fixture::new(); + let provider = fixture.component( + "provider", + "provider", + "org.example.dolphin", + "0.1.0", + "linux", + "gnu", + "1.6.0", + ); + let launch = fixture.component( + "launch", + "extension", + "org.example.dolphin.launch", + "0.2.0", + "windows", + "msvc", + "1.6.0", + ); + let bundle = fixture.bundle(&[&provider, &launch]); + let report = inspect_bundle_candidate(&bundle, EmulationPolicy::RequireNative) + .await + .unwrap(); + let (registry, settings) = install_target(&fixture); + + let installed = install_bundle_candidate( + &bundle, + report, + registry.clone(), + settings.bundle_store(), + EmulationPolicy::RequireNative, + 1_700_000_000, + ) + .await + .unwrap(); + + assert!(installed.components[0].active); + assert!(!installed.components[1].active); + assert_eq!( + registry + .active("org.example.dolphin") + .unwrap() + .unwrap() + .version, + "0.1.0" + ); + assert!( + registry + .active("org.example.dolphin.launch") + .unwrap() + .is_none() + ); + assert_eq!( + registry + .versions("org.example.dolphin.launch") + .unwrap() + .iter() + .map(|installed| installed.version.as_str()) + .collect::>(), + vec!["0.2.0"] + ); + assert_eq!( + settings + .bundle_store() + .bundle("org.example.dolphin") + .unwrap() + .expect("the mapping is stored") + .components + .len(), + 2 + ); + } + + fn permission(id: &str, scope: &str) -> serde_json::Value { + serde_json::json!({ + "id": id, + "required": false, + "scope": scope, + "reason": "Signed fixture permission" + }) + } + + #[tokio::test] + async fn an_installed_bundle_is_one_inventory_entry_with_each_component_status() { + let fixture = Fixture::new(); + let provider = fixture.component( + "provider", + "provider", + "org.example.dolphin", + "0.1.0", + "linux", + "gnu", + "1.6.0", + ); + // The extension installs on this Linux host but no extension runtime is available, so its + // component status is `unavailable` while the provider stays usable. + let launch = fixture.component( + "launch", + "extension", + "org.example.dolphin.launch", + "0.2.0", + "linux", + "gnu", + "1.6.0", + ); + let standalone = fixture.component( + "standalone", + "provider", + "org.example.standalone", + "0.3.0", + "linux", + "gnu", + "1.6.0", + ); + let bundle = fixture.bundle(&[&provider, &launch]); + + let paths = DataPaths::at(fixture.dir.path().join("app-data")); + let api = PluginApi::default(); + let state = PluginStateLayout::managed(&paths); + api.set_state_layout(state.clone()); + let profiles = api.providers.profiles(); + profiles.update(Some("bundle-account"), true); + let registry = PluginPackageRegistry::open(&paths).unwrap(); + let service = review_service(&api, &paths, &state, ®istry); + let settings = SqliteSettingsStore::open(&paths.database_file()).unwrap(); + service.set_bundle_store(settings.bundle_store()); + + let report = inspect_bundle_candidate(&bundle, EmulationPolicy::RequireNative) + .await + .unwrap(); + install_bundle_candidate( + &bundle, + report, + registry.clone(), + settings.bundle_store(), + EmulationPolicy::RequireNative, + 1_700_000_000, + ) + .await + .unwrap(); + + // A standalone package with the same publisher stays one entry and carries no bundle + // fields, so grouping can never absorb an unrelated install. + let key = fixture.base64_key(); + let staged = fixture.dir.path().join("standalone-stage"); + stage_package_archive(&standalone, &staged, &key).unwrap(); + registry + .install_signed("org.example.standalone", "0.3.0", &staged, &key, true) + .unwrap(); + let fingerprint = publisher_trust::key_fingerprint(&key); + publisher_trust::PublisherTrustStore::open(state.trust_dir()) + .unwrap() + .confirm_publishers(&["org.example.standalone".to_owned()], &key, &fingerprint) + .unwrap(); + + // The inventory only reports publisher-pinned packages, exactly as after one review. + let review = service.bundle_import_review(bundle).await.unwrap(); + service + .bundle_import_confirm_publisher(&review.token, &review.bundle.publisher_fingerprint) + .await + .unwrap(); + + let inventory = service.managed_inventory().await.unwrap(); + assert_eq!(inventory.len(), 2, "{inventory:#?}"); + let entry = inventory + .iter() + .find(|plugin| plugin.plugin_id == "org.example.dolphin") + .expect("the bundle is one entry keyed by its bundle id"); + assert_eq!(entry.plugin_kind, "bundle"); + assert_eq!(entry.name, "Dolphin GameCube and Wii"); + assert_eq!(entry.version, "0.1.0"); + assert_eq!(entry.bundle_id.as_deref(), Some("org.example.dolphin")); + assert_eq!( + entry.bundle_name.as_deref(), + Some("Dolphin GameCube and Wii") + ); + assert_eq!( + entry.bundle_publisher_fingerprint.as_deref(), + Some(review.bundle.publisher_fingerprint.as_str()) + ); + assert_eq!(entry.status, "installed"); + // The bundle itself is never a single manageable component. + assert!(entry.publisher_fingerprint.is_none()); + let components = entry + .bundle_components + .as_ref() + .expect("the entry carries its components"); + assert_eq!(components.len(), 2); + let provider_component = components + .iter() + .find(|component| component.plugin_id == "org.example.dolphin") + .unwrap(); + assert_eq!(provider_component.plugin_kind, "provider"); + assert_eq!(provider_component.version, "0.1.0"); + assert_eq!(provider_component.status, "installed"); + assert_eq!(provider_component.runtime_available, Some(true)); + let launch_component = components + .iter() + .find(|component| component.plugin_id == "org.example.dolphin.launch") + .unwrap(); + assert_eq!(launch_component.plugin_kind, "extension"); + assert_eq!(launch_component.version, "0.2.0"); + assert_eq!(launch_component.status, "unavailable"); + assert_eq!(launch_component.runtime_available, Some(false)); + assert!(components.iter().all(|component| { + component.publisher_fingerprint.as_deref() == Some(fingerprint.as_str()) + })); + + let standalone_entry = inventory + .iter() + .find(|plugin| plugin.plugin_id == "org.example.standalone") + .expect("the standalone package keeps its own entry"); + assert_eq!(standalone_entry.plugin_kind, "provider"); + assert_eq!(standalone_entry.name, "org.example.standalone fixture"); + assert_eq!(standalone_entry.version, "0.3.0"); + assert!(standalone_entry.bundle_id.is_none()); + assert!(standalone_entry.bundle_name.is_none()); + assert!(standalone_entry.bundle_components.is_none()); + } + + #[tokio::test] + async fn an_accepted_bundle_import_registers_and_enables_its_components_without_a_restart() { + let fixture = Fixture::new(); + let provider = fixture.component( + "provider", + "provider", + "org.example.dolphin", + "0.1.0", + "linux", + "gnu", + "1.6.0", + ); + let launch = fixture.component_with_permissions( + "launch", + "extension", + "org.example.dolphin.launch", + "0.2.0", + "linux", + "gnu", + "1.6.0", + vec![permission("game.launch", "selected game")], + ); + let bundle = fixture.bundle(&[&provider, &launch]); + + let paths = DataPaths::at(fixture.dir.path().join("app-data")); + let api = PluginApi::default(); + let state = PluginStateLayout::managed(&paths); + api.set_state_layout(state.clone()); + api.providers + .profiles() + .update(Some("bundle-account"), true); + let registry = PluginPackageRegistry::open(&paths).unwrap(); + let settings = SqliteSettingsStore::open(&paths.database_file()).unwrap(); + let service = bundle_service(&api, &paths, &state, ®istry, &settings); + + let review = service.bundle_import_review(bundle).await.unwrap(); + assert_eq!(review.components.len(), 2); + service + .bundle_import_confirm_publisher(&review.token, &review.bundle.publisher_fingerprint) + .await + .unwrap(); + let outcome = service + .bundle_import_install(&review.token, false, &[]) + .await + .unwrap(); + assert_eq!(outcome.components.len(), 2); + + let provider_outcome = outcome + .components + .iter() + .find(|component| component.plugin_id == "org.example.dolphin") + .unwrap(); + // The inert provider fixture cannot start; it stays installed and reports the error. + assert!(provider_outcome.active); + assert!(!provider_outcome.activated); + assert!(provider_outcome.activation_error.is_some()); + let launch_outcome = outcome + .components + .iter() + .find(|component| component.plugin_id == "org.example.dolphin.launch") + .unwrap(); + assert!( + launch_outcome.activated, + "{:?}", + launch_outcome.activation_error + ); + assert_eq!(launch_outcome.kind, "extension"); + + // The same host registers both packages and composes the extension slot immediately. + let lifecycle = service.lifecycle().unwrap(); + assert!(lifecycle.is_registered("org.example.dolphin")); + assert!(lifecycle.is_registered("org.example.dolphin.launch")); + assert!(lifecycle.extension_runtime_available("org.example.dolphin.launch")); + assert!( + lifecycle + .enabled("org.example.dolphin.launch".into()) + .await + .unwrap() + ); + + let inventory = service.managed_inventory().await.unwrap(); + let bundle_entry = inventory + .iter() + .find(|plugin| plugin.plugin_kind == "bundle") + .expect("the installed bundle is one inventory entry"); + let components = bundle_entry + .bundle_components + .as_ref() + .expect("the bundle entry carries its components"); + let launch_component = components + .iter() + .find(|component| component.plugin_id == "org.example.dolphin.launch") + .unwrap(); + assert_eq!(launch_component.status, "installed"); + assert_eq!(launch_component.runtime_available, Some(true)); + assert_eq!(launch_component.enabled, Some(true)); + let provider_component = components + .iter() + .find(|component| component.plugin_id == "org.example.dolphin") + .unwrap(); + assert_eq!(provider_component.status, "installed"); + assert_eq!(provider_component.runtime_available, Some(true)); + } + + /// A service with an authenticated profile and the same registry and state the fixtures + /// install into, matching application startup before the hosted providers are composed. + fn review_service( + api: &PluginApi, + paths: &DataPaths, + state: &PluginStateLayout, + registry: &PluginPackageRegistry, + ) -> PluginUpdateService { + let service = PluginUpdateService::open(paths).unwrap(); + let processes = ProviderProcesses::new_for_lifecycle( + api.providers.clone(), + paths.data_dir().join("plugins.sock"), + vec![], + state.clone(), + ) + .unwrap(); + service.set_lifecycle(Arc::new(ThirdPartyPluginLifecycle::new( + api.providers.clone(), + processes, + state.clone(), + registry.clone(), + ManagedPackageLifecycle::new(registry.clone()), + ))); + service.set_profiles(api.providers.profiles()); + service + } + + /// The same service with the application's bundle mapping, so bundle inventory, update review + /// and uninstall observe the rows the tests installed through the platform store. + fn bundle_service( + api: &PluginApi, + paths: &DataPaths, + state: &PluginStateLayout, + registry: &PluginPackageRegistry, + settings: &SqliteSettingsStore, + ) -> PluginUpdateService { + let service = review_service(api, paths, state, registry); + service.set_bundle_store(settings.bundle_store()); + service + } + + fn decision(snapshot: &PluginPermissionSnapshot, granted: bool) -> PermissionDecision { + let request = &snapshot.requested_permissions[0]; + PermissionDecision { + permission_id: request.permission_id.clone(), + scope: request.allowed_scopes.iter().next().unwrap().clone(), + granted, + } + } + + fn submission( + snapshot: &PluginPermissionSnapshot, + revision: u64, + granted: bool, + ) -> BundleComponentPermissionSubmission { + BundleComponentPermissionSubmission { + plugin_id: snapshot.plugin_id.clone(), + expected_profile_id: snapshot.profile_id.clone(), + expected_publisher_fingerprint: snapshot.publisher_fingerprint.clone(), + expected_revision: revision, + decisions: vec![decision(snapshot, granted)], + } + } + + #[tokio::test] + async fn bundle_review_groups_both_components_and_one_confirmation_pins_the_publisher() { + let fixture = Fixture::new(); + let provider = fixture.component_with_permissions( + "provider", + "provider", + "org.example.dolphin", + "0.1.0", + "linux", + "gnu", + "1.6.0", + vec![permission("storage.persist", "own-provider")], + ); + let launch = fixture.component_with_permissions( + "launch", + "extension", + "org.example.dolphin.launch", + "0.2.0", + "linux", + "gnu", + "1.6.0", + vec![permission("game.launch", "approved-game-session")], + ); + let bundle = fixture.bundle(&[&provider, &launch]); + + let paths = DataPaths::at(fixture.dir.path().join("app-data")); + let api = PluginApi::default(); + let state = PluginStateLayout::managed(&paths); + api.set_state_layout(state.clone()); + let profiles = api.providers.profiles(); + profiles.update(Some("bundle-account"), true); + let registry = PluginPackageRegistry::open(&paths).unwrap(); + let service = review_service(&api, &paths, &state, ®istry); + let profile = profiles.require().unwrap(); + + // The fixture entrypoints are inert placeholder bytes, so a successful review also shows + // that no component code ran to produce it. + let review = service.bundle_import_review(bundle).await.unwrap(); + assert_eq!(review.bundle.id, "org.example.dolphin"); + assert_eq!(review.bundle.name, "Dolphin GameCube and Wii"); + assert_eq!(review.bundle.version, "0.1.0"); + assert_eq!(review.bundle.publisher_key_id, "dolphin-dev"); + assert_eq!( + review.bundle.publisher_fingerprint, + publisher_trust::key_fingerprint(&fixture.base64_key()) + ); + assert_eq!(review.trust, "untrusted"); + assert_eq!(review.pinned_fingerprint, None); + assert_eq!(review.license.expressions, vec!["MIT".to_owned()]); + assert_eq!(review.license.components.len(), 2); + + assert_eq!(review.components.len(), 2); + let provider = review + .components + .iter() + .find(|component| component.review.plugin_id == "org.example.dolphin") + .expect("the provider is grouped by its own identity"); + assert_eq!(provider.kind, "provider"); + assert_eq!( + provider.availability, + BundleComponentAvailability::Available + ); + assert_eq!(provider.review.version, "0.1.0"); + assert_eq!(provider.review.publisher_key_id, "dolphin-dev"); + assert_eq!( + provider.review.publisher_fingerprint, + review.bundle.publisher_fingerprint + ); + assert_eq!(provider.review.permission_ids, vec!["storage.persist"]); + assert_eq!( + provider.review.requested_permissions[0].scope, + "own-provider" + ); + assert_eq!(provider.review.license, "MIT"); + assert_eq!( + provider.review.license_files, + vec!["licenses/LICENSE".to_owned()] + ); + assert!(provider.review.native_access.is_empty()); + assert_eq!(provider.review.compatibility, "compatible"); + assert_eq!( + provider.review.compatibility_details.state, + CompatibilityState::Compatible + ); + let launch = review + .components + .iter() + .find(|component| component.review.plugin_id == "org.example.dolphin.launch") + .expect("the extension is grouped by its own identity"); + assert_eq!(launch.kind, "extension"); + assert_eq!(launch.availability, BundleComponentAvailability::Available); + assert_eq!(launch.review.permission_ids, vec!["game.launch"]); + + // Reviewing and confirming is not consent: no grant record exists for either component. + assert!(state.open_grants(&profile).unwrap().identities().is_empty()); + + // A mismatched confirmation pins nothing; the exact displayed fingerprint pins both + // components in one decision. + assert!( + service + .bundle_import_confirm_publisher( + &review.token, + &format!("SHA256:{}", "0".repeat(64)) + ) + .await + .is_err() + ); + let pinned = service + .bundle_import_confirm_publisher(&review.token, &review.bundle.publisher_fingerprint) + .await + .unwrap(); + assert_eq!(pinned.trust, "trusted"); + assert_eq!(pinned.pinned_fingerprint, None); + assert!( + pinned + .components + .iter() + .all(|component| component.review.trust == "trusted") + ); + let trust = publisher_trust::PublisherTrustStore::open(state.trust_dir()).unwrap(); + for plugin_id in ["org.example.dolphin", "org.example.dolphin.launch"] { + assert_eq!( + trust.inspect(plugin_id, &fixture.base64_key()).unwrap(), + publisher_trust::KeyStatus::Trusted { + fingerprint: review.bundle.publisher_fingerprint.clone() + } + ); + } + assert!(state.open_grants(&profile).unwrap().identities().is_empty()); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn grouped_bundle_permissions_isolate_a_denial_and_a_stale_revision() { + let fixture = Fixture::new(); + let provider = fixture.component_with_permissions( + "provider", + "provider", + "org.example.dolphin", + "0.1.0", + "linux", + "gnu", + "1.6.0", + vec![permission("storage.persist", "own-provider")], + ); + let launch = fixture.component_with_permissions( + "launch", + "extension", + "org.example.dolphin.launch", + "0.2.0", + "linux", + "gnu", + "1.6.0", + vec![permission("game.launch", "approved-game-session")], + ); + let bundle = fixture.bundle(&[&provider, &launch]); + + let paths = DataPaths::at(fixture.dir.path().join("app-data")); + let api = PluginApi::default(); + let state = PluginStateLayout::managed(&paths); + api.set_state_layout(state.clone()); + let profiles = api.providers.profiles(); + profiles.update(Some("bundle-account"), true); + let registry = PluginPackageRegistry::open(&paths).unwrap(); + let service = review_service(&api, &paths, &state, ®istry); + + let report = inspect_bundle_candidate(&bundle, EmulationPolicy::RequireNative) + .await + .unwrap(); + let settings = + SqliteSettingsStore::open(&fixture.dir.path().join("bundles.sqlite3")).unwrap(); + install_bundle_candidate( + &bundle, + report, + registry.clone(), + settings.bundle_store(), + EmulationPolicy::RequireNative, + 1_700_000_000, + ) + .await + .unwrap(); + + let review = service.bundle_import_review(bundle.clone()).await.unwrap(); + service + .bundle_import_confirm_publisher(&review.token, &review.bundle.publisher_fingerprint) + .await + .unwrap(); + + // The host registers only trusted active packages, exactly as it does at startup. + let store = SqliteSettingsStore::new(db::open(Path::new(":memory:")).unwrap()); + let library: Arc = + Arc::new(store.library_store()); + let endpoint = fixture.dir.path().join("plugins.sock"); + let host = HostedProviders::bundled( + api.providers.clone(), + Arc::new(Default::default()), + Some(endpoint.clone()), + paths.clone(), + library, + None, + ) + .await + .unwrap(); + let _server = + PluginApiServer::start(&tokio::runtime::Handle::current(), &endpoint, api.clone()) + .unwrap(); + service.set_lifecycle(host.lifecycle()); + + let provider_snapshot = service + .permission_snapshot("org.example.dolphin".into()) + .await + .unwrap(); + let launch_snapshot = service + .permission_snapshot("org.example.dolphin.launch".into()) + .await + .unwrap(); + for snapshot in [&provider_snapshot, &launch_snapshot] { + assert_eq!(snapshot.grant_revision, 0); + assert!(snapshot.effective_grants.is_empty()); + assert!(!snapshot.requested_permissions.is_empty()); + } + + // One grouped review: the provider is granted and the extension is denied. Denying one + // component neither grants it nor disturbs its sibling's record. + let first = service + .apply_bundle_permissions(vec![ + submission(&provider_snapshot, provider_snapshot.grant_revision, true), + submission(&launch_snapshot, launch_snapshot.grant_revision, false), + ]) + .await + .unwrap(); + assert_eq!(first.components.len(), 2); + assert!( + first + .components + .iter() + .all(|component| component.error.is_none()) + ); + let provider_saved = first.components[0] + .snapshot + .as_ref() + .expect("the provider decision was saved"); + let launch_saved = first.components[1] + .snapshot + .as_ref() + .expect("the denied component keeps its own record"); + assert_eq!( + provider_saved.effective_grants[0].state, + PermissionState::Granted + ); + assert_eq!( + launch_saved.effective_grants[0].state, + PermissionState::Denied + ); + assert_eq!(provider_saved.grant_revision, 1); + assert_eq!(launch_saved.grant_revision, 1); + + // A stale revision fails only the component that carries it. The sibling still saves and + // the stale component keeps its previous grant and revision. + let stale = service + .apply_bundle_permissions(vec![ + submission(provider_saved, provider_saved.grant_revision - 1, false), + submission(launch_saved, launch_saved.grant_revision, true), + ]) + .await + .unwrap(); + assert!( + stale.components[0] + .error + .as_deref() + .is_some_and(|error| error.contains("grants changed")), + "{:?}", + stale.components[0] + ); + assert!(stale.components[0].snapshot.is_none()); + let launch_updated = stale.components[1] + .snapshot + .as_ref() + .expect("the sibling decision still applies"); + assert_eq!( + launch_updated.effective_grants[0].state, + PermissionState::Granted + ); + assert_eq!(launch_updated.grant_revision, 2); + + let provider_after = service + .permission_snapshot("org.example.dolphin".into()) + .await + .unwrap(); + assert_eq!(provider_after.grant_revision, provider_saved.grant_revision); + assert_eq!( + provider_after.effective_grants[0].state, + PermissionState::Granted + ); + let launch_after = service + .permission_snapshot("org.example.dolphin.launch".into()) + .await + .unwrap(); + assert_eq!(launch_after.grant_revision, 2); + assert_eq!( + launch_after.effective_grants[0].state, + PermissionState::Granted + ); + } + + /// A running-profile update fixture: registry, mapping store, state and grant context that all + /// describe the same account, exactly as application startup composes them. + struct UpdateFixture { + fixture: Fixture, + paths: DataPaths, + api: PluginApi, + state: PluginStateLayout, + registry: PluginPackageRegistry, + settings: SqliteSettingsStore, + } + + impl UpdateFixture { + fn new() -> Self { + let fixture = Fixture::new(); + let paths = DataPaths::at(fixture.dir.path().join("app-data")); + fs::create_dir_all(paths.data_dir()).unwrap(); + let api = PluginApi::default(); + let state = PluginStateLayout::prepare_managed(&paths).unwrap(); + api.set_state_layout(state.clone()); + api.providers + .profiles() + .update(Some("bundle-account"), true); + let registry = PluginPackageRegistry::open(&paths).unwrap(); + let settings = + SqliteSettingsStore::open(&fixture.dir.path().join("bundles.sqlite3")).unwrap(); + Self { + fixture, + paths, + api, + state, + registry, + settings, + } + } + + fn service(&self) -> PluginUpdateService { + bundle_service( + &self.api, + &self.paths, + &self.state, + &self.registry, + &self.settings, + ) + } + + fn grants(&self) -> BundleGrantContext { + BundleGrantContext { + layout: self.state.clone(), + profiles: self.api.providers.profiles(), + } + } + + fn identity(&self, plugin_id: &str, publisher_fingerprint: &str) -> PluginIdentity { + PluginIdentity { + plugin_id: plugin_id.to_owned(), + publisher_fingerprint: publisher_fingerprint.to_owned(), + profile_id: self + .api + .providers + .profiles() + .current() + .expect("the fixture profile is signed in") + .profile_id() + .to_owned(), + } + } + + fn grant(&self, identity: &PluginIdentity, scope: &str) { + let scope = GrantScope::Declared { + value: scope.to_owned(), + }; + let request = PermissionRequest { + permission_id: gamenode_plugin_protocol::capability::NETWORK_FETCH.to_owned(), + required: false, + allowed_scopes: BTreeSet::from([scope.clone()]), + }; + let decision = PermissionDecision { + permission_id: gamenode_plugin_protocol::capability::NETWORK_FETCH.to_owned(), + scope, + granted: true, + }; + self.state + .open_grants(&self.api.providers.profiles().current().unwrap()) + .unwrap() + .replace_grants(identity.clone(), &[request], &[decision]) + .unwrap(); + } + } + + #[tokio::test] + async fn a_bundle_update_swaps_every_component_atomically_and_keeps_unchanged_grants() { + let update = UpdateFixture::new(); + let fixture = &update.fixture; + let provider_v1 = fixture.component_with_permissions( + "provider-v1", + "provider", + "org.example.dolphin", + "0.1.0", + "linux", + "gnu", + "1.6.0", + vec![permission("network.fetch", "https://api.example.com")], + ); + let launch_v1 = fixture.component_with_permissions( + "launch-v1", + "extension", + "org.example.dolphin.launch", + "0.2.0", + "linux", + "gnu", + "1.6.0", + vec![permission("game.launch", "approved-game-session")], + ); + let bundle_v1 = fixture.bundle(&[&provider_v1, &launch_v1]); + let report_v1 = inspect_bundle_candidate(&bundle_v1, EmulationPolicy::RequireNative) + .await + .unwrap(); + let installed = install_bundle_candidate( + &bundle_v1, + report_v1.clone(), + update.registry.clone(), + update.settings.bundle_store(), + EmulationPolicy::RequireNative, + 1_700_000_000, + ) + .await + .unwrap(); + + // One grant exists for the provider before the update. + let fingerprint = report_v1.bundle.publisher_fingerprint.clone(); + let provider_identity = update.identity("org.example.dolphin", &fingerprint); + update.grant(&provider_identity, "https://api.example.com"); + let revision_before = update + .state + .open_grants(&update.api.providers.profiles().current().unwrap()) + .unwrap() + .revision(&provider_identity); + + // The update keeps the provider's signed permission unchanged, moves the extension's scope + // and adds a new provider permission that must start ungranted. + let provider_v2 = fixture.component_with_permissions( + "provider-v2", + "provider", + "org.example.dolphin", + "0.2.0", + "linux", + "gnu", + "1.6.0", + vec![ + permission("network.fetch", "https://api.example.com"), + permission("library.write", "own-entries"), + ], + ); + let launch_v2 = fixture.component_with_permissions( + "launch-v2", + "extension", + "org.example.dolphin.launch", + "0.3.0", + "linux", + "gnu", + "1.6.0", + vec![permission("game.launch", "selected-game-session")], + ); + let bundle_v2 = fixture.bundle_version(&[&provider_v2, &launch_v2], "0.2.0"); + let report_v2 = inspect_bundle_candidate(&bundle_v2, EmulationPolicy::RequireNative) + .await + .unwrap(); + let stopper = RecordingStopper::default(); + + let outcome = apply_bundle_update( + &bundle_v2, + report_v2.clone(), + installed.bundle.clone(), + update.registry.clone(), + update.settings.bundle_store(), + &stopper, + update.grants(), + EmulationPolicy::RequireNative, + 1_700_000_100, + ) + .await + .unwrap(); + + assert_eq!(outcome.bundle_id, "org.example.dolphin"); + assert_eq!(outcome.previous_version, "0.1.0"); + assert_eq!(outcome.version, "0.2.0"); + assert!(outcome.components.iter().all(|component| component.active)); + assert_eq!( + stopper.stopped(), + vec!["org.example.dolphin", "org.example.dolphin.launch"] + ); + assert_eq!( + update + .registry + .active("org.example.dolphin") + .unwrap() + .map(|installed| installed.version), + Some("0.2.0".to_owned()) + ); + assert_eq!( + update + .registry + .active("org.example.dolphin.launch") + .unwrap() + .map(|installed| installed.version), + Some("0.3.0".to_owned()) + ); + let stored = update + .settings + .bundle_store() + .bundle("org.example.dolphin") + .unwrap() + .expect("the updated mapping is current"); + assert_eq!(stored.version, "0.2.0"); + assert_eq!( + stored + .components + .iter() + .map(|component| component.package_version.as_str()) + .collect::>(), + BTreeSet::from(["0.2.0", "0.3.0"]) + ); + assert_eq!( + update + .settings + .bundle_store() + .previous_versions("org.example.dolphin") + .unwrap(), + vec!["0.1.0".to_owned()] + ); + // The unchanged provider grant survives at the same revision; the new permission is not + // granted, and the extension's changed scope was narrowed away. + let grants = update + .state + .open_grants(&update.api.providers.profiles().current().unwrap()) + .unwrap(); + assert_eq!(grants.revision(&provider_identity), revision_before); + let effective = grants.effective_grants(&provider_identity); + assert_eq!(effective.len(), 1); + assert_eq!( + effective[0].permission_id, + gamenode_plugin_protocol::capability::NETWORK_FETCH + ); + let launch_identity = update.identity("org.example.dolphin.launch", &fingerprint); + assert!( + grants.effective_grants(&launch_identity).is_empty(), + "a changed scope is not widened or carried over" + ); + } + + #[tokio::test] + async fn a_failed_bundle_update_keeps_the_previous_set_and_removes_new_versions() { + let update = UpdateFixture::new(); + let fixture = &update.fixture; + let provider_v1 = fixture.component( + "provider-v1", + "provider", + "org.example.dolphin", + "0.1.0", + "linux", + "gnu", + "1.6.0", + ); + let launch_v1 = fixture.component_with_permissions( + "launch-v1", + "extension", + "org.example.dolphin.launch", + "0.2.0", + "linux", + "gnu", + "1.6.0", + vec![permission("game.launch", "approved-game-session")], + ); + let bundle_v1 = fixture.bundle(&[&provider_v1, &launch_v1]); + let report_v1 = inspect_bundle_candidate(&bundle_v1, EmulationPolicy::RequireNative) + .await + .unwrap(); + install_bundle_candidate( + &bundle_v1, + report_v1, + update.registry.clone(), + update.settings.bundle_store(), + EmulationPolicy::RequireNative, + 1_700_000_000, + ) + .await + .unwrap(); + + let provider_v2 = fixture.component( + "provider-v2", + "provider", + "org.example.dolphin", + "0.2.0", + "linux", + "gnu", + "1.6.0", + ); + let launch_v2 = fixture.component( + "launch-v2", + "extension", + "org.example.dolphin.launch", + "0.3.0", + "linux", + "gnu", + "1.6.0", + ); + let bundle_v2 = fixture.bundle_version(&[&provider_v2, &launch_v2], "0.2.0"); + let report_v2 = inspect_bundle_candidate(&bundle_v2, EmulationPolicy::RequireNative) + .await + .unwrap(); + // Remove the mapping behind the reviewed record, so the mapping write fails after every + // new component was installed and activated. + let reviewed_mapping = update + .settings + .bundle_store() + .bundle("org.example.dolphin") + .unwrap() + .unwrap(); + update + .settings + .bundle_store() + .remove_bundle("org.example.dolphin") + .unwrap(); + let stopper = RecordingStopper::default(); + + let result = apply_bundle_update( + &bundle_v2, + report_v2, + reviewed_mapping, + update.registry.clone(), + update.settings.bundle_store(), + &stopper, + update.grants(), + EmulationPolicy::RequireNative, + 1_700_000_100, + ) + .await; + assert!( + matches!(result, Err(BundleUpdateError::Mapping(_))), + "{result:?}" + ); + // The previous versions are active again and the new ones this call published are gone. + assert_eq!( + update + .registry + .active("org.example.dolphin") + .unwrap() + .map(|installed| installed.version), + Some("0.1.0".to_owned()) + ); + assert_eq!( + update + .registry + .active("org.example.dolphin.launch") + .unwrap() + .map(|installed| installed.version), + Some("0.2.0".to_owned()) + ); + assert!( + update + .registry + .versions("org.example.dolphin") + .unwrap() + .iter() + .all(|installed| installed.version == "0.1.0") + ); + assert!( + update + .registry + .versions("org.example.dolphin.launch") + .unwrap() + .iter() + .all(|installed| installed.version == "0.2.0") + ); + assert_eq!( + update + .settings + .bundle_store() + .previous_versions("org.example.dolphin") + .unwrap(), + Vec::::new() + ); + } + + #[tokio::test] + async fn rollback_restores_the_previous_bundle_versions_and_grants() { + let update = UpdateFixture::new(); + let fixture = &update.fixture; + let provider_v1 = fixture.component_with_permissions( + "provider-v1", + "provider", + "org.example.dolphin", + "0.1.0", + "linux", + "gnu", + "1.6.0", + vec![permission("network.fetch", "https://api.example.com")], + ); + let launch_v1 = fixture.component_with_permissions( + "launch-v1", + "extension", + "org.example.dolphin.launch", + "0.2.0", + "linux", + "gnu", + "1.6.0", + vec![permission("game.launch", "approved-game-session")], + ); + let bundle_v1 = fixture.bundle(&[&provider_v1, &launch_v1]); + let report_v1 = inspect_bundle_candidate(&bundle_v1, EmulationPolicy::RequireNative) + .await + .unwrap(); + let installed = install_bundle_candidate( + &bundle_v1, + report_v1.clone(), + update.registry.clone(), + update.settings.bundle_store(), + EmulationPolicy::RequireNative, + 1_700_000_000, + ) + .await + .unwrap(); + let fingerprint = report_v1.bundle.publisher_fingerprint.clone(); + let provider_identity = update.identity("org.example.dolphin", &fingerprint); + update.grant(&provider_identity, "https://api.example.com"); + let revision = update + .state + .open_grants(&update.api.providers.profiles().current().unwrap()) + .unwrap() + .revision(&provider_identity); + + let provider_v2 = fixture.component_with_permissions( + "provider-v2", + "provider", + "org.example.dolphin", + "0.2.0", + "linux", + "gnu", + "1.6.0", + vec![permission("network.fetch", "https://api.example.com")], + ); + let launch_v2 = fixture.component( + "launch-v2", + "extension", + "org.example.dolphin.launch", + "0.3.0", + "linux", + "gnu", + "1.6.0", + ); + let bundle_v2 = fixture.bundle_version(&[&provider_v2, &launch_v2], "0.2.0"); + let report_v2 = inspect_bundle_candidate(&bundle_v2, EmulationPolicy::RequireNative) + .await + .unwrap(); + let stopper = RecordingStopper::default(); + apply_bundle_update( + &bundle_v2, + report_v2, + installed.bundle.clone(), + update.registry.clone(), + update.settings.bundle_store(), + &stopper, + update.grants(), + EmulationPolicy::RequireNative, + 1_700_000_100, + ) + .await + .unwrap(); + + let rollback = rollback_bundle_version( + "org.example.dolphin", + "0.1.0", + update.registry.clone(), + update.settings.bundle_store(), + &stopper, + update.grants(), + EmulationPolicy::RequireNative, + 1_700_000_200, + ) + .await + .unwrap(); + + assert_eq!(rollback.previous_version, "0.2.0"); + assert_eq!(rollback.version, "0.1.0"); + assert_eq!( + update + .registry + .active("org.example.dolphin") + .unwrap() + .map(|installed| installed.version), + Some("0.1.0".to_owned()) + ); + assert_eq!( + update + .registry + .active("org.example.dolphin.launch") + .unwrap() + .map(|installed| installed.version), + Some("0.2.0".to_owned()) + ); + let stored = update + .settings + .bundle_store() + .bundle("org.example.dolphin") + .unwrap() + .unwrap(); + assert_eq!(stored.version, "0.1.0"); + assert_eq!( + stored + .components + .iter() + .map(|component| component.package_version.as_str()) + .collect::>(), + BTreeSet::from(["0.1.0", "0.2.0"]) + ); + // The unchanged grant is still there at the same revision; rollback never widens it. + let grants = update + .state + .open_grants(&update.api.providers.profiles().current().unwrap()) + .unwrap(); + assert_eq!(grants.revision(&provider_identity), revision); + assert_eq!(grants.effective_grants(&provider_identity).len(), 1); + // The replaced version is now the rollback target. + assert_eq!( + update + .settings + .bundle_store() + .previous_versions("org.example.dolphin") + .unwrap(), + vec!["0.2.0".to_owned()] + ); + } + + #[tokio::test] + async fn a_changed_bundle_archive_keeps_the_previous_set_active() { + let update = UpdateFixture::new(); + let fixture = &update.fixture; + let provider_v1 = fixture.component( + "provider-v1", + "provider", + "org.example.dolphin", + "0.1.0", + "linux", + "gnu", + "1.6.0", + ); + let launch_v1 = fixture.component( + "launch-v1", + "extension", + "org.example.dolphin.launch", + "0.2.0", + "linux", + "gnu", + "1.6.0", + ); + let bundle_v1 = fixture.bundle(&[&provider_v1, &launch_v1]); + let report_v1 = inspect_bundle_candidate(&bundle_v1, EmulationPolicy::RequireNative) + .await + .unwrap(); + let installed = install_bundle_candidate( + &bundle_v1, + report_v1, + update.registry.clone(), + update.settings.bundle_store(), + EmulationPolicy::RequireNative, + 1_700_000_000, + ) + .await + .unwrap(); + let provider_v2 = fixture.component( + "provider-v2", + "provider", + "org.example.dolphin", + "0.2.0", + "linux", + "gnu", + "1.6.0", + ); + let launch_v2 = fixture.component( + "launch-v2", + "extension", + "org.example.dolphin.launch", + "0.3.0", + "linux", + "gnu", + "1.6.0", + ); + let bundle_v2 = fixture.bundle_version(&[&provider_v2, &launch_v2], "0.2.0"); + let report_v2 = inspect_bundle_candidate(&bundle_v2, EmulationPolicy::RequireNative) + .await + .unwrap(); + // The reviewed archive changes on disk before approval. + let mut bytes = fs::read(&bundle_v2).unwrap(); + bytes.pop(); + fs::write(&bundle_v2, bytes).unwrap(); + + let stopper = RecordingStopper::default(); + let result = apply_bundle_update( + &bundle_v2, + report_v2, + installed.bundle, + update.registry.clone(), + update.settings.bundle_store(), + &stopper, + update.grants(), + EmulationPolicy::RequireNative, + 1_700_000_100, + ) + .await; + assert!(result.is_err(), "{result:?}"); + assert_eq!( + update + .registry + .active("org.example.dolphin") + .unwrap() + .map(|installed| installed.version), + Some("0.1.0".to_owned()) + ); + assert_eq!( + update + .registry + .active("org.example.dolphin.launch") + .unwrap() + .map(|installed| installed.version), + Some("0.2.0".to_owned()) + ); + assert!( + update + .registry + .versions("org.example.dolphin") + .unwrap() + .iter() + .all(|installed| installed.version == "0.1.0") + ); + assert_eq!( + update + .settings + .bundle_store() + .bundle("org.example.dolphin") + .unwrap() + .map(|bundle| bundle.version), + Some("0.1.0".to_owned()) + ); + } + + /// A signed update release for a real fixture bundle, bound to the bundle's manifest hash the + /// way the signed index carries it. + fn update_release(bundle: &Path, version: &str) -> UpdateRelease { + let verified = gamenode_platform::plugin_bundles::verify_bundle_archive(bundle).unwrap(); + UpdateRelease { + version: version.to_owned(), + targets: vec!["linux-x86_64-gnu".to_owned()], + api_range: ">=1.6.0, <2.0.0".to_owned(), + package_url: "https://updates.example/bundle.gnbundle".to_owned(), + package_size: 1, + package_sha256: "a".repeat(64), + bundle_sha256: Some(verified.manifest_sha256), + } + } + + #[tokio::test] + async fn a_bundle_update_review_carries_the_index_hash_and_per_component_diffs() { + let update = UpdateFixture::new(); + let fixture = &update.fixture; + let provider_v1 = fixture.component_with_permissions( + "provider-v1", + "provider", + "org.example.dolphin", + "0.1.0", + "linux", + "gnu", + "1.6.0", + vec![permission("network.fetch", "https://api.example.com")], + ); + let launch_v1 = fixture.component_with_permissions( + "launch-v1", + "extension", + "org.example.dolphin.launch", + "0.2.0", + "linux", + "gnu", + "1.6.0", + vec![permission("game.launch", "approved-game-session")], + ); + let bundle_v1 = fixture.bundle(&[&provider_v1, &launch_v1]); + let report_v1 = inspect_bundle_candidate(&bundle_v1, EmulationPolicy::RequireNative) + .await + .unwrap(); + let installed = install_bundle_candidate( + &bundle_v1, + report_v1, + update.registry.clone(), + update.settings.bundle_store(), + EmulationPolicy::RequireNative, + 1_700_000_000, + ) + .await + .unwrap(); + let service = update.service(); + + let provider_v2 = fixture.component_with_permissions( + "provider-v2", + "provider", + "org.example.dolphin", + "0.2.0", + "linux", + "gnu", + "1.6.0", + vec![ + permission("network.fetch", "https://api.example.com"), + permission("library.write", "own-entries"), + ], + ); + let launch_v2 = fixture.component_with_permissions( + "launch-v2", + "extension", + "org.example.dolphin.launch", + "0.3.0", + "linux", + "gnu", + "1.6.0", + vec![permission("game.launch", "selected-game-session")], + ); + let bundle_v2 = fixture.bundle_version(&[&provider_v2, &launch_v2], "0.2.0"); + let release = update_release(&bundle_v2, "0.2.0"); + let (review, report) = service + .bundle_update_review_from_archive(&installed.bundle, &release, &bundle_v2) + .await + .unwrap(); + assert_eq!(review.bundle_id, "org.example.dolphin"); + assert_eq!(review.installed_version, "0.1.0"); + assert_eq!(review.candidate_version, "0.2.0"); + assert_eq!( + Some(review.bundle_sha256.clone()), + release.bundle_sha256.clone() + ); + assert!(!review.is_downgrade); + assert!(review.requires_manual_approval); + assert_eq!(report.components.len(), 2); + let provider = review + .components + .iter() + .find(|component| component.plugin_id == "org.example.dolphin") + .unwrap(); + assert_eq!(provider.installed_version, "0.1.0"); + assert_eq!(provider.candidate_version, "0.2.0"); + assert_eq!(provider.kind, "provider"); + assert_eq!(provider.added_permissions, vec!["library.write".to_owned()]); + assert_eq!(provider.compatibility, "compatible"); + assert_eq!( + provider.availability, + BundleComponentAvailability::Available + ); + let launch = review + .components + .iter() + .find(|component| component.plugin_id == "org.example.dolphin.launch") + .unwrap(); + assert_eq!(launch.installed_version, "0.2.0"); + assert_eq!(launch.candidate_version, "0.3.0"); + assert_eq!(launch.changed_permissions, vec!["game.launch".to_owned()]); + assert_eq!(review.added_permissions, vec!["library.write".to_owned()]); + assert_eq!(review.changed_permissions, vec!["game.launch".to_owned()]); + + // A standalone release under a bundle review is a mixed update and is rejected before any + // archive is inspected or installed. + let mut package_release = release.clone(); + package_release.bundle_sha256 = None; + let error = service + .bundle_update_review_from_archive(&installed.bundle, &package_release, &bundle_v2) + .await + .expect_err("a package release is not a bundle update"); + assert!(error.contains("not a signed bundle"), "{error}"); + + // A release that adds a component is not the same product and is rejected. + let extra = fixture.component( + "extra", + "extension", + "org.example.dolphin.extra", + "0.1.0", + "linux", + "gnu", + "1.6.0", + ); + let bundle_v3 = fixture.bundle_version(&[&provider_v2, &launch_v2, &extra], "0.3.0"); + let release_v3 = update_release(&bundle_v3, "0.3.0"); + let error = service + .bundle_update_review_from_archive(&installed.bundle, &release_v3, &bundle_v3) + .await + .expect_err("a bundle update cannot change the component set"); + assert!(error.contains("add, remove or re-kind"), "{error}"); + } + + #[tokio::test] + async fn a_bundle_rollback_review_is_produced_before_the_confirmed_restore() { + let update = UpdateFixture::new(); + let fixture = &update.fixture; + let provider_v1 = fixture.component( + "provider-v1", + "provider", + "org.example.dolphin", + "0.1.0", + "linux", + "gnu", + "1.6.0", + ); + let launch_v1 = fixture.component_with_permissions( + "launch-v1", + "extension", + "org.example.dolphin.launch", + "0.2.0", + "linux", + "gnu", + "1.6.0", + vec![permission("game.launch", "approved-game-session")], + ); + let bundle_v1 = fixture.bundle(&[&provider_v1, &launch_v1]); + let report_v1 = inspect_bundle_candidate(&bundle_v1, EmulationPolicy::RequireNative) + .await + .unwrap(); + let installed = install_bundle_candidate( + &bundle_v1, + report_v1, + update.registry.clone(), + update.settings.bundle_store(), + EmulationPolicy::RequireNative, + 1_700_000_000, + ) + .await + .unwrap(); + let provider_v2 = fixture.component( + "provider-v2", + "provider", + "org.example.dolphin", + "0.2.0", + "linux", + "gnu", + "1.6.0", + ); + let launch_v2 = fixture.component( + "launch-v2", + "extension", + "org.example.dolphin.launch", + "0.3.0", + "linux", + "gnu", + "1.6.0", + ); + let bundle_v2 = fixture.bundle_version(&[&provider_v2, &launch_v2], "0.2.0"); + let report_v2 = inspect_bundle_candidate(&bundle_v2, EmulationPolicy::RequireNative) + .await + .unwrap(); + let stopper = RecordingStopper::default(); + apply_bundle_update( + &bundle_v2, + report_v2, + installed.bundle, + update.registry.clone(), + update.settings.bundle_store(), + &stopper, + update.grants(), + EmulationPolicy::RequireNative, + 1_700_000_100, + ) + .await + .unwrap(); + + let service = update.service(); + let available = service.available_bundle_rollbacks().await.unwrap(); + assert_eq!(available.len(), 1); + assert_eq!(available[0].active_version, "0.2.0"); + assert_eq!(available[0].versions, vec!["0.1.0".to_owned()]); + + let review = service + .review_bundle_rollback("org.example.dolphin", "0.1.0") + .await + .unwrap(); + assert!(review.is_rollback); + assert!(review.is_downgrade); + assert_eq!(review.installed_version, "0.2.0"); + assert_eq!(review.candidate_version, "0.1.0"); + let provider = review + .components + .iter() + .find(|component| component.plugin_id == "org.example.dolphin") + .unwrap(); + assert_eq!(provider.installed_version, "0.2.0"); + assert_eq!(provider.candidate_version, "0.1.0"); + + let refused = service + .approve_bundle_rollback("org.example.dolphin", "0.1.0", false) + .await + .expect_err("rollback requires confirmation"); + assert!(refused.contains("explicit user confirmation"), "{refused}"); + // A refused confirmation does not consume the reviewed rollback. + let outcome = service + .approve_bundle_rollback("org.example.dolphin", "0.1.0", true) + .await + .unwrap(); + assert_eq!(outcome.version, "0.1.0"); + assert_eq!( + update + .registry + .active("org.example.dolphin") + .unwrap() + .map(|installed| installed.version), + Some("0.1.0".to_owned()) + ); + } + + /// Records every component it is asked to stop; the stop itself is the no-op an idle component + /// needs, so the test observes the removal order without starting a real process. + #[derive(Default)] + struct RecordingStopper { + stopped: Mutex>, + } + + impl RecordingStopper { + fn stopped(&self) -> Vec { + self.stopped.lock().unwrap().clone() + } + } + + impl BundleComponentStopper for RecordingStopper { + fn stop_component<'a>( + &'a self, + plugin_id: &'a str, + ) -> Pin + Send + 'a>> { + self.stopped.lock().unwrap().push(plugin_id.to_owned()); + Box::pin(std::future::ready(())) + } + } + + /// Records the durable-retention choice made for each removed component. + #[derive(Default)] + struct RecordingRetention { + calls: Mutex>, + } + + impl RecordingRetention { + fn calls(&self) -> Vec<(String, DataRetention)> { + self.calls.lock().unwrap().clone() + } + } + + impl DurableRetentionSink for RecordingRetention { + fn apply<'a>( + &'a self, + plugin_id: &'a str, + retention: DataRetention, + ) -> Pin> + Send + 'a>> + { + self.calls + .lock() + .unwrap() + .push((plugin_id.to_owned(), retention)); + let outcome = DurableRetentionOutcome { + plugin_id: plugin_id.to_owned(), + data_retention: retention.as_str(), + archived_records: u64::from(retention == DataRetention::Keep), + removed_records: u64::from(retention == DataRetention::Delete), + reclaimed_bytes: 0, + private_archived_records: u64::from(retention == DataRetention::Keep), + private_removed_records: u64::from(retention == DataRetention::Delete), + private_reclaimed_bytes: 0, + }; + Box::pin(std::future::ready(Ok(outcome))) + } + } + + #[tokio::test] + async fn a_bundle_removal_applies_one_retention_choice_to_every_removed_component() { + let components = vec![ + RemovedBundleComponent { + plugin_id: "org.example.dolphin".to_owned(), + version: "0.1.0".to_owned(), + stopped: true, + }, + RemovedBundleComponent { + plugin_id: "org.example.dolphin.launch".to_owned(), + version: "0.2.0".to_owned(), + stopped: false, + }, + ]; + let sink = RecordingRetention::default(); + + let kept = apply_bundle_durable_retention(&components, DataRetention::Keep, &sink).await; + assert_eq!(kept.data_retention, "kept"); + assert_eq!(kept.retained.len(), 2); + assert!(kept.failures.is_empty()); + assert!( + kept.retained.iter().all(|outcome| { + outcome.data_retention == "kept" && outcome.archived_records == 1 + }) + ); + assert_eq!( + sink.calls(), + [ + ("org.example.dolphin".to_owned(), DataRetention::Keep), + ("org.example.dolphin.launch".to_owned(), DataRetention::Keep) + ] + ); + + let deleted = + apply_bundle_durable_retention(&components[..1], DataRetention::Delete, &sink).await; + assert_eq!(deleted.data_retention, "deleted"); + assert_eq!(deleted.retained.len(), 1); + assert_eq!(deleted.retained[0].removed_records, 1); + assert_eq!( + sink.calls().last(), + Some(&("org.example.dolphin".to_owned(), DataRetention::Delete)) + ); + } + + #[tokio::test] + async fn removing_a_bundle_stops_the_active_component_and_deletes_only_its_versions() { + let fixture = Fixture::new(); + let provider = fixture.component( + "provider", + "provider", + "org.example.dolphin", + "0.1.0", + "linux", + "gnu", + "1.6.0", + ); + // No Windows target matches the Linux test host, so this component is installed inactive. + let launch = fixture.component( + "launch", + "extension", + "org.example.dolphin.launch", + "0.2.0", + "windows", + "msvc", + "1.6.0", + ); + // An unrelated standalone version of the same plugin id stays installed and active. + let standalone_launch = fixture.component( + "launch-standalone", + "extension", + "org.example.dolphin.launch", + "0.1.9", + "linux", + "gnu", + "1.6.0", + ); + let bundle = fixture.bundle(&[&provider, &launch]); + let report = inspect_bundle_candidate(&bundle, EmulationPolicy::RequireNative) + .await + .unwrap(); + let key = fixture.base64_key(); + let (registry, settings) = install_target(&fixture); + + let staged = fixture.dir.path().join("standalone-launch"); + stage_package_archive(&standalone_launch, &staged, &key).unwrap(); + let standalone = registry + .install_signed("org.example.dolphin.launch", "0.1.9", &staged, &key, true) + .unwrap(); + + let installed = install_bundle_candidate( + &bundle, + report, + registry.clone(), + settings.bundle_store(), + EmulationPolicy::RequireNative, + 1_700_000_000, + ) + .await + .unwrap(); + + // A grant record and a library entry exist before the uninstall and must survive it. + let grants_dir = fixture.dir.path().join("account"); + let identity = PluginIdentity { + plugin_id: "org.example.dolphin".to_owned(), + publisher_fingerprint: "ab".repeat(32), + profile_id: "fixture-profile".to_owned(), + }; + let scope = GrantScope::Declared { + value: "https://api.example.com".to_owned(), + }; + let request = PermissionRequest { + permission_id: gamenode_plugin_protocol::capability::NETWORK_FETCH.to_owned(), + required: false, + allowed_scopes: BTreeSet::from([scope.clone()]), + }; + let decision = PermissionDecision { + permission_id: gamenode_plugin_protocol::capability::NETWORK_FETCH.to_owned(), + scope, + granted: true, + }; + PermissionGrantStore::open(&grants_dir) + .unwrap() + .replace_grants(identity.clone(), &[request], &[decision]) + .unwrap(); + let grants_before = PermissionGrantStore::open(&grants_dir).unwrap(); + assert!(!grants_before.effective_grants(&identity).is_empty()); + + settings + .library_store() + .save_scan( + "dolphin", + &[Record { + id: "gamecube-1".to_owned(), + name: Some("Wind Waker".to_owned()), + install_dir: "/games/wind-waker".to_owned(), + fields: BTreeMap::new(), + }], + &BTreeMap::new(), + 1_700_000_000, + ) + .unwrap(); + + let stopper = RecordingStopper::default(); + let removed = remove_installed_bundle( + "org.example.dolphin", + registry.clone(), + settings.bundle_store(), + &stopper, + ) + .await + .unwrap(); + + assert_eq!(removed.bundle, installed.bundle); + assert_eq!(removed.components.len(), 2); + let provider_removal = removed + .components + .iter() + .find(|component| component.plugin_id == "org.example.dolphin") + .unwrap(); + assert_eq!(provider_removal.version, "0.1.0"); + assert!(provider_removal.stopped); + let launch_removal = removed + .components + .iter() + .find(|component| component.plugin_id == "org.example.dolphin.launch") + .unwrap(); + assert_eq!(launch_removal.version, "0.2.0"); + // The bundle's extension version was inactive, so there was no process to stop; the active + // process belongs to the unrelated standalone version and is left alone. + assert!(!launch_removal.stopped); + assert_eq!(stopper.stopped(), vec!["org.example.dolphin"]); + + // The mapping is gone for both components. + let store = settings.bundle_store(); + assert_eq!(store.bundle("org.example.dolphin").unwrap(), None); + assert_eq!( + store.bundle_for_plugin("org.example.dolphin").unwrap(), + None + ); + assert_eq!( + store + .bundle_for_plugin("org.example.dolphin.launch") + .unwrap(), + None + ); + + // The bundle's versions are gone; the standalone version of the same plugin id survives, + // is still active and still verifies. + assert!(registry.versions("org.example.dolphin").unwrap().is_empty()); + assert!(registry.active("org.example.dolphin").unwrap().is_none()); + assert_eq!( + registry.versions("org.example.dolphin.launch").unwrap(), + vec![standalone.clone()] + ); + assert_eq!( + registry.active("org.example.dolphin.launch").unwrap(), + Some(standalone.clone()) + ); + assert_eq!( + registry + .verify_active_package("org.example.dolphin.launch", &key) + .unwrap(), + Some(standalone) + ); + + // Grants and library history are untouched. + let grants_after = PermissionGrantStore::open(&grants_dir).unwrap(); + assert_eq!( + grants_after.effective_grants(&identity), + grants_before.effective_grants(&identity) + ); + assert_eq!( + grants_after.revision(&identity), + grants_before.revision(&identity) + ); + let library = settings.library_store().load_cache(None).unwrap(); + assert_eq!(library.entries.len(), 1); + assert_eq!(library.entries[0].key, "dolphin:gamecube-1"); + assert!(library.entries[0].installed); + } + + #[tokio::test] + async fn a_partial_removal_keeps_only_the_failed_component_mapped() { + let fixture = Fixture::new(); + let provider = fixture.component( + "provider", + "provider", + "org.example.dolphin", + "0.1.0", + "linux", + "gnu", + "1.6.0", + ); + let launch = fixture.component( + "launch", + "extension", + "org.example.dolphin.launch", + "0.2.0", + "linux", + "gnu", + "1.6.0", + ); + let bundle = fixture.bundle(&[&provider, &launch]); + let report = inspect_bundle_candidate(&bundle, EmulationPolicy::RequireNative) + .await + .unwrap(); + let (registry, settings) = install_target(&fixture); + let installed = install_bundle_candidate( + &bundle, + report, + registry.clone(), + settings.bundle_store(), + EmulationPolicy::RequireNative, + 1_700_000_000, + ) + .await + .unwrap(); + + // Damage the extension's versions directory so its recorded version can no longer be + // deleted, while the provider stays removable. + let launch_path = installed + .components + .iter() + .find(|component| component.plugin_id == "org.example.dolphin.launch") + .unwrap() + .package_path + .clone(); + let versions_dir = launch_path + .parent() + .and_then(Path::parent) + .unwrap() + .to_path_buf(); + fs::remove_dir_all(&versions_dir).unwrap(); + fs::write(&versions_dir, b"not a directory").unwrap(); + + let stopper = RecordingStopper::default(); + let result = remove_installed_bundle( + "org.example.dolphin", + registry.clone(), + settings.bundle_store(), + &stopper, + ) + .await; + let BundleRemovalError::PartialRemoval { + bundle_id, + removed, + failures, + .. + } = result.unwrap_err() + else { + panic!("expected a partial removal"); + }; + assert_eq!(bundle_id, "org.example.dolphin"); + assert_eq!(removed.len(), 1); + assert_eq!(removed[0].plugin_id, "org.example.dolphin"); + assert_eq!(failures.len(), 1); + assert_eq!(failures[0].plugin_id, "org.example.dolphin.launch"); + assert_eq!(failures[0].version, "0.2.0"); + + // The provider is deleted and no longer mapped. + assert!(registry.versions("org.example.dolphin").unwrap().is_empty()); + // Only the failed component stays mapped: no row names the deleted provider. + let store = settings.bundle_store(); + let remaining = store + .bundle("org.example.dolphin") + .unwrap() + .expect("the partial mapping is kept for a retry"); + assert_eq!(remaining.components.len(), 1); + assert_eq!( + remaining.components[0].plugin_id, + "org.example.dolphin.launch" + ); + assert_eq!( + store.bundle_for_plugin("org.example.dolphin").unwrap(), + None + ); + assert_eq!( + store + .bundle_for_plugin("org.example.dolphin.launch") + .unwrap(), + Some(remaining) + ); + } + + #[tokio::test] + async fn uninstalling_a_bundle_applies_one_private_data_retention_choice() { + use gamenode_platform::plugin_storage::{ + DurableStore, PluginStorageError, QUOTA_BYTES, namespace_dir, + }; + + let fixture = Fixture::new(); + let provider = fixture.component( + "provider", + "provider", + "org.example.dolphin", + "0.1.0", + "linux", + "gnu", + "1.6.0", + ); + let launch = fixture.component( + "launch", + "extension", + "org.example.dolphin.launch", + "0.2.0", + "linux", + "gnu", + "1.6.0", + ); + let bundle = fixture.bundle(&[&provider, &launch]); + let (registry, settings) = install_target(&fixture); + let install = |report| { + install_bundle_candidate( + &bundle, + report, + registry.clone(), + settings.bundle_store(), + EmulationPolicy::RequireNative, + 1_700_000_000, + ) + }; + let installed = install( + inspect_bundle_candidate(&bundle, EmulationPolicy::RequireNative) + .await + .unwrap(), + ) + .await + .unwrap(); + let publisher = installed.bundle.publisher_fingerprint.clone(); + let data_root = fixture.dir.path().join("plugin-data"); + let profile = "fixture-profile"; + let profile_data = namespace_dir(&data_root, &publisher, "org.example.dolphin", profile); + let mut component_store = DurableStore::open(&profile_data).unwrap(); + component_store + .put("kept", b"value", 1, None, 100, QUOTA_BYTES) + .unwrap(); + drop(component_store); + let private_persistence = profile_data.join("plugin-persistence.sqlite3"); + fs::write(&private_persistence, b"private persistence").unwrap(); + let other_profile = namespace_dir( + &data_root, + &publisher, + "org.example.dolphin", + "other-profile", + ); + let mut other_store = DurableStore::open(&other_profile).unwrap(); + other_store + .put("kept", b"other", 1, None, 100, QUOTA_BYTES) + .unwrap(); + drop(other_store); + fs::write( + other_profile.join("plugin-persistence.sqlite3"), + b"other profile persistence", + ) + .unwrap(); + // Another plugin of the same publisher has its own private namespaces. + let foreign_plugin = namespace_dir(&data_root, &publisher, "org.example.other", profile); + let mut foreign_store = DurableStore::open(&foreign_plugin).unwrap(); + foreign_store + .put("kept", b"foreign", 1, None, 100, QUOTA_BYTES) + .unwrap(); + drop(foreign_store); + fs::write( + foreign_plugin.join("plugin-persistence.sqlite3"), + b"foreign persistence", + ) + .unwrap(); + + // Keep: the packages and mapping are removed, and the private entries become inert but + // stay attributed to the profile. + let stopper = RecordingStopper::default(); + let kept = uninstall_bundle( + "org.example.dolphin", + registry.clone(), + settings.bundle_store(), + &stopper, + BundleDataRetention::Keep, + Some(BundlePrivateData { + root: &data_root, + profile_id: profile, + }), + ) + .await + .unwrap(); + assert_eq!(kept.data_retention, "kept"); + assert!(kept.failures.is_empty(), "{:?}", kept.failures); + assert_eq!(kept.removed.len(), 2); + assert_eq!(stopper.stopped().len(), 2); + assert!(profile_data.is_dir()); + let kept_store = DurableStore::open_existing(&profile_data) + .unwrap() + .expect("the kept namespace remains on disk"); + assert!(kept_store.get("kept", 100).unwrap().is_none()); + assert_eq!(kept_store.archived_usage().unwrap().records, 1); + let mut kept_store = kept_store; + assert!(matches!( + kept_store.put("kept", b"new", 2, None, 100, QUOTA_BYTES), + Err(PluginStorageError::Archived) + )); + assert!( + DurableStore::open_existing(&other_profile) + .unwrap() + .unwrap() + .get("kept", 100) + .unwrap() + .is_some(), + "another profile stays readable" + ); + assert!( + DurableStore::open_existing(&foreign_plugin) + .unwrap() + .unwrap() + .get("kept", 100) + .unwrap() + .is_some(), + "another plugin stays readable" + ); + assert!( + settings + .bundle_store() + .bundle("org.example.dolphin") + .unwrap() + .is_none() + ); + assert!(registry.versions("org.example.dolphin").unwrap().is_empty()); + assert_eq!(registry.active("org.example.dolphin").unwrap(), None); + + // Delete: reinstalling and uninstalling again removes only the chosen profile's data. + install( + inspect_bundle_candidate(&bundle, EmulationPolicy::RequireNative) + .await + .unwrap(), + ) + .await + .unwrap(); + let deleted = uninstall_bundle( + "org.example.dolphin", + registry.clone(), + settings.bundle_store(), + &RecordingStopper::default(), + BundleDataRetention::Delete, + Some(BundlePrivateData { + root: &data_root, + profile_id: profile, + }), + ) + .await + .unwrap(); + assert_eq!(deleted.data_retention, "deleted"); + assert!(deleted.failures.is_empty(), "{:?}", deleted.failures); + assert!(!profile_data.exists()); + assert!( + other_profile.is_dir(), + "another signed-in profile's private data is not part of this choice" + ); + assert!(other_profile.join("storage.sqlite3").is_file()); + assert_eq!( + fs::read(other_profile.join("plugin-persistence.sqlite3")).unwrap(), + b"other profile persistence" + ); + assert!( + foreign_plugin.join("storage.sqlite3").is_file(), + "another plugin's private store is not reclaimed" + ); + assert_eq!( + fs::read(foreign_plugin.join("plugin-persistence.sqlite3")).unwrap(), + b"foreign persistence" + ); + assert!( + registry + .active("org.example.dolphin.launch") + .unwrap() + .is_none() + ); + } + + #[tokio::test] + async fn an_uninstall_outcome_names_every_component_that_could_not_be_removed() { + let fixture = Fixture::new(); + let provider = fixture.component( + "provider", + "provider", + "org.example.dolphin", + "0.1.0", + "linux", + "gnu", + "1.6.0", + ); + let launch = fixture.component( + "launch", + "extension", + "org.example.dolphin.launch", + "0.2.0", + "linux", + "gnu", + "1.6.0", + ); + let bundle = fixture.bundle(&[&provider, &launch]); + let report = inspect_bundle_candidate(&bundle, EmulationPolicy::RequireNative) + .await + .unwrap(); + let (registry, settings) = install_target(&fixture); + let installed = install_bundle_candidate( + &bundle, + report, + registry.clone(), + settings.bundle_store(), + EmulationPolicy::RequireNative, + 1_700_000_000, + ) + .await + .unwrap(); + + // Damage the extension's versions directory so its recorded version cannot be deleted. + let launch_path = installed + .components + .iter() + .find(|component| component.plugin_id == "org.example.dolphin.launch") + .unwrap() + .package_path + .clone(); + let versions_dir = launch_path + .parent() + .and_then(Path::parent) + .unwrap() + .to_path_buf(); + fs::remove_dir_all(&versions_dir).unwrap(); + fs::write(&versions_dir, b"not a directory").unwrap(); + + let outcome = uninstall_bundle( + "org.example.dolphin", + registry.clone(), + settings.bundle_store(), + &RecordingStopper::default(), + BundleDataRetention::Keep, + None, + ) + .await + .expect("a partial removal is reported as an outcome, not a generic error"); + assert_eq!(outcome.bundle_id, "org.example.dolphin"); + assert_eq!(outcome.removed.len(), 1); + assert_eq!(outcome.removed[0].plugin_id, "org.example.dolphin"); + assert_eq!(outcome.failures.len(), 1); + assert_eq!(outcome.failures[0].plugin_id, "org.example.dolphin.launch"); + assert_eq!(outcome.failures[0].version, "0.2.0"); + assert!(!outcome.failures[0].error.is_empty()); + // The failed component keeps its mapping row for a retry. + assert_eq!( + settings + .bundle_store() + .bundle("org.example.dolphin") + .unwrap() + .expect("the failed component stays mapped") + .components + .len(), + 1 + ); + } + + /// The real Dolphin development publisher key. The bundle acceptance asserts that the signed + /// artifact is verified against exactly this key, so a re-signed artifact with another + /// publisher cannot pass unnoticed. + #[cfg(target_os = "linux")] + const DOLPHIN_PUBLISHER_PUBLIC_KEY: &str = "9MJsveQ7SI656O7ykweL/Y+WN1pye9EJ9W+yaQZmidw="; + + #[cfg(target_os = "linux")] + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn the_real_dolphin_bundle_is_one_review_one_inventory_entry_and_one_uninstall() { + use crate::plugin_host::{ + PluginApiServer, + runtime::{HostedProviders, ProviderRuntime}, + }; + use gamenode_platform::plugin_storage::{DurableStore, QUOTA_BYTES, namespace_dir}; + use std::os::unix::fs::PermissionsExt; + use std::sync::Arc; + + let Some(artifact) = dolphin_bundle_artifact() else { + return; + }; + let publisher_key: [u8; 32] = base64::engine::general_purpose::STANDARD + .decode(DOLPHIN_PUBLISHER_PUBLIC_KEY) + .unwrap() + .try_into() + .unwrap(); + let fingerprint = publisher_trust::key_fingerprint(&publisher_key); + + let directory = tempfile::tempdir().unwrap(); + std::fs::set_permissions(directory.path(), std::fs::Permissions::from_mode(0o700)).unwrap(); + let paths = DataPaths::at(directory.path().join("app-data")); + let api = PluginApi::default(); + let state = PluginStateLayout::managed(&paths); + api.set_state_layout(state.clone()); + api.providers + .profiles() + .update(Some("dolphin-emu-account"), true); + let registry = PluginPackageRegistry::open(&paths).unwrap(); + let settings = SqliteSettingsStore::open(&paths.database_file()).unwrap(); + let endpoint = paths.data_dir().join("plugins.sock"); + + // The same lifecycle the application builds before the host composes its runtime; import + // only needs an authenticated profile and the signed registry. + let preliminary = Arc::new(ThirdPartyPluginLifecycle::new( + api.providers.clone(), + ProviderProcesses::new_for_lifecycle( + api.providers.clone(), + endpoint.clone(), + vec![], + state.clone(), + ) + .unwrap(), + state.clone(), + registry.clone(), + ManagedPackageLifecycle::new(registry.clone()), + )); + let service = PluginUpdateService::open(&paths).unwrap(); + service.set_lifecycle(preliminary); + service.set_profiles(api.providers.profiles()); + service.set_bundle_store(settings.bundle_store()); + + // 7.1: one aggregated review for both signed components, pinned to the development key. + let review = service + .bundle_import_review(artifact.clone()) + .await + .unwrap(); + assert_eq!(review.bundle.id, "dev.richmont.gamenode.dolphin-emu.bundle"); + assert_eq!(review.bundle.name, "Dolphin GameCube and Wii"); + assert_eq!(review.bundle.version, "0.1.0"); + assert_eq!( + review.bundle.publisher_key_id, + "richmont-dolphin-emu-development" + ); + assert_eq!(review.bundle.publisher_fingerprint, fingerprint); + assert_eq!(review.trust, "untrusted"); + assert_eq!(review.license.expressions, ["GPL-3.0-only"]); + assert_eq!(review.components.len(), 2); + let provider_review = review + .components + .iter() + .find(|component| component.review.plugin_id == "dev.richmont.gamenode.dolphin-emu") + .expect("the provider is reviewed as one component"); + assert_eq!(provider_review.kind, "provider"); + assert_eq!(provider_review.review.version, "0.1.0"); + assert_eq!(provider_review.review.compatibility, "compatible"); + assert_eq!( + provider_review.availability, + BundleComponentAvailability::Available + ); + let provider_permissions = provider_review + .review + .requested_permissions + .iter() + .map(|permission| permission.id.as_str()) + .collect::>(); + for expected in [ + "provider.context.read", + "library.discovery", + "data.publish", + "storage.persist", + ] { + assert!( + provider_permissions.contains(expected), + "the review shows {expected}: {provider_permissions:?}" + ); + } + let launch_review = review + .components + .iter() + .find(|component| { + component.review.plugin_id == "dev.richmont.gamenode.dolphin-emu-launch" + }) + .expect("the extension is reviewed as one component"); + assert_eq!(launch_review.kind, "extension"); + assert_eq!(launch_review.review.version, "0.1.0"); + assert_eq!(launch_review.review.compatibility, "compatible"); + assert_eq!( + launch_review.availability, + BundleComponentAvailability::Available + ); + + // One publisher confirmation covers the bundle; then the reviewed archive installs. + service + .bundle_import_confirm_publisher(&review.token, &fingerprint) + .await + .unwrap(); + let installed = service + .bundle_import_install(&review.token, false, &[]) + .await + .unwrap(); + assert_eq!( + installed.bundle_id, + "dev.richmont.gamenode.dolphin-emu.bundle" + ); + assert_eq!(installed.components.len(), 2); + assert!( + installed + .components + .iter() + .all(|component| component.active) + ); + assert_eq!( + registry + .active("dev.richmont.gamenode.dolphin-emu") + .unwrap() + .map(|installed| installed.version), + Some("0.1.0".to_owned()) + ); + assert_eq!( + registry + .active("dev.richmont.gamenode.dolphin-emu-launch") + .unwrap() + .map(|installed| installed.version), + Some("0.1.0".to_owned()) + ); + + // 7.2 inventory: recompose the host from the registry exactly as on startup. + let library: Arc = Arc::new( + SqliteSettingsStore::open(&paths.database_file()) + .unwrap() + .library_store(), + ); + let host = HostedProviders::bundled( + api.providers.clone(), + Arc::new(Default::default()), + Some(endpoint.clone()), + paths.clone(), + library, + None, + ) + .await + .unwrap(); + let server = + PluginApiServer::start(&tokio::runtime::Handle::current(), &endpoint, api.clone()) + .unwrap(); + let inventory_service = PluginUpdateService::open(&paths).unwrap(); + inventory_service.set_lifecycle(host.lifecycle()); + inventory_service.set_profiles(api.providers.profiles()); + inventory_service.set_bundle_store(settings.bundle_store()); + let inventory = inventory_service.managed_inventory().await.unwrap(); + assert_eq!(inventory.len(), 1, "{inventory:#?}"); + let entry = &inventory[0]; + assert_eq!(entry.plugin_kind, "bundle"); + assert_eq!(entry.plugin_id, "dev.richmont.gamenode.dolphin-emu.bundle"); + assert_eq!(entry.name, "Dolphin GameCube and Wii"); + assert_eq!(entry.version, "0.1.0"); + assert_eq!( + entry.bundle_publisher_fingerprint.as_deref(), + Some(fingerprint.as_str()) + ); + let components = entry.bundle_components.as_ref().unwrap(); + assert_eq!(components.len(), 2); + let provider_component = components + .iter() + .find(|component| component.plugin_id == "dev.richmont.gamenode.dolphin-emu") + .unwrap(); + assert_eq!(provider_component.plugin_kind, "provider"); + assert_eq!(provider_component.version, "0.1.0"); + assert_eq!(provider_component.status, "installed"); + assert_eq!(provider_component.runtime_available, Some(true)); + assert_eq!( + provider_component.publisher_fingerprint.as_deref(), + Some(fingerprint.as_str()) + ); + let launch_component = components + .iter() + .find(|component| component.plugin_id == "dev.richmont.gamenode.dolphin-emu-launch") + .unwrap(); + assert_eq!(launch_component.plugin_kind, "extension"); + assert_eq!(launch_component.version, "0.1.0"); + assert_eq!( + launch_component.status, "installed", + "the extension target is compatible and the runtime is composed on Linux" + ); + assert_eq!(launch_component.runtime_available, Some(true)); + + // Keep: both packages and the mapping disappear; the private namespace turns inert. + let data_root = state.plugin_data_root().unwrap().to_path_buf(); + let signed_in = api + .providers + .profiles() + .require() + .expect("the acceptance host is signed in"); + let profile = signed_in.profile_id().to_owned(); + let provider_namespace = namespace_dir( + &data_root, + &fingerprint, + "dev.richmont.gamenode.dolphin-emu", + &profile, + ); + let mut private_store = DurableStore::open(&provider_namespace).unwrap(); + private_store + .put("saved", b"value", 1, None, 100, QUOTA_BYTES) + .unwrap(); + drop(private_store); + std::fs::write( + provider_namespace.join("plugin-persistence.sqlite3"), + b"provider persistence", + ) + .unwrap(); + let kept = host + .lifecycle() + .remove_bundle( + "dev.richmont.gamenode.dolphin-emu.bundle".into(), + settings.bundle_store(), + false, + ) + .await + .unwrap(); + assert_eq!(kept.data_retention, "kept"); + assert_eq!(kept.removed.len(), 2, "{kept:#?}"); + assert!(kept.failures.is_empty(), "{kept:#?}"); + assert!(provider_namespace.is_dir()); + let kept_store = DurableStore::open_existing(&provider_namespace) + .unwrap() + .expect("the kept namespace remains on disk"); + assert_eq!(kept_store.archived_usage().unwrap().records, 1); + assert!(kept_store.get("saved", 100).unwrap().is_none()); + assert_eq!( + std::fs::read(provider_namespace.join("plugin-persistence.sqlite3")).unwrap(), + b"provider persistence" + ); + assert!( + settings + .bundle_store() + .bundle("dev.richmont.gamenode.dolphin-emu.bundle") + .unwrap() + .is_none() + ); + assert!( + registry + .versions("dev.richmont.gamenode.dolphin-emu") + .unwrap() + .is_empty() + ); + assert!( + registry + .versions("dev.richmont.gamenode.dolphin-emu-launch") + .unwrap() + .is_empty() + ); + host.shutdown().await; + server.shutdown().await; + + // Delete: reinstall the same artifact and uninstall again through the named removal path. + let second_review = service.bundle_import_review(artifact).await.unwrap(); + service + .bundle_import_confirm_publisher( + &second_review.token, + &second_review.bundle.publisher_fingerprint, + ) + .await + .unwrap(); + service + .bundle_import_install(&second_review.token, false, &[]) + .await + .unwrap(); + let deleted = uninstall_bundle( + "dev.richmont.gamenode.dolphin-emu.bundle", + registry.clone(), + settings.bundle_store(), + &RecordingStopper::default(), + BundleDataRetention::Delete, + Some(BundlePrivateData { + root: &data_root, + profile_id: &profile, + }), + ) + .await + .unwrap(); + assert_eq!(deleted.data_retention, "deleted"); + assert_eq!(deleted.removed.len(), 2, "{deleted:#?}"); + assert!(deleted.failures.is_empty(), "{deleted:#?}"); + assert!( + !provider_namespace.exists(), + "Delete removes only the signed-in profile's private namespace" + ); + assert!( + registry + .versions("dev.richmont.gamenode.dolphin-emu") + .unwrap() + .is_empty() + ); + assert!( + settings + .bundle_store() + .bundle("dev.richmont.gamenode.dolphin-emu.bundle") + .unwrap() + .is_none() + ); + } +} diff --git a/crates/app/src/plugin_host/cleanup.rs b/crates/app/src/plugin_host/cleanup.rs new file mode 100644 index 000000000..40d37cec8 --- /dev/null +++ b/crates/app/src/plugin_host/cleanup.rs @@ -0,0 +1,503 @@ +//! Reviewed host-wide cleanup of plugin storage. +//! +//! This is host administration, not a plugin route: nothing here is served over `ResourceHost` +//! and no plugin RPC can reach it. A review enumerates non-empty producers and private stores of +//! the active account profile with their logical sizes, ages and effective limits. Applying the +//! review requires the exact single-use token and an explicit confirmation; only the selected +//! owner candidates are pruned, through the same per-namespace retention paths the automatic +//! cleanup uses. User-protected and archived rows stay, another owner is never crossed, and a +//! partial failure is reported per candidate with the measured reclaimed space. + +use std::collections::BTreeMap; +use std::sync::Mutex; + +use gamenode_platform::plugin_shared_data::OwnerScope; +use gamenode_platform::plugin_storage::QUOTA_BYTES; +use sha2::{Digest, Sha256}; +use tonic::Status; + +use super::runtime::ThirdPartyPluginLifecycle; + +mod admin; +pub use admin::{PluginStorageAccounting, PluginStorageLocation, PluginStoragePool}; + +/// The store a candidate belongs to. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum CleanupKind { + DurableShared, + PrivatePersistence, +} + +impl CleanupKind { + pub fn as_str(self) -> &'static str { + match self { + Self::DurableShared => "durable_shared", + Self::PrivatePersistence => "private_persistence", + } + } +} + +/// One owner's non-empty dataset or private store, as presented for review. Contains no value, +/// physical path or raw owner key. +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct StorageCleanupCandidate { + /// Opaque host id binding the kind and the owner key. It cannot be used to address a path. + pub candidate_id: String, + /// `durable_shared` or `private_persistence`. + pub kind: String, + pub plugin_id: String, + pub profile_id: String, + pub records: u64, + pub protected_records: u64, + pub archived_records: u64, + pub logical_bytes: u64, + /// Namespace- or pool-wide SQLite page estimate, never a per-owner figure. + pub physical_bytes_estimate: u64, + pub oldest_updated_at: Option, + /// Effective byte limit the cleanup will apply. `None` means only the expiry/age path. + pub max_bytes: Option, + pub max_age_seconds: Option, +} + +/// The review the user must confirm. The token is single-use and bound to the active profile and +/// the candidate snapshot. +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct StorageCleanupReview { + pub token: String, + pub generated_at: i64, + pub candidates: Vec, +} + +/// One selected candidate's result. +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct StorageCleanupResult { + pub candidate_id: String, + pub kind: String, + pub plugin_id: String, + /// `completed` or `failed`. + pub status: String, + pub removed_records: u64, + pub reclaimed_bytes: u64, + #[serde(skip_serializing_if = "Option::is_none")] + pub error: Option, +} + +/// The measured result of one confirmed cleanup. The token cannot be reused. +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct StorageCleanupReport { + pub token: String, + pub removed_records: u64, + pub reclaimed_bytes: u64, + /// Protected records the reviewed candidates held and this cleanup kept. + pub skipped_protected_records: u64, + pub results: Vec, +} + +#[derive(Clone)] +struct ReviewedCandidate { + candidate: StorageCleanupCandidate, + owner_key: [u8; 32], + publisher_fingerprint: String, +} + +#[derive(Clone)] +struct IssuedReview { + token: String, + profile_id: String, + profile_epoch: u64, + candidates: Vec, +} + +/// Single-use cleanup reviews. Older reviews are dropped first, so a settings surface cannot grow +/// unbounded state. +#[derive(Default)] +pub struct CleanupReviews { + issued: Mutex>, +} + +const MAX_ISSUED_REVIEWS: usize = 8; + +impl CleanupReviews { + fn issue(&self, review: IssuedReview) { + let mut issued = self.issued.lock().unwrap_or_else(|p| p.into_inner()); + issued.push(review); + if issued.len() > MAX_ISSUED_REVIEWS { + issued.remove(0); + } + } + + fn get(&self, token: &str) -> Option { + self.issued + .lock() + .unwrap_or_else(|p| p.into_inner()) + .iter() + .find(|review| review.token == token) + .cloned() + } + + fn take(&self, token: &str) -> Option { + let mut issued = self.issued.lock().unwrap_or_else(|p| p.into_inner()); + let index = issued.iter().position(|review| review.token == token)?; + Some(issued.remove(index)) + } +} + +fn candidate_id(kind: CleanupKind, owner_key: &[u8; 32]) -> String { + let mut digest = Sha256::new(); + digest.update(b"gamenode.cleanup.candidate.v1\0"); + digest.update(kind.as_str().as_bytes()); + digest.update(owner_key); + digest + .finalize() + .iter() + .map(|byte| format!("{byte:02x}")) + .collect() +} + +fn effective_private_max_bytes(policy_max: u64) -> u64 { + if policy_max == 0 { + QUOTA_BYTES + } else { + policy_max.min(QUOTA_BYTES) + } +} + +impl ThirdPartyPluginLifecycle { + /// Enumerates cleanup candidates for the active profile. Reading never creates a pool or a + /// private store file. The returned token must be confirmed before anything is deleted. + pub async fn storage_cleanup_review(&self) -> Result { + let now = unix_now()?; + self.storage_cleanup_review_at(now).await + } + + /// Applies one confirmed review. An unconfirmed call, an unknown token or a selection outside + /// the review changes nothing. Each selected candidate is pruned on its own; a partial + /// failure is reported and leaves the other candidates' results intact. + pub async fn storage_cleanup_apply( + &self, + token: String, + candidate_ids: Vec, + confirmed: bool, + ) -> Result { + let now = unix_now()?; + self.storage_cleanup_apply_at(token, candidate_ids, confirmed, now) + .await + } + + pub(crate) async fn storage_cleanup_review_at( + &self, + now: i64, + ) -> Result { + let api = self.host_api(); + let profile = api.profiles().require()?; + let profile_id = profile.profile_id().to_owned(); + let profile_epoch = profile.epoch(); + let mut identities: BTreeMap<(String, String), ()> = BTreeMap::new(); + for provider_id in api.third_party_provider_ids() { + if let Some((plugin_id, publisher)) = api.third_party_identity(&provider_id) { + identities.insert((plugin_id, publisher), ()); + } + } + let storage = self.private_storage(); + let mut candidates = Vec::new(); + for (plugin_id, publisher_fingerprint) in identities.into_keys() { + let resolver = api + .profiles() + .resolver(&plugin_id, &publisher_fingerprint, None)?; + let owner_key = *resolver.storage_owner().key(); + let owner = OwnerScope::new(owner_key, profile_epoch) + .map_err(|_| Status::failed_precondition("plugin profile is invalid"))?; + + if let Some(usage) = api.shared_pool().usage(owner, now).await? + && (usage.records > 0 || usage.archived_records > 0) + { + candidates.push(ReviewedCandidate { + candidate: StorageCleanupCandidate { + candidate_id: candidate_id(CleanupKind::DurableShared, &owner_key), + kind: CleanupKind::DurableShared.as_str().to_owned(), + plugin_id: plugin_id.clone(), + profile_id: profile_id.clone(), + records: usage.records, + protected_records: usage.protected_records, + archived_records: usage.archived_records, + logical_bytes: usage.logical_bytes, + physical_bytes_estimate: usage.physical_bytes_estimate, + oldest_updated_at: usage.oldest_updated_at, + max_bytes: Some(usage.max_bytes), + max_age_seconds: usage.max_age_seconds, + }, + owner_key, + publisher_fingerprint: publisher_fingerprint.clone(), + }); + } + + let Some(storage) = storage.as_ref() else { + continue; + }; + let Some(usage) = storage.private_usage(&resolver, profile_epoch).await? else { + continue; + }; + let records: u64 = usage + .categories + .iter() + .map(|category| category.records) + .sum(); + let protected: u64 = usage + .categories + .iter() + .map(|category| category.protected_records) + .sum(); + if records == 0 && usage.archived_records == 0 { + continue; + } + let policy_max = usage.retention.map_or(0, |policy| policy.max_bytes); + candidates.push(ReviewedCandidate { + candidate: StorageCleanupCandidate { + candidate_id: candidate_id(CleanupKind::PrivatePersistence, &owner_key), + kind: CleanupKind::PrivatePersistence.as_str().to_owned(), + plugin_id, + profile_id: profile_id.clone(), + records, + protected_records: protected, + archived_records: usage.archived_records, + logical_bytes: usage.logical_bytes, + physical_bytes_estimate: usage.physical_bytes_estimate, + oldest_updated_at: usage.oldest_used_at, + max_bytes: Some(effective_private_max_bytes(policy_max)), + max_age_seconds: usage.retention.and_then(|policy| { + (policy.max_age_seconds > 0).then_some(policy.max_age_seconds) + }), + }, + owner_key, + publisher_fingerprint, + }); + } + + let token = gamenode_platform::random::nonce(); + self.cleanup_reviews().issue(IssuedReview { + token: token.clone(), + profile_id: profile_id.clone(), + profile_epoch, + candidates: candidates.clone(), + }); + Ok(StorageCleanupReview { + token, + generated_at: now, + candidates: candidates + .into_iter() + .map(|reviewed| reviewed.candidate) + .collect(), + }) + } + + /// Applies one reviewed candidate through the same per-namespace retention paths as the + /// automatic cleanup, plus the archived reclaim when the review showed retained rows. + async fn cleanup_candidate( + &self, + reviewed: &ReviewedCandidate, + resolver: &super::namespace::ExternalNamespaceResolver, + owner_key: [u8; 32], + epoch: u64, + now: i64, + ) -> Result<(u64, u64), Status> { + let candidate = &reviewed.candidate; + if candidate.kind == CleanupKind::DurableShared.as_str() { + let owner = OwnerScope::new(owner_key, epoch) + .map_err(|_| Status::failed_precondition("plugin profile is invalid"))?; + let mut removed = 0_u64; + let mut reclaimed = 0_u64; + if let Some(pruned) = self + .host_api() + .shared_pool() + .prune_owner(owner, now) + .await? + { + removed = pruned.removed_records; + reclaimed = pruned.reclaimed_bytes; + } + if candidate.archived_records > 0 + && let Some(archived) = self + .host_api() + .shared_pool() + .reclaim_archived_owner(owner) + .await? + { + removed = removed.saturating_add(archived.removed_records); + reclaimed = reclaimed.saturating_add(archived.reclaimed_bytes); + } + return Ok((removed, reclaimed)); + } + + let storage = self.private_storage().ok_or_else(|| { + Status::failed_precondition("private plugin data is unavailable on this host") + })?; + let cleaned = storage.cleanup_persistence(resolver, epoch).await?; + let mut removed = cleaned.removed_records; + let mut reclaimed = cleaned.reclaimed_bytes; + if candidate.archived_records > 0 { + let archived = storage + .reclaim_archived_persistence(resolver, epoch) + .await?; + removed = removed.saturating_add(archived.records); + reclaimed = reclaimed.saturating_add(archived.logical_bytes); + } + Ok((removed, reclaimed)) + } + + pub(crate) async fn storage_cleanup_apply_at( + &self, + token: String, + candidate_ids: Vec, + confirmed: bool, + now: i64, + ) -> Result { + if !confirmed { + return Err(Status::failed_precondition( + "reviewed storage cleanup requires confirmation", + )); + } + if candidate_ids.is_empty() { + return Err(Status::invalid_argument( + "select at least one cleanup candidate", + )); + } + let mut unique = std::collections::BTreeSet::new(); + if candidate_ids.iter().any(|id| !unique.insert(id.clone())) { + return Err(Status::invalid_argument("candidate ids must be unique")); + } + let review = self + .cleanup_reviews() + .get(&token) + .ok_or_else(|| Status::failed_precondition("cleanup review expired or was used"))?; + let profile = self.host_api().profiles().require()?; + if profile.profile_id() != review.profile_id || profile.epoch() != review.profile_epoch { + return Err(Status::failed_precondition( + "the account profile changed; create a new cleanup review", + )); + } + let by_id: BTreeMap<&str, &ReviewedCandidate> = review + .candidates + .iter() + .map(|candidate| (candidate.candidate.candidate_id.as_str(), candidate)) + .collect(); + for id in &candidate_ids { + if !by_id.contains_key(id.as_str()) { + return Err(Status::invalid_argument( + "a selected candidate is not in this cleanup review", + )); + } + } + + let mut results = Vec::with_capacity(candidate_ids.len()); + let mut removed_records = 0_u64; + let mut reclaimed_bytes = 0_u64; + for id in &candidate_ids { + let reviewed = by_id[id.as_str()]; + let candidate = &reviewed.candidate; + let registered_publisher = self + .host_api() + .third_party_provider_ids_for_plugin(&candidate.plugin_id) + .into_iter() + .find_map(|provider_id| { + self.host_api() + .third_party_identity(&provider_id) + .filter(|(plugin_id, _)| plugin_id == &candidate.plugin_id) + .map(|(_, publisher)| publisher) + }); + let resolved = if registered_publisher.as_deref() + != Some(reviewed.publisher_fingerprint.as_str()) + { + Err(Status::failed_precondition( + "plugin identity changed since the cleanup review", + )) + } else { + self.host_api().profiles().resolver( + &candidate.plugin_id, + &reviewed.publisher_fingerprint, + None, + ) + }; + let outcome = match resolved { + Ok(resolver) => { + let owner_key = *resolver.storage_owner().key(); + if owner_key != reviewed.owner_key { + Err(Status::failed_precondition( + "plugin identity changed since the cleanup review", + )) + } else { + self.cleanup_candidate( + reviewed, + &resolver, + owner_key, + review.profile_epoch, + now, + ) + .await + } + } + Err(error) => Err(error), + }; + match outcome { + Ok((removed, reclaimed)) => { + removed_records = removed_records.saturating_add(removed); + reclaimed_bytes = reclaimed_bytes.saturating_add(reclaimed); + results.push(StorageCleanupResult { + candidate_id: candidate.candidate_id.clone(), + kind: candidate.kind.clone(), + plugin_id: candidate.plugin_id.clone(), + status: "completed".to_owned(), + removed_records: removed, + reclaimed_bytes: reclaimed, + error: None, + }); + } + Err(error) => results.push(StorageCleanupResult { + candidate_id: candidate.candidate_id.clone(), + kind: candidate.kind.clone(), + plugin_id: candidate.plugin_id.clone(), + status: "failed".to_owned(), + removed_records: 0, + reclaimed_bytes: 0, + error: Some(error.message().to_owned()), + }), + } + } + + // Single use: even a partial failure consumes the reviewed snapshot and needs a new + // review for a retry. + self.cleanup_reviews().take(&token); + let skipped_protected_records = candidate_ids + .iter() + .filter_map(|id| by_id.get(id.as_str())) + .map(|candidate| candidate.candidate.protected_records) + .sum(); + tracing::info!( + %token, + removed_records, + reclaimed_bytes, + skipped_protected_records, + "reviewed host-wide plugin storage cleanup completed" + ); + Ok(StorageCleanupReport { + token, + removed_records, + reclaimed_bytes, + skipped_protected_records, + results, + }) + } +} + +fn unix_now() -> Result { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|elapsed| elapsed.as_secs().max(1) as i64) + .map_err(|_| Status::failed_precondition("the system clock is before the Unix epoch")) +} + +#[cfg(test)] +mod tests; diff --git a/crates/app/src/plugin_host/cleanup/admin.rs b/crates/app/src/plugin_host/cleanup/admin.rs new file mode 100644 index 000000000..624da6b16 --- /dev/null +++ b/crates/app/src/plugin_host/cleanup/admin.rs @@ -0,0 +1,250 @@ +//! Host-only physical storage accounting for plugin data. +//! +//! This is host administration, not a plugin route: nothing here is served over `ResourceHost` +//! and no plugin RPC can reach it. It reports the host-managed physical files, their measured +//! allocation, the quota-charged logical bytes of one plugin and the effective limits, so the +//! settings surface can explain where plugin data lives and what cleanup would free. Paths are +//! host UI only; every plugin-facing usage reply keeps reporting logical values alone. + +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; + +use gamenode_platform::plugin_shared_data::{ + FILE_NAME as SHARED_POOL_FILE, MAX_OWNER_LOGICAL_BYTES, OwnerScope, +}; +use gamenode_platform::plugin_storage::namespace_store_file; +use tonic::Status; + +use super::{effective_private_max_bytes, unix_now}; +use crate::plugin_host::runtime::ThirdPartyPluginLifecycle; + +/// One physical file holding plugin data of the active profile. +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PluginStorageLocation { + pub plugin_id: String, + /// `durable_shared` or `private_persistence`. + pub kind: String, + /// The host-managed file on disk. Shown only in the host UI. + pub path: String, + /// `namespace` when the file belongs to this plugin/profile alone, `pool` when every + /// third-party producer shares the same SQLite file. + pub scope: String, + /// Measured bytes of the database file plus its write-ahead log and shared-memory sidecars. + pub file_bytes: u64, + /// Quota-charged bytes of this plugin's live records. + pub logical_bytes: u64, + pub records: u64, + pub protected_records: u64, + pub archived_records: u64, + pub oldest_used_at: Option, + /// Effective byte limit the automatic retention path applies. + pub max_bytes: Option, + pub max_age_seconds: Option, +} + +/// The durable pool file, accounted once because every producer shares it. +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PluginStoragePool { + pub path: String, + /// Measured bytes of the pool file and its SQLite sidecars. + pub file_bytes: u64, + /// Live logical bytes of every accounted producer in the pool. + pub logical_bytes: u64, + /// `file_bytes` minus the accounted logical bytes; SQLite metadata and free pages. + pub overhead_bytes: u64, + pub owners: u64, + pub max_owner_bytes: u64, +} + +/// Host-only accounting of the active profile's plugin data. +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PluginStorageAccounting { + pub profile_id: String, + /// One entry per plugin and store that holds data; no value or raw owner key. + pub locations: Vec, + /// `None` when this host has no durable pool file. + pub pool: Option, + pub private_root_bytes: u64, +} + +impl ThirdPartyPluginLifecycle { + /// Physical accounting of the active profile's plugin data, measured on a blocking worker. + pub async fn storage_locations(&self) -> Result { + let now = unix_now()?; + self.storage_locations_at(now).await + } + + pub(crate) async fn storage_locations_at( + &self, + now: i64, + ) -> Result { + let api = self.host_api(); + let profile = api.profiles().require()?; + let profile_id = profile.profile_id().to_owned(); + let profile_epoch = profile.epoch(); + let storage = self.private_storage(); + let pool = api.shared_pool(); + let pool_file = pool.data_dir().map(|dir| dir.join(SHARED_POOL_FILE)); + + let mut identities: BTreeMap<(String, String), ()> = BTreeMap::new(); + for provider_id in api.third_party_provider_ids() { + if let Some((plugin_id, publisher)) = api.third_party_identity(&provider_id) { + identities.insert((plugin_id, publisher), ()); + } + } + + let mut locations: Vec = Vec::new(); + let mut pool_logical_bytes = 0_u64; + let mut pool_owners = 0_u64; + for (plugin_id, publisher_fingerprint) in identities.into_keys() { + let resolver = api + .profiles() + .resolver(&plugin_id, &publisher_fingerprint, None)?; + let owner_key = *resolver.storage_owner().key(); + let owner = OwnerScope::new(owner_key, profile_epoch) + .map_err(|_| Status::failed_precondition("plugin profile is invalid"))?; + + if let Some(usage) = pool.usage(owner, now).await? + && (usage.records > 0 || usage.archived_records > 0) + { + pool_logical_bytes = pool_logical_bytes.saturating_add(usage.logical_bytes); + pool_owners = pool_owners.saturating_add(1); + locations.push(PluginStorageLocation { + plugin_id: plugin_id.clone(), + kind: "durable_shared".to_owned(), + path: pool_file.as_deref().map(display_path).unwrap_or_default(), + scope: "pool".to_owned(), + file_bytes: 0, + logical_bytes: usage.logical_bytes, + records: usage.records, + protected_records: usage.protected_records, + archived_records: usage.archived_records, + oldest_used_at: usage.oldest_updated_at, + max_bytes: Some(usage.max_bytes), + max_age_seconds: usage.max_age_seconds, + }); + } + + let Some(storage) = storage.as_ref() else { + continue; + }; + let Some(usage) = storage.private_usage(&resolver, profile_epoch).await? else { + continue; + }; + let records: u64 = usage + .categories + .iter() + .map(|category| category.records) + .sum(); + let protected: u64 = usage + .categories + .iter() + .map(|category| category.protected_records) + .sum(); + if records == 0 && usage.archived_records == 0 { + continue; + } + let identity = resolver.identity(); + let path = storage.root().map(|root| { + namespace_store_file( + root, + &identity.publisher_fingerprint, + &identity.plugin_id, + &identity.profile_id, + ) + }); + let policy_max = usage.retention.map_or(0, |policy| policy.max_bytes); + locations.push(PluginStorageLocation { + plugin_id, + kind: "private_persistence".to_owned(), + path: path.as_deref().map(display_path).unwrap_or_default(), + scope: "namespace".to_owned(), + file_bytes: 0, + logical_bytes: usage.logical_bytes, + records, + protected_records: protected, + archived_records: usage.archived_records, + oldest_used_at: usage.oldest_used_at, + max_bytes: Some(effective_private_max_bytes(policy_max)), + max_age_seconds: usage.retention.and_then(|policy| { + (policy.max_age_seconds > 0).then_some(policy.max_age_seconds) + }), + }); + } + + // One measuring pass over the distinct files; a missing file measures as zero. + let mut measured: BTreeMap = BTreeMap::new(); + for location in &locations { + if !location.path.is_empty() { + measured.entry(PathBuf::from(&location.path)).or_default(); + } + } + let paths: Vec = measured.keys().cloned().collect(); + if !paths.is_empty() { + let sizes = tokio::task::spawn_blocking(move || { + paths + .into_iter() + .map(|path| { + let bytes = physical_file_bytes(&path); + (path, bytes) + }) + .collect::>() + }) + .await + .map_err(|_| { + Status::unavailable("the plugin storage accounting worker is unavailable") + })?; + measured = sizes; + } + let mut private_root_bytes = 0_u64; + for location in &mut locations { + let bytes = measured + .get(Path::new(&location.path)) + .copied() + .unwrap_or(0); + location.file_bytes = bytes; + if location.scope == "namespace" { + private_root_bytes = private_root_bytes.saturating_add(bytes); + } + } + + let pool = pool_file.map(|path| { + let file_bytes = measured.get(&path).copied().unwrap_or(0); + PluginStoragePool { + path: display_path(&path), + file_bytes, + logical_bytes: pool_logical_bytes, + overhead_bytes: file_bytes.saturating_sub(pool_logical_bytes), + owners: pool_owners, + max_owner_bytes: MAX_OWNER_LOGICAL_BYTES, + } + }); + + Ok(PluginStorageAccounting { + profile_id, + locations, + pool, + private_root_bytes, + }) + } +} + +fn display_path(path: &Path) -> String { + path.to_string_lossy().into_owned() +} + +/// The bytes a SQLite database occupies on disk, including its `-wal` and `-shm` sidecars. +fn physical_file_bytes(path: &Path) -> u64 { + let mut total = std::fs::metadata(path).map_or(0, |metadata| metadata.len()); + for suffix in ["-wal", "-shm"] { + let mut sidecar = path.as_os_str().to_owned(); + sidecar.push(suffix); + total = total.saturating_add( + std::fs::metadata(PathBuf::from(sidecar)).map_or(0, |metadata| metadata.len()), + ); + } + total +} diff --git a/crates/app/src/plugin_host/cleanup/tests.rs b/crates/app/src/plugin_host/cleanup/tests.rs new file mode 100644 index 000000000..a18af5a5a --- /dev/null +++ b/crates/app/src/plugin_host/cleanup/tests.rs @@ -0,0 +1,504 @@ +use std::path::PathBuf; +use std::sync::Arc; + +use gamenode_platform::plugin_shared_data::OwnerScope; +use gamenode_platform::plugin_storage::{ + DurableStore, QUOTA_BYTES, RetentionPolicy, namespace_dir, +}; +use gamenode_plugin_protocol::capability as cap; + +use crate::plugin_host::shared_pool::DurableWrite; +use crate::plugin_host::{ + PluginApi, + provider::{ExtensionServices, Registration, RegistrationKind, RegistrationOrigin}, + runtime::ThirdPartyPluginLifecycle, +}; + +const ONE: &str = "org.example.one"; +const TWO: &str = "org.example.two"; + +struct Fixture { + dir: tempfile::TempDir, + root: PluginApi, + state: crate::plugin_host::profile::PluginStateLayout, + registry: gamenode_platform::plugin_registry::PluginPackageRegistry, +} + +impl Fixture { + fn new() -> Self { + let dir = tempfile::tempdir().unwrap(); + let data_dir = dir.path().join("app-data"); + std::fs::create_dir_all(&data_dir).unwrap(); + let root = PluginApi { + shared_pool: Arc::new(crate::plugin_host::shared_pool::DurableSharedPool::new( + &data_dir, + )), + storage: Arc::new(crate::plugin_host::storage::PluginStorage::new( + dir.path().join("plugin-data"), + )), + ..Default::default() + }; + let state = crate::plugin_host::profile::PluginStateLayout::new(dir.path().join("state")); + root.set_state_layout(state.clone()); + root.providers.profiles().update(Some("account-one"), true); + let registry = gamenode_platform::plugin_registry::PluginPackageRegistry::at( + dir.path().join("registry"), + ) + .unwrap(); + let fixture = Self { + dir, + root, + state, + registry, + }; + fixture.register(ONE, "provider-one", "aa"); + fixture.register(TWO, "provider-two", "bb"); + fixture + } + + fn register(&self, plugin_id: &str, provider_id: &str, fingerprint_byte: &str) { + self.root + .providers + .register(Registration { + provider_id: provider_id.into(), + plugin_id: plugin_id.into(), + declared_developer: "Example Developer".into(), + package_digest: vec![7; 32], + kind: RegistrationKind::Provider, + origin: RegistrationOrigin::ThirdParty { + publisher_fingerprint: fingerprint_byte.repeat(32), + }, + capabilities: vec![cap::CONTEXT.into()], + shared_catalog: false, + playtime: Default::default(), + services: Arc::new(ExtensionServices), + }) + .unwrap(); + } + + fn lifecycle(&self) -> ThirdPartyPluginLifecycle { + let processes = crate::plugin_host::process::ProviderProcesses::new_for_lifecycle( + self.root.providers.clone(), + self.dir.path().join("plugins.sock"), + vec![], + self.state.clone(), + ) + .unwrap(); + let lifecycle = ThirdPartyPluginLifecycle::new( + self.root.providers.clone(), + processes, + self.state.clone(), + self.registry.clone(), + crate::plugin_host::managed_packages::ManagedPackageLifecycle::new( + self.registry.clone(), + ), + ); + lifecycle.set_private_storage(self.root.storage.clone()); + lifecycle + } + + fn fingerprint(&self, plugin_id: &str) -> String { + if plugin_id == ONE { + "aa".repeat(32) + } else { + "bb".repeat(32) + } + } + + fn owner(&self, plugin_id: &str) -> OwnerScope { + let resolver = self + .root + .providers + .profiles() + .resolver(plugin_id, &self.fingerprint(plugin_id), None) + .unwrap(); + OwnerScope::new( + *resolver.storage_owner().key(), + self.root.providers.profiles().require().unwrap().epoch(), + ) + .unwrap() + } + + fn profile_id(&self) -> String { + self.root + .providers + .profiles() + .require() + .unwrap() + .profile_id() + .to_owned() + } + + fn private_dir(&self, plugin_id: &str) -> PathBuf { + namespace_dir( + &self.dir.path().join("plugin-data"), + &self.fingerprint(plugin_id), + plugin_id, + &self.profile_id(), + ) + } + + fn write_private( + &self, + plugin_id: &str, + key: &str, + value: &[u8], + expires_at: Option, + protected: bool, + ) { + let mut store = DurableStore::open(&self.private_dir(plugin_id)).unwrap(); + store + .put(key, value, 1, expires_at, 100, QUOTA_BYTES) + .unwrap(); + if protected { + assert!(store.set_user_protected(key, true).unwrap()); + } + } + + async fn publish(&self, plugin_id: &str, resource: &str, expires_at: Option) -> String { + use gamenode_platform::plugin_shared_data::RecordProvenance; + self.root + .shared_pool + .persist(DurableWrite { + owner: self.owner(plugin_id), + dataset_id: "org.example.catalog".to_owned(), + schema_id: "org.example.catalog.v1".to_owned(), + schema_version: 1, + fields_json: format!(r#"{{"title":"{resource}"}}"#), + opaque_payload: Vec::new(), + resource_id: Some(resource.to_owned()), + observed_at: 100, + sequence: 1, + source_observation_id: format!("observation-{resource}"), + expires_at, + now: 100, + provenance: RecordProvenance { + source_plugin_id: plugin_id.to_owned(), + source_publisher_fingerprint: self.fingerprint(plugin_id), + source_profile_id: "account-one".to_owned(), + declared_developer: "Example Developer".to_owned(), + origin: "registry".to_owned(), + package_version: "1.0.0".to_owned(), + package_digest: vec![7; 32], + }, + }) + .await + .unwrap() + .record_id + } + + fn candidate_id( + review: &crate::plugin_host::cleanup::StorageCleanupReview, + kind: &str, + plugin_id: &str, + ) -> String { + review + .candidates + .iter() + .find(|candidate| candidate.kind == kind && candidate.plugin_id == plugin_id) + .unwrap_or_else(|| panic!("no {kind} candidate for {plugin_id}")) + .candidate_id + .clone() + } +} + +#[tokio::test] +async fn cleanup_requires_confirmation_and_touches_only_selected_owners() { + let fixture = Fixture::new(); + fixture.write_private(ONE, "unprotected", b"old", Some(150), false); + fixture.write_private(ONE, "protected", b"keep", None, true); + fixture.write_private(TWO, "other", b"other", None, false); + // Make the private retention policy the path that removes ONE's old entry, as automatic + // per-namespace retention would. + let mut store = DurableStore::open(&fixture.private_dir(ONE)).unwrap(); + store + .set_retention_policy( + "private", + RetentionPolicy { + max_age_seconds: 10, + max_bytes: 0, + }, + 100, + 2, + ) + .unwrap(); + drop(store); + + let _expired = fixture.publish(ONE, "expired", Some(150)).await; + let _live = fixture.publish(ONE, "live", None).await; + let _two = fixture.publish(TWO, "other", None).await; + + let lifecycle = fixture.lifecycle(); + let review = lifecycle.storage_cleanup_review_at(100).await.unwrap(); + assert_eq!(review.candidates.len(), 4); + let one_private = Fixture::candidate_id(&review, "private_persistence", ONE); + let two_private = Fixture::candidate_id(&review, "private_persistence", TWO); + let one_durable = Fixture::candidate_id(&review, "durable_shared", ONE); + let two_durable = Fixture::candidate_id(&review, "durable_shared", TWO); + let all = vec![ + one_private.clone(), + two_private.clone(), + one_durable.clone(), + two_durable.clone(), + ]; + + // Unconfirmed, unknown-token and out-of-review selections change nothing. + let unconfirmed = lifecycle + .storage_cleanup_apply_at(review.token.clone(), all.clone(), false, 200) + .await + .unwrap_err(); + assert_eq!(unconfirmed.code(), tonic::Code::FailedPrecondition); + let unknown = lifecycle + .storage_cleanup_apply_at("not-a-token".into(), all.clone(), true, 200) + .await + .unwrap_err(); + assert_eq!(unknown.code(), tonic::Code::FailedPrecondition); + let outside = lifecycle + .storage_cleanup_apply_at(review.token.clone(), vec!["deadbeef".into()], true, 200) + .await + .unwrap_err(); + assert_eq!(outside.code(), tonic::Code::InvalidArgument); + assert_eq!( + fixture + .root + .shared_pool + .usage(fixture.owner(ONE), 100) + .await + .unwrap() + .unwrap() + .records, + 2, + "nothing was pruned before confirmation" + ); + + let report = lifecycle + .storage_cleanup_apply_at( + review.token.clone(), + vec![one_private, one_durable], + true, + 200, + ) + .await + .unwrap(); + assert_eq!( + report.removed_records, 2, + "one private and one expired durable" + ); + assert!(report.reclaimed_bytes > 0); + assert_eq!(report.skipped_protected_records, 1); + assert_eq!(report.results.len(), 2); + assert!( + report + .results + .iter() + .all(|result| result.status == "completed") + ); + + // ONE's protected private entry and live durable record survive; TWO is untouched. + let store = DurableStore::open(&fixture.private_dir(ONE)).unwrap(); + assert!(store.get("unprotected", 200).unwrap().is_none()); + assert!(store.get("protected", 200).unwrap().is_some()); + drop(store); + let usage = fixture + .root + .shared_pool + .usage(fixture.owner(ONE), 200) + .await + .unwrap() + .unwrap(); + assert_eq!(usage.records, 1, "the live durable record remains"); + assert_eq!( + fixture + .root + .shared_pool + .usage(fixture.owner(TWO), 200) + .await + .unwrap() + .unwrap() + .records, + 1, + "another owner is never crossed" + ); + assert!(fixture.private_dir(TWO).exists()); + let store = DurableStore::open(&fixture.private_dir(TWO)).unwrap(); + assert!(store.get("other", 200).unwrap().is_some()); + + // The token is single-use; retry needs a new review. + let reused = lifecycle + .storage_cleanup_apply_at(review.token, vec![all[2].clone()], true, 200) + .await + .unwrap_err(); + assert_eq!(reused.code(), tonic::Code::FailedPrecondition); +} + +#[tokio::test] +async fn storage_locations_report_physical_files_overhead_and_effective_limits() { + let fixture = Fixture::new(); + fixture.write_private(ONE, "note", b"value", None, false); + fixture.publish(ONE, "live", None).await; + let expected_private_bytes = gamenode_platform::plugin_storage::charge("note", b"value".len()); + + let accounting = fixture.lifecycle().storage_locations_at(100).await.unwrap(); + assert_eq!(accounting.profile_id, fixture.profile_id()); + + let private = accounting + .locations + .iter() + .find(|location| location.kind == "private_persistence" && location.plugin_id == ONE) + .expect("one private location"); + assert_eq!(private.scope, "namespace"); + let expected_private_path = fixture + .private_dir(ONE) + .join("storage.sqlite3") + .to_string_lossy() + .into_owned(); + assert_eq!( + private.path, expected_private_path, + "the host UI names the managed file; plugin replies never do" + ); + assert_eq!(private.logical_bytes, expected_private_bytes); + assert_eq!(private.max_bytes, Some(QUOTA_BYTES)); + assert!(private.file_bytes >= private.logical_bytes); + assert!(private.file_bytes > 0); + assert!( + accounting.private_root_bytes >= private.file_bytes, + "the private root total covers this namespace" + ); + + let durable = accounting + .locations + .iter() + .find(|location| location.kind == "durable_shared" && location.plugin_id == ONE) + .expect("one durable location"); + assert_eq!(durable.scope, "pool"); + assert!(durable.path.ends_with("plugin-shared-data.gnpersistence")); + assert_eq!(durable.records, 1); + assert_eq!( + durable.max_bytes, + Some(gamenode_platform::plugin_shared_data::MAX_OWNER_LOGICAL_BYTES) + ); + + let pool = accounting.pool.expect("the pool file is accounted once"); + assert_eq!(pool.owners, 1); + assert_eq!(pool.logical_bytes, durable.logical_bytes); + assert_eq!(pool.path, durable.path); + assert_eq!( + pool.overhead_bytes, + pool.file_bytes.saturating_sub(pool.logical_bytes), + "overhead is the measured file minus the quota-charged logical bytes" + ); + assert!(pool.file_bytes > 0); + + // Another plugin has no location until it stores something, and the accounting never + // creates a namespace. + assert!( + accounting + .locations + .iter() + .all(|location| location.plugin_id != TWO) + ); + assert!(!fixture.private_dir(TWO).exists()); +} + +#[tokio::test] +async fn cleanup_reports_a_partial_failure_and_consumes_the_review() { + let fixture = Fixture::new(); + fixture.write_private(ONE, "one", b"one", None, false); + fixture.write_private(TWO, "two", b"two", None, false); + let lifecycle = fixture.lifecycle(); + let review = lifecycle.storage_cleanup_review_at(100).await.unwrap(); + let one = Fixture::candidate_id(&review, "private_persistence", ONE); + let two = Fixture::candidate_id(&review, "private_persistence", TWO); + + // TWO disappears between the review and the confirmation. Its owner cannot be resolved, so + // the candidate fails without touching either store. + fixture + .root + .providers + .unregister_third_party_plugin(TWO) + .await + .unwrap(); + let report = lifecycle + .storage_cleanup_apply_at(review.token.clone(), vec![one.clone(), two], true, 200) + .await + .unwrap(); + assert_eq!(report.results.len(), 2); + assert_eq!(report.results[0].status, "completed"); + assert_eq!(report.results[1].status, "failed"); + assert!(report.results[1].error.is_some()); + assert_eq!(report.removed_records, 0, "nothing was over a limit"); + assert!(fixture.private_dir(TWO).exists()); + assert!(fixture.private_dir(ONE).exists()); + + let reused = lifecycle + .storage_cleanup_apply_at(review.token, vec![one], true, 200) + .await + .unwrap_err(); + assert_eq!(reused.code(), tonic::Code::FailedPrecondition); +} + +#[tokio::test] +async fn cleanup_reclaims_archived_rows_only_when_that_owner_is_selected() { + let fixture = Fixture::new(); + fixture.write_private(ONE, "kept", b"archived", None, false); + fixture.write_private(TWO, "kept", b"live", None, false); + fixture.publish(ONE, "archived", None).await; + let mut store = DurableStore::open(&fixture.private_dir(ONE)).unwrap(); + store.archive_entries(2).unwrap(); + drop(store); + fixture + .root + .shared_pool + .archive_owner(fixture.owner(ONE), 100) + .await + .unwrap(); + + let lifecycle = fixture.lifecycle(); + let review = lifecycle.storage_cleanup_review_at(100).await.unwrap(); + let one_private = Fixture::candidate_id(&review, "private_persistence", ONE); + let two_private = Fixture::candidate_id(&review, "private_persistence", TWO); + let report = lifecycle + .storage_cleanup_apply_at(review.token, vec![one_private, two_private], true, 100) + .await + .unwrap(); + assert_eq!(report.removed_records, 1, "only ONE's archived private row"); + assert_eq!( + report.reclaimed_bytes, + gamenode_platform::plugin_storage::charge("kept", 8) + ); + let remaining = DurableStore::open(&fixture.private_dir(ONE)).unwrap(); + assert_eq!(remaining.archived_usage().unwrap().records, 0); + assert_eq!( + fixture + .root + .shared_pool + .usage(fixture.owner(ONE), 100) + .await + .unwrap() + .unwrap() + .archived_records, + 1, + "the durable candidate was not selected" + ); + let live = DurableStore::open(&fixture.private_dir(TWO)).unwrap(); + assert!(live.get("kept", 100).unwrap().is_some()); + + let review = lifecycle.storage_cleanup_review_at(100).await.unwrap(); + let durable = Fixture::candidate_id(&review, "durable_shared", ONE); + let report = lifecycle + .storage_cleanup_apply_at(review.token, vec![durable], true, 100) + .await + .unwrap(); + assert_eq!(report.removed_records, 1); + assert_eq!( + fixture + .root + .shared_pool + .usage(fixture.owner(ONE), 100) + .await + .unwrap() + .unwrap() + .archived_records, + 0 + ); +} diff --git a/crates/app/src/plugin_host/compatibility.rs b/crates/app/src/plugin_host/compatibility.rs new file mode 100644 index 000000000..67bb78e49 --- /dev/null +++ b/crates/app/src/plugin_host/compatibility.rs @@ -0,0 +1,909 @@ +//! Pure evaluation of a signed package target against the detected execution +//! environment. Author-tested environments are informational and never affect +//! this verdict. + +use gamenode_platform::plugin_environment::{ + EmulationPolicy, EmulationStatus, LibcIdentity, OperatingSystemKind, PluginEnvironment, +}; + +use super::package::{LibcFamily, Target, WindowsProduct}; +use super::package::{Manifest, ManifestError}; +use std::path::Path; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum CompatibilityState { + Compatible, + Incompatible, + Indeterminate, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum CompatibilityReason { + OperatingSystemMismatch, + ArchitectureMismatch, + AbiMismatch, + UnknownOperatingSystem, + UnknownArchitecture, + UnknownAbi, + EmulationRejected, + EmulationUnknown, + WindowsProductMismatch, + WindowsVersionTooOld, + WindowsVersionTooNew, + WindowsBuildTooOld, + WindowsBuildTooNew, + WindowsProductUnknown, + WindowsVersionUnknown, + WindowsBuildUnknown, + LinuxLibcMismatch, + LinuxLibcVersionTooOld, + LinuxLibcUnknown, + LinuxDistributionMismatch, + LinuxDistributionVersionMismatch, + LinuxDistributionUnknown, + NoAdditionalRequirements, + RequirementsMalformed, + RequirementsSatisfied, +} + +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CompatibilityVerdict { + pub state: CompatibilityState, + /// Stable machine-readable reasons; strings suitable for logs/UI belong in + /// a presentation layer. + pub reasons: Vec, + /// Facts the detector could not establish, preserved for diagnostics. + pub unknown_facts: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct TargetCompatibilityAssessment { + /// Retains all signed target declarations, including informational `tested_on` entries. + pub target: Target, + pub verdict: CompatibilityVerdict, +} + +#[derive(Debug, thiserror::Error)] +pub enum PackageCompatibilityError { + #[error("invalid package manifest: {0}")] + InvalidManifest(ManifestError), + #[error("executable resolves outside the package directory")] + ExecutableOutsidePackage, + #[error("executable is not a declared manifest target")] + ExecutableNotDeclared, + #[error("execution environment detection failed: {0}")] + EnvironmentDetection(String), + #[error("compatibility worker failed")] + WorkerFailed, +} + +/// Validate a package manifest against the target executable and a detected +/// effective environment. This is reusable by import/update/activation flows; +/// pre-launch also calls it with refreshed environment facts. +pub fn assess_package( + package_root: &Path, + executable: &Path, + manifest_bytes: &[u8], + environment: &PluginEnvironment, + emulation_policy: EmulationPolicy, +) -> Result { + let manifest = + Manifest::parse_json(manifest_bytes).map_err(PackageCompatibilityError::InvalidManifest)?; + let root = std::fs::canonicalize(package_root) + .map_err(|_| PackageCompatibilityError::ExecutableOutsidePackage)?; + let executable = std::fs::canonicalize(executable) + .map_err(|_| PackageCompatibilityError::ExecutableOutsidePackage)?; + let relative = executable + .strip_prefix(&root) + .map_err(|_| PackageCompatibilityError::ExecutableOutsidePackage)? + .to_string_lossy() + .replace('\\', "/"); + let target = manifest + .manifest() + .targets + .iter() + .find(|target| target.entrypoint == relative) + .ok_or(PackageCompatibilityError::ExecutableNotDeclared)?; + Ok(evaluate_target(target, environment, emulation_policy)) +} + +/// Evaluate every manifest target for import or update selection. Callers can +/// display the retained `tested_on` declarations separately from the verdict; +/// tested coverage never changes eligibility. +pub fn assess_manifest_targets( + manifest_bytes: &[u8], + environment: &PluginEnvironment, + emulation_policy: EmulationPolicy, +) -> Result, PackageCompatibilityError> { + let manifest = + Manifest::parse_json(manifest_bytes).map_err(PackageCompatibilityError::InvalidManifest)?; + Ok(manifest + .manifest() + .targets + .iter() + .cloned() + .map(|target| TargetCompatibilityAssessment { + verdict: evaluate_target(&target, environment, emulation_policy), + target, + }) + .collect()) +} + +/// Detect the current execution environment and assess every declared target. +/// Both the OS probes and manifest evaluation run off the UI/executor thread. +pub async fn assess_manifest_for_current_environment( + manifest_bytes: Vec, + emulation_policy: EmulationPolicy, +) -> Result<(PluginEnvironment, Vec), PackageCompatibilityError> { + let environment = gamenode_platform::plugin_environment::detect() + .await + .map_err(PackageCompatibilityError::EnvironmentDetection)?; + let evaluation_environment = environment.clone(); + let assessments = tokio::task::spawn_blocking(move || { + assess_manifest_targets(&manifest_bytes, &evaluation_environment, emulation_policy) + }) + .await + .map_err(|_| PackageCompatibilityError::WorkerFailed)??; + Ok((environment, assessments)) +} + +impl CompatibilityVerdict { + fn new( + state: CompatibilityState, + reasons: Vec, + environment: &PluginEnvironment, + ) -> Self { + Self { + state, + reasons, + unknown_facts: environment.unknown_facts.clone(), + } + } +} + +/// Evaluate one already-validated target. `tested_on` is deliberately ignored: +/// it records author testing and is not a runtime requirement. +pub fn evaluate_target( + target: &Target, + environment: &PluginEnvironment, + emulation_policy: EmulationPolicy, +) -> CompatibilityVerdict { + let mut reasons = Vec::new(); + let mut indeterminate = false; + + let detected_os = detect_os(environment); + match detected_os { + Some(os) if os == target.os => {} + Some(_) => reasons.push(CompatibilityReason::OperatingSystemMismatch), + None => { + reasons.push(CompatibilityReason::UnknownOperatingSystem); + indeterminate = true; + } + } + + match environment.process_architecture.as_deref() { + Some(arch) if normalize_arch(arch) == normalize_arch(&target.arch) => {} + Some(_) => reasons.push(CompatibilityReason::ArchitectureMismatch), + None => { + reasons.push(CompatibilityReason::UnknownArchitecture); + indeterminate = true; + } + } + + match environment.process_abi.as_deref() { + Some(abi) if abi == target.abi => {} + Some(_) => reasons.push(CompatibilityReason::AbiMismatch), + None => { + reasons.push(CompatibilityReason::UnknownAbi); + indeterminate = true; + } + } + + if !emulation_policy.accepts(&environment.emulation) { + match &environment.emulation { + EmulationStatus::Unknown => { + reasons.push(CompatibilityReason::EmulationUnknown); + indeterminate = true; + } + EmulationStatus::Emulated => reasons.push(CompatibilityReason::EmulationRejected), + EmulationStatus::Native => unreachable!("native is accepted by every policy"), + } + } + + if !reasons.is_empty() && !indeterminate { + return CompatibilityVerdict::new(CompatibilityState::Incompatible, reasons, environment); + } + + if let Some(requirements) = &target.requires { + match target.os.as_str() { + "windows" => { + let Some(req) = requirements.windows.as_ref() else { + reasons.push(CompatibilityReason::RequirementsMalformed); + return CompatibilityVerdict::new( + CompatibilityState::Indeterminate, + reasons, + environment, + ); + }; + indeterminate |= evaluate_windows(req, environment, &mut reasons); + } + "linux" => { + let Some(req) = requirements.linux.as_ref() else { + reasons.push(CompatibilityReason::RequirementsMalformed); + return CompatibilityVerdict::new( + CompatibilityState::Indeterminate, + reasons, + environment, + ); + }; + indeterminate |= evaluate_linux(req, environment, &mut reasons); + } + _ => { + reasons.push(CompatibilityReason::RequirementsMalformed); + return CompatibilityVerdict::new( + CompatibilityState::Indeterminate, + reasons, + environment, + ); + } + } + } else { + reasons.push(CompatibilityReason::NoAdditionalRequirements); + } + + if reasons.iter().any(is_definite_mismatch) { + CompatibilityVerdict::new(CompatibilityState::Incompatible, reasons, environment) + } else if indeterminate { + CompatibilityVerdict::new(CompatibilityState::Indeterminate, reasons, environment) + } else { + if !reasons.contains(&CompatibilityReason::RequirementsSatisfied) { + reasons.push(CompatibilityReason::RequirementsSatisfied); + } + CompatibilityVerdict::new(CompatibilityState::Compatible, reasons, environment) + } +} + +fn detect_os(environment: &PluginEnvironment) -> Option<&'static str> { + if environment + .userspace + .as_ref() + .is_some_and(|userspace| userspace.family.eq_ignore_ascii_case("windows")) + { + Some("windows") + } else if environment + .host + .as_ref() + .is_some_and(|host| host.family.eq_ignore_ascii_case("linux")) + || environment.libc.is_some() + { + Some("linux") + } else { + None + } +} + +fn evaluate_windows( + requirements: &super::package::WindowsRequirements, + environment: &PluginEnvironment, + reasons: &mut Vec, +) -> bool { + let userspace = environment.userspace.as_ref(); + let mut unknown = false; + + if let Some(required) = requirements.product { + let actual = userspace.and_then(|identity| identity.kind); + let matches = matches!( + (required, actual), + (WindowsProduct::Client, Some(OperatingSystemKind::Client)) + | (WindowsProduct::Server, Some(OperatingSystemKind::Server)) + ); + if matches { + // matched + } else if actual.is_some_and(|kind| kind != OperatingSystemKind::Unknown) { + reasons.push(CompatibilityReason::WindowsProductMismatch); + } else { + reasons.push(CompatibilityReason::WindowsProductUnknown); + unknown = true; + } + } + + let actual_version = userspace.and_then(|identity| identity.version_id.as_deref()); + for (bound, is_minimum) in [ + (requirements.min_version.as_deref(), true), + (requirements.max_version.as_deref(), false), + ] { + let Some(bound) = bound else { continue }; + match actual_version.and_then(|actual| compare_numeric_versions(actual, bound)) { + Some(ordering) if is_minimum && ordering.is_lt() => { + reasons.push(CompatibilityReason::WindowsVersionTooOld) + } + Some(ordering) if !is_minimum && ordering.is_gt() => { + reasons.push(CompatibilityReason::WindowsVersionTooNew) + } + Some(_) => {} + None => { + reasons.push(CompatibilityReason::WindowsVersionUnknown); + unknown = true; + break; + } + } + } + + if requirements.min_build.is_some() || requirements.max_build.is_some() { + let Some(actual) = userspace.and_then(|identity| identity.build) else { + reasons.push(CompatibilityReason::WindowsBuildUnknown); + return true; + }; + if requirements.min_build.is_some_and(|min| actual < min) { + reasons.push(CompatibilityReason::WindowsBuildTooOld); + } + if requirements.max_build.is_some_and(|max| actual > max) { + reasons.push(CompatibilityReason::WindowsBuildTooNew); + } + } + unknown +} + +fn evaluate_linux( + requirements: &super::package::LinuxRequirements, + environment: &PluginEnvironment, + reasons: &mut Vec, +) -> bool { + let mut unknown = false; + if let Some(required) = &requirements.libc { + let actual = environment.libc.as_ref(); + let (actual_family, actual_version) = match actual { + Some(LibcIdentity::Gnu(version)) => (Some(LibcFamily::Glibc), version.as_deref()), + Some(LibcIdentity::Musl(version)) => (Some(LibcFamily::Musl), version.as_deref()), + Some(LibcIdentity::Unknown) | None => (None, None), + }; + match actual_family { + Some(family) if family != required.family => { + reasons.push(CompatibilityReason::LinuxLibcMismatch) + } + Some(_) => match actual_version { + Some(version) => match compare_numeric_versions(version, &required.min_version) { + Some(ordering) if ordering.is_lt() => { + reasons.push(CompatibilityReason::LinuxLibcVersionTooOld) + } + Some(_) => {} + None => { + reasons.push(CompatibilityReason::LinuxLibcUnknown); + unknown = true; + } + }, + None => { + reasons.push(CompatibilityReason::LinuxLibcUnknown); + unknown = true; + } + }, + None => { + reasons.push(CompatibilityReason::LinuxLibcUnknown); + unknown = true; + } + } + } + + if let Some(alternatives) = &requirements.distributions { + let userspace = environment.userspace.as_ref(); + let Some(id) = userspace.and_then(|identity| identity.id.as_deref()) else { + reasons.push(CompatibilityReason::LinuxDistributionUnknown); + return true; + }; + let Some(alternative) = alternatives.iter().find(|entry| entry.id == id) else { + reasons.push(CompatibilityReason::LinuxDistributionMismatch); + return unknown; + }; + let Some(version) = userspace.and_then(|identity| identity.version_id.as_deref()) else { + reasons.push(CompatibilityReason::LinuxDistributionUnknown); + return true; + }; + if !alternative + .versions + .iter() + .any(|allowed| allowed == version) + { + reasons.push(CompatibilityReason::LinuxDistributionVersionMismatch); + } + } + unknown +} + +fn is_definite_mismatch(reason: &CompatibilityReason) -> bool { + matches!( + reason, + CompatibilityReason::OperatingSystemMismatch + | CompatibilityReason::ArchitectureMismatch + | CompatibilityReason::AbiMismatch + | CompatibilityReason::EmulationRejected + | CompatibilityReason::WindowsProductMismatch + | CompatibilityReason::WindowsVersionTooOld + | CompatibilityReason::WindowsVersionTooNew + | CompatibilityReason::WindowsBuildTooOld + | CompatibilityReason::WindowsBuildTooNew + | CompatibilityReason::LinuxLibcMismatch + | CompatibilityReason::LinuxLibcVersionTooOld + | CompatibilityReason::LinuxDistributionMismatch + | CompatibilityReason::LinuxDistributionVersionMismatch + ) +} + +fn normalize_arch(architecture: &str) -> String { + match architecture.to_ascii_lowercase().as_str() { + "amd64" | "x86-64" => "x86_64".into(), + "arm64" => "aarch64".into(), + "i386" | "i486" | "i586" | "i686" => "x86".into(), + other => other.into(), + } +} + +fn compare_numeric_versions(left: &str, right: &str) -> Option { + let parse = |version: &str| { + if version.is_empty() + || !version + .bytes() + .all(|byte| byte.is_ascii_digit() || byte == b'.') + { + return None; + } + version + .split('.') + .map(|part| part.parse::().ok()) + .collect::>>() + }; + let mut left = parse(left)?; + let mut right = parse(right)?; + let len = left.len().max(right.len()); + left.resize(len, 0); + right.resize(len, 0); + Some(left.cmp(&right)) +} + +#[cfg(test)] +mod tests { + use super::*; + use gamenode_platform::plugin_environment::{HostIdentity, LibcIdentity, UserspaceIdentity}; + use std::collections::BTreeMap; + + fn linux_target(arch: &str) -> Target { + Target { + os: "linux".into(), + arch: arch.into(), + abi: "gnu".into(), + entrypoint: "bin/plugin".into(), + requires: None, + tested_on: vec![], + } + } + + fn linux_environment() -> PluginEnvironment { + PluginEnvironment { + userspace: Some(UserspaceIdentity { + family: "debian".into(), + id: Some("debian".into()), + version_id: Some("13".into()), + name: Some("Debian GNU/Linux".into()), + product: None, + major: Some(13), + minor: None, + build: None, + kind: None, + extra: BTreeMap::new(), + }), + host: Some(HostIdentity { + family: "Linux".into(), + version: Some("6.12".into()), + architecture: Some("x86_64".into()), + }), + process_architecture: Some("x86_64".into()), + process_abi: Some("gnu".into()), + libc: Some(LibcIdentity::Gnu(Some("2.36".into()))), + emulation: EmulationStatus::Native, + unknown_facts: vec![], + } + } + + fn windows_environment() -> PluginEnvironment { + PluginEnvironment { + userspace: Some(UserspaceIdentity { + family: "windows".into(), + id: None, + version_id: Some("10.0.22631".into()), + name: Some("Windows 11".into()), + product: Some("Windows product SKU".into()), + major: Some(10), + minor: Some(0), + build: Some(22631), + kind: Some(OperatingSystemKind::Client), + extra: BTreeMap::new(), + }), + host: Some(HostIdentity { + family: "windows_nt_kernel".into(), + version: Some("10.0".into()), + architecture: Some("x86_64".into()), + }), + process_architecture: Some("x86_64".into()), + process_abi: Some("msvc".into()), + libc: None, + emulation: EmulationStatus::Native, + unknown_facts: vec![], + } + } + + const DOCUMENTED_MANIFEST: &[u8] = + include_bytes!("../../../../docs/fixtures/plugin-target-compatibility.json"); + + fn assert_documented_verdict( + entrypoint: &str, + environment: &PluginEnvironment, + state: CompatibilityState, + reasons: &[CompatibilityReason], + ) { + let assessments = assess_manifest_targets( + DOCUMENTED_MANIFEST, + environment, + EmulationPolicy::RequireNative, + ) + .unwrap(); + let assessment = assessments + .iter() + .find(|assessment| assessment.target.entrypoint == entrypoint) + .unwrap(); + assert_eq!( + assessment.verdict, + CompatibilityVerdict { + state, + reasons: reasons.to_vec(), + unknown_facts: environment.unknown_facts.clone(), + }, + "{entrypoint}: {environment:?}", + ); + } + + #[test] + fn documented_glibc_target_requires_libc_and_an_exact_distribution_alternative() { + use CompatibilityReason::*; + use CompatibilityState::*; + + let mut environment = linux_environment(); + environment.process_architecture = Some("amd64".into()); + environment + .userspace + .as_mut() + .unwrap() + .extra + .insert("ID_LIKE".into(), "debian".into()); + for (id, version, libc, state, reason) in [ + ( + "debian", + Some("13"), + "2.36", + Compatible, + RequirementsSatisfied, + ), + ( + "debian", + Some("13.1"), + "2.36", + Compatible, + RequirementsSatisfied, + ), + ( + "fedora", + Some("43"), + "2.40", + Compatible, + RequirementsSatisfied, + ), + ( + "debian", + Some("13.0"), + "2.36", + Incompatible, + LinuxDistributionVersionMismatch, + ), + ( + "debian", + Some("12"), + "2.36", + Incompatible, + LinuxDistributionVersionMismatch, + ), + ( + "ubuntu", + Some("24.04"), + "2.36", + Incompatible, + LinuxDistributionMismatch, + ), + ( + "ubuntu", + None, + "2.36", + Incompatible, + LinuxDistributionMismatch, + ), + ( + "debian", + None, + "2.36", + Indeterminate, + LinuxDistributionUnknown, + ), + ( + "debian", + Some("13"), + "2.35", + Incompatible, + LinuxLibcVersionTooOld, + ), + ] { + let userspace = environment.userspace.as_mut().unwrap(); + userspace.id = Some(id.into()); + userspace.version_id = version.map(str::to_owned); + environment.libc = Some(LibcIdentity::Gnu(Some(libc.into()))); + assert_documented_verdict("bin/linux-gnu-x64/plugin", &environment, state, &[reason]); + } + } + + #[test] + fn documented_interpreted_target_rechecks_native_dependency_without_an_allowlist() { + use CompatibilityReason::*; + use CompatibilityState::*; + + let mut environment = linux_environment(); + environment.userspace = None; + environment.process_abi = Some("musl".into()); + environment.unknown_facts = + vec!["distribution.id".into(), "distribution.version_id".into()]; + let entrypoint = "bin/linux-musl-x64/python-plugin"; + for (libc, state, reason) in [ + (Some("1.2.4"), Compatible, RequirementsSatisfied), + (Some("1.2.10"), Compatible, RequirementsSatisfied), + (Some("1.2.3"), Incompatible, LinuxLibcVersionTooOld), + (None, Indeterminate, LinuxLibcUnknown), + ] { + environment.libc = Some(LibcIdentity::Musl(libc.map(str::to_owned))); + assert_documented_verdict(entrypoint, &environment, state, &[reason]); + } + + // Hold the target ABI fact constant to isolate the libc-family comparison. + environment.libc = Some(LibcIdentity::Gnu(Some("2.36".into()))); + assert_documented_verdict(entrypoint, &environment, Incompatible, &[LinuxLibcMismatch]); + assert_documented_verdict( + entrypoint, + &linux_environment(), + Incompatible, + &[AbiMismatch], + ); + } + + #[test] + fn incompatible_and_indeterminate_are_distinct() { + let mismatch = evaluate_target( + &linux_target("x86_64"), + &linux_environment(), + EmulationPolicy::RequireNative, + ); + assert_eq!(mismatch.state, CompatibilityState::Compatible); + let incompatible = evaluate_target( + &linux_target("aarch64"), + &linux_environment(), + EmulationPolicy::RequireNative, + ); + assert_eq!(incompatible.state, CompatibilityState::Incompatible); + let unknown = PluginEnvironment { + unknown_facts: vec!["architecture".into()], + ..Default::default() + }; + let indeterminate = evaluate_target( + &linux_target("x86_64"), + &unknown, + EmulationPolicy::AllowUnknown, + ); + assert_eq!(indeterminate.state, CompatibilityState::Indeterminate); + assert_eq!(indeterminate.unknown_facts, vec!["architecture".to_owned()]); + } + + #[test] + fn tested_coverage_is_not_a_runtime_requirement_and_emulation_is_explicit() { + let mut target = linux_target("x86_64"); + target + .tested_on + .push(super::super::package::TestedEnvironment { + product: None, + release: None, + distribution: Some("fedora".into()), + version: Some("40".into()), + }); + let mut environment = linux_environment(); + environment.emulation = EmulationStatus::Emulated; + assert_eq!( + evaluate_target(&target, &environment, EmulationPolicy::AllowEmulated).state, + CompatibilityState::Compatible + ); + assert_eq!( + evaluate_target(&target, &environment, EmulationPolicy::RequireNative).state, + CompatibilityState::Incompatible + ); + } + + #[test] + fn package_assessment_uses_only_the_signed_declared_entrypoint() { + let directory = tempfile::tempdir().unwrap(); + std::fs::create_dir_all(directory.path().join("bin")).unwrap(); + let executable = directory.path().join("bin/plugin"); + std::fs::write(&executable, b"fixture").unwrap(); + let manifest = br#"{ + "schema":1, + "id":"org.example.reader", + "kind":"provider", + "provider_id":"example-reader", + "name":"Reader", + "version":"1.0.0", + "api":{"min": "1.6.0", "max": "1.6.0"}, + "targets":[{"os":"linux","arch":"x86_64","abi":"gnu","entrypoint":"bin/plugin","tested_on":[{"distribution":"fedora","version":"40"}]}], + "publisher":{"key_id":"fixture","public_key":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="}, + "license":{"expression":"MIT","files":["licenses/LICENSE"]} + }"#; + + let compatible = assess_package( + directory.path(), + &executable, + manifest, + &linux_environment(), + EmulationPolicy::RequireNative, + ) + .unwrap(); + assert_eq!(compatible.state, CompatibilityState::Compatible); + let assessments = assess_manifest_targets( + manifest, + &linux_environment(), + EmulationPolicy::RequireNative, + ) + .unwrap(); + assert_eq!(assessments.len(), 1); + assert_eq!(assessments[0].verdict.state, CompatibilityState::Compatible); + assert_eq!( + assessments[0].target.tested_on[0].distribution.as_deref(), + Some("fedora") + ); + + let outside = tempfile::tempdir().unwrap(); + let outside_executable = outside.path().join("plugin"); + std::fs::write(&outside_executable, b"fixture").unwrap(); + assert!(matches!( + assess_package( + directory.path(), + &outside_executable, + manifest, + &linux_environment(), + EmulationPolicy::RequireNative, + ), + Err(PackageCompatibilityError::ExecutableOutsidePackage) + )); + } + + #[test] + fn documented_windows_target_checks_product_version_and_inclusive_build_bounds() { + use CompatibilityReason::*; + use CompatibilityState::*; + use OperatingSystemKind::{Client, Server, Unknown}; + + let mut environment = windows_environment(); + let entrypoint = "bin/windows-x64/plugin.exe"; + for (product, version, build, state, reason) in [ + ( + Client, + Some("10.0.22000"), + Some(22000), + Compatible, + RequirementsSatisfied, + ), + ( + Client, + Some("10.0.26100"), + Some(26100), + Compatible, + RequirementsSatisfied, + ), + ( + Server, + Some("10.0.22631"), + Some(22631), + Incompatible, + WindowsProductMismatch, + ), + ( + Client, + Some("6.3"), + Some(22000), + Incompatible, + WindowsVersionTooOld, + ), + ( + Client, + Some("10.0.19045"), + Some(19045), + Incompatible, + WindowsBuildTooOld, + ), + ( + Client, + Some("10.0.26101"), + Some(26101), + Incompatible, + WindowsBuildTooNew, + ), + ( + Client, + Some("10.0"), + None, + Indeterminate, + WindowsBuildUnknown, + ), + ( + Unknown, + Some("10.0"), + Some(22631), + Indeterminate, + WindowsProductUnknown, + ), + ( + Client, + None, + Some(22631), + Indeterminate, + WindowsVersionUnknown, + ), + ] { + let userspace = environment.userspace.as_mut().unwrap(); + userspace.kind = Some(product); + userspace.version_id = version.map(str::to_owned); + userspace.build = build; + assert_documented_verdict(entrypoint, &environment, state, &[reason]); + } + + let userspace = environment.userspace.as_mut().unwrap(); + userspace.build = Some(19045); + assert_documented_verdict( + entrypoint, + &environment, + Incompatible, + &[WindowsVersionUnknown, WindowsBuildTooOld], + ); + } + + #[test] + fn manifest_assessment_rejects_unknown_selectors_and_ambiguous_targets() { + let manifest: serde_json::Value = serde_json::from_slice(DOCUMENTED_MANIFEST).unwrap(); + let mut ambiguous = manifest.clone(); + let mut server = ambiguous["targets"][0].clone(); + server["entrypoint"] = "bin/windows-x64/server.exe".into(); + server["requires"]["windows"]["product"] = "server".into(); + ambiguous["targets"].as_array_mut().unwrap().push(server); + + let mut malformed = manifest; + malformed["targets"][0]["requires"]["windows"]["release"] = "23H2".into(); + + for (manifest, expected) in [ + (ambiguous, "ambiguous target selection"), + (malformed, "unknown field `release`"), + ] { + let error = assess_manifest_targets( + &serde_json::to_vec(&manifest).unwrap(), + &windows_environment(), + EmulationPolicy::RequireNative, + ) + .unwrap_err(); + let PackageCompatibilityError::InvalidManifest(error) = error else { + panic!("expected manifest rejection, got {error:?}"); + }; + assert!(error.to_string().contains(expected), "{error}"); + } + } +} diff --git a/crates/app/src/plugin_host/confirmations.rs b/crates/app/src/plugin_host/confirmations.rs new file mode 100644 index 000000000..7bf996d84 --- /dev/null +++ b/crates/app/src/plugin_host/confirmations.rs @@ -0,0 +1,216 @@ +//! The application's side of plugin confirmations (task 10.10): the bridge between the host's +//! [`Prompter`] port and the window, and the settings list of confirmations the user asked the +//! host to remember. +//! +//! The window is told what to ask with the `plugin:confirmation` event and answers with the +//! `plugin_confirmation_answer` command. A confirmation that stops waiting without an answer (the +//! plugin withdrew the request, the time ran out) is closed with `plugin:confirmation-closed`. +//! Everything in the event except the ids the host made is text the plugin or its provider +//! supplied: the window shows it as plain text. + +use std::collections::HashMap; +use std::sync::{Arc, Mutex}; + +use async_trait::async_trait; +use tokio::sync::oneshot; +use tonic::Status; + +use super::intents::{Answer, ConfirmationRequest, Prompter}; +use super::profile::PluginProfiles; +use super::storage::PluginStorage; + +/// The event that asks the window to show a confirmation. +pub const EVENT: &str = "plugin:confirmation"; +/// The event that tells the window a confirmation is no longer waiting. +pub const CLOSED_EVENT: &str = "plugin:confirmation-closed"; + +/// What the window shows. `id` is the host's; the rest identifies the plugin the host +/// authenticated and the game its provider named. +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PluginConfirmation { + pub id: String, + pub plugin_id: String, + pub publisher_fingerprint: String, + pub game_name: String, + /// `launch` or `install`. + pub operation: String, + pub details: Vec, + /// Exact host-resolved launch plan for launch-specific review UI. + pub launch_plan: Option, + /// How long the host waits for the answer. + pub timeout_seconds: u64, +} + +/// What the bridge tells the window. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Signal { + Open(Box), + Closed(String), +} + +/// Delivers a signal to the window. `false` when there is no window to receive it. +pub type Emit = Arc bool + Send + Sync>; + +/// Asks the user through the window. +pub struct ConfirmationBridge { + emit: Emit, + waiting: Mutex>>, +} + +/// Forgets a confirmation that stopped waiting, and closes it in the window. +struct Forget<'a> { + bridge: &'a ConfirmationBridge, + id: String, +} + +impl Drop for Forget<'_> { + fn drop(&mut self) { + let waiting = self + .bridge + .waiting + .lock() + .unwrap_or_else(|p| p.into_inner()) + .remove(&self.id) + .is_some(); + if waiting { + (self.bridge.emit)(Signal::Closed(self.id.clone())); + } + } +} + +impl ConfirmationBridge { + pub fn new(emit: Emit) -> Self { + Self { + emit, + waiting: Mutex::default(), + } + } + + /// Delivers the user's answer to the confirmation `id`. `false` when it is not waiting any + /// more (answered already, withdrawn or timed out), so a late or repeated answer does nothing. + pub fn answer(&self, id: &str, approved: bool, remember: bool) -> bool { + let sender = self + .waiting + .lock() + .unwrap_or_else(|p| p.into_inner()) + .remove(id); + sender.is_some_and(|sender| sender.send(Answer { approved, remember }).is_ok()) + } +} + +#[async_trait] +impl Prompter for ConfirmationBridge { + async fn confirm(&self, request: ConfirmationRequest) -> Result { + let mut bytes = [0_u8; 16]; + getrandom::fill(&mut bytes).map_err(|_| Status::internal("no source of randomness"))?; + let id: String = bytes.iter().map(|b| format!("{b:02x}")).collect(); + let (send, receive) = oneshot::channel(); + self.waiting + .lock() + .unwrap_or_else(|p| p.into_inner()) + .insert(id.clone(), send); + // From here on, however this call ends, the confirmation stops waiting. + let _forget = Forget { + bridge: self, + id: id.clone(), + }; + let shown = (self.emit)(Signal::Open(Box::new(PluginConfirmation { + id, + plugin_id: request.plugin_id, + publisher_fingerprint: request.publisher_fingerprint, + game_name: request.game_name, + operation: request.operation.as_str().to_owned(), + details: request.details, + launch_plan: request.launch_plan, + timeout_seconds: super::intents::CONFIRMATION_TIMEOUT.as_secs(), + }))); + if !shown { + return Err(Status::unavailable("there is no window to ask the user in")); + } + receive + .await + .map_err(|_| Status::unavailable("the confirmation was closed")) + } +} + +/// One confirmation the user asked the host to remember, as the settings list shows it. +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct RememberedConfirmation { + pub id: String, + pub game_name: String, + /// `launch` or `install`. + pub operation: String, + /// Unix seconds. + pub approved_at: i64, +} + +/// The settings view of remembered confirmations, read and revoked on the host's own behalf. +pub struct PluginApprovals { + storage: Arc, + profiles: Arc, +} + +impl PluginApprovals { + pub fn new(storage: Arc, profiles: Arc) -> Self { + Self { storage, profiles } + } + + fn describe(status: Status) -> String { + status.message().to_owned() + } + + /// What the user allowed `plugin_id` (of the publisher `publisher_fingerprint`) to start + /// without asking, in the active profile. + pub async fn list( + &self, + plugin_id: &str, + publisher_fingerprint: &str, + ) -> Result, String> { + let resolver = self + .profiles + .resolver(plugin_id, publisher_fingerprint, None) + .map_err(Self::describe)?; + let approvals = self + .storage + .run_for_host(&resolver, self.profiles.epoch(), |namespace| { + namespace.intent_approvals() + }) + .await + .map_err(Self::describe)?; + Ok(approvals + .into_iter() + .map(|approval| RememberedConfirmation { + id: approval.id, + game_name: approval.game_name, + operation: approval.operation, + approved_at: approval.approved_at, + }) + .collect()) + } + + /// Forgets one remembered confirmation: the next request asks the user again. `false` when + /// there was none with that id. + pub async fn revoke( + &self, + plugin_id: &str, + publisher_fingerprint: &str, + id: &str, + ) -> Result { + let resolver = self + .profiles + .resolver(plugin_id, publisher_fingerprint, None) + .map_err(Self::describe)?; + let id = id.to_owned(); + self.storage + .run_for_host(&resolver, self.profiles.epoch(), move |namespace| { + namespace.revoke_intent_approval(&id) + }) + .await + .map_err(Self::describe) + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/app/src/plugin_host/confirmations/tests.rs b/crates/app/src/plugin_host/confirmations/tests.rs new file mode 100644 index 000000000..c551b6174 --- /dev/null +++ b/crates/app/src/plugin_host/confirmations/tests.rs @@ -0,0 +1,212 @@ +//! The window bridge and the settings list of remembered confirmations (task 10.10). + +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::Duration; + +use super::*; +use crate::plugin_host::intents::Operation; +use gamenode_platform::plugin_storage::IntentApproval; + +fn request() -> ConfirmationRequest { + ConfirmationRequest { + plugin_id: "org.example".into(), + publisher_fingerprint: "ab".repeat(32), + game_name: "Game one".into(), + operation: Operation::Install, + details: vec![], + launch_plan: None, + } +} + +/// A window that records what it was told and whether it is open. +fn window() -> (Emit, Arc>>, Arc) { + let seen = Arc::new(Mutex::new(Vec::new())); + let open = Arc::new(AtomicBool::new(true)); + let emit: Emit = { + let (seen, open) = (seen.clone(), open.clone()); + Arc::new(move |signal| { + seen.lock().unwrap().push(signal); + open.load(Ordering::SeqCst) + }) + }; + (emit, seen, open) +} + +async fn shown(seen: &Arc>>) -> PluginConfirmation { + for _ in 0..200 { + if let Some(Signal::Open(confirmation)) = seen.lock().unwrap().first().cloned() { + return *confirmation; + } + tokio::time::sleep(Duration::from_millis(5)).await; + } + panic!("nothing was shown"); +} + +#[tokio::test] +async fn the_window_is_shown_the_request_and_its_answer_comes_back_once() { + let (emit, seen, _) = window(); + let bridge = Arc::new(ConfirmationBridge::new(emit)); + let asking = tokio::spawn({ + let bridge = bridge.clone(); + async move { bridge.confirm(request()).await } + }); + let confirmation = shown(&seen).await; + assert_eq!( + ( + confirmation.plugin_id.as_str(), + confirmation.game_name.as_str(), + confirmation.operation.as_str(), + confirmation.timeout_seconds, + ), + ("org.example", "Game one", "install", 300) + ); + assert_eq!(confirmation.id.len(), 32); + + // An unknown id does nothing; the real one answers, and only once. + assert!(!bridge.answer("nothing", true, false)); + assert!(bridge.answer(&confirmation.id, true, true)); + assert!(!bridge.answer(&confirmation.id, false, false)); + assert_eq!( + asking.await.unwrap().unwrap(), + Answer { + approved: true, + remember: true + } + ); + // An answered confirmation is closed by the window itself: no second signal. + assert_eq!(seen.lock().unwrap().len(), 1); +} + +#[tokio::test] +async fn a_confirmation_that_stops_waiting_is_closed_in_the_window() { + let (emit, seen, _) = window(); + let bridge = Arc::new(ConfirmationBridge::new(emit)); + let asking = tokio::spawn({ + let bridge = bridge.clone(); + async move { bridge.confirm(request()).await } + }); + let confirmation = shown(&seen).await; + // The host stops waiting (the request was withdrawn, or the time ran out). + asking.abort(); + let _ = asking.await; + for _ in 0..200 { + if seen.lock().unwrap().len() == 2 { + break; + } + tokio::time::sleep(Duration::from_millis(5)).await; + } + assert_eq!( + seen.lock().unwrap()[1], + Signal::Closed(confirmation.id.clone()) + ); + // A late answer to a closed confirmation is ignored. + assert!(!bridge.answer(&confirmation.id, true, false)); +} + +#[tokio::test] +async fn with_no_window_nothing_can_be_asked() { + let (emit, _, open) = window(); + open.store(false, Ordering::SeqCst); + let bridge = ConfirmationBridge::new(emit); + let status = bridge.confirm(request()).await.unwrap_err(); + assert_eq!(status.code(), tonic::Code::Unavailable); +} + +#[tokio::test] +async fn the_settings_list_reads_and_revokes_a_plugins_remembered_confirmations() { + let temp = tempfile::tempdir().unwrap(); + let storage = Arc::new(PluginStorage::new(temp.path())); + let profiles = Arc::new(PluginProfiles::default()); + let approvals = PluginApprovals::new(storage.clone(), profiles.clone()); + let publisher = "ab".repeat(32); + + // No account profile: nothing to list. + assert!(approvals.list("org.example", &publisher).await.is_err()); + + profiles.update(Some("a"), true); + assert!( + approvals + .list("org.example", &publisher) + .await + .unwrap() + .is_empty() + ); + + // The host remembers a confirmation for the plugin (as a request's approval does). + let resolver = profiles.resolver("org.example", &publisher, None).unwrap(); + storage + .run_for_host(&resolver, profiles.epoch(), |namespace| { + let guard: crate::plugin_host::library::CommitGuard = Box::new(|| Ok(())); + namespace.save_intent_approval( + &IntentApproval { + id: "one".into(), + game_id: "3".into(), + installation_id: "inst".into(), + operation: "launch".into(), + target_revision: 0, + recipe_id: String::new(), + recipe_revision: 0, + plan_fingerprint: String::new(), + game_name: "Game".into(), + approved_at: 77, + }, + &guard, + ) + }) + .await + .unwrap(); + + let listed = approvals.list("org.example", &publisher).await.unwrap(); + assert_eq!( + listed, + [RememberedConfirmation { + id: "one".into(), + game_name: "Game".into(), + operation: "launch".into(), + approved_at: 77 + }] + ); + // Another plugin has none, and cannot revoke this one's. + assert!( + approvals + .list("org.other", &publisher) + .await + .unwrap() + .is_empty() + ); + assert!( + !approvals + .revoke("org.other", &publisher, "one") + .await + .unwrap() + ); + assert!( + approvals + .revoke("org.example", &publisher, "one") + .await + .unwrap() + ); + assert!( + !approvals + .revoke("org.example", &publisher, "one") + .await + .unwrap() + ); + assert!( + approvals + .list("org.example", &publisher) + .await + .unwrap() + .is_empty() + ); + + // A different account has its own (empty) list. + profiles.update(Some("b"), true); + assert!( + approvals + .list("org.example", &publisher) + .await + .unwrap() + .is_empty() + ); +} diff --git a/crates/app/src/plugin_host/file_approvals.rs b/crates/app/src/plugin_host/file_approvals.rs new file mode 100644 index 000000000..7063c1c3c --- /dev/null +++ b/crates/app/src/plugin_host/file_approvals.rs @@ -0,0 +1,487 @@ +//! Host-owned settings for file approvals and standing logical-library root approvals. +use std::path::PathBuf; +use std::sync::Arc; + +use gamenode_platform::plugin_files; +use gamenode_platform::plugin_storage::{ + ORIGIN_DECLARED, ORIGIN_USER, PluginLibraryRoot, PluginLibraryRow, operation, +}; +use serde::Serialize; +use tonic::Status; + +use super::files::{ + APPROVAL_TIMEOUT, AffectedGame, FileAccess, RootApprovalBridge, RootApprover, RootRequest, + RootScope, +}; +use super::library::{CommitGuard, LibraryFeed}; +use super::profile::PluginProfiles; +use super::storage::{Namespace, PluginStorage}; + +#[derive(Clone, Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PluginFolderApproval { + pub id: String, + pub plugin_id: String, + pub publisher_fingerprint: String, + pub installation_name: String, + pub kind: String, + pub root: String, + pub operations: Vec, + pub affected_games: Vec, + pub revoked: bool, + pub declared_by_plugin: bool, + pub logical_library: bool, + pub library_id: Option, + pub watching: Option, +} + +/// Reads and changes approvals for one authenticated plugin in the active account profile. +pub struct PluginFolderApprovals { + storage: Arc, + profiles: Arc, + files: Arc, + feed: Arc, + bridge: Arc, +} + +impl PluginFolderApprovals { + pub fn new( + storage: Arc, + profiles: Arc, + files: Arc, + feed: Arc, + bridge: Arc, + ) -> Self { + Self { + storage, + profiles, + files, + feed, + bridge, + } + } + + fn identity( + &self, + plugin_id: &str, + publisher: &str, + ) -> Result { + self.profiles + .resolver(plugin_id, publisher, None) + .map_err(|error| error.message().to_owned()) + } + + pub async fn list( + &self, + plugin_id: &str, + publisher: &str, + ) -> Result, String> { + let resolver = self.identity(plugin_id, publisher)?; + let epoch = self.profiles.epoch(); + let (approvals, libraries) = self + .storage + .run_for_host(&resolver, epoch, |namespace| { + Ok((namespace.file_approvals()?, namespace.plugin_libraries()?)) + }) + .await + .map_err(|error| error.message().to_owned())?; + let feed_names = self + .feed + .folders() + .into_iter() + .map(|entry| (entry.entry_key, entry.name)) + .collect::>(); + let mut result = approvals + .into_iter() + .map(|approval| { + let affected_games = approval + .affected + .iter() + .filter_map(|key| feed_names.get(key).cloned()) + .collect(); + PluginFolderApproval { + id: approval.id, + plugin_id: plugin_id.to_owned(), + publisher_fingerprint: publisher.to_owned(), + installation_name: approval.installation_id, + kind: approval.kind, + root: approval.root, + operations: operation_names(approval.operations), + affected_games, + revoked: approval.revoked_at.is_some(), + declared_by_plugin: approval.origin == ORIGIN_DECLARED, + logical_library: false, + library_id: None, + watching: None, + } + }) + .collect::>(); + for library in libraries.into_iter().filter(|row| !row.removed) { + result.extend(library.roots.into_iter().map(|root| PluginFolderApproval { + id: root.id, + plugin_id: plugin_id.to_owned(), + publisher_fingerprint: publisher.to_owned(), + installation_name: library.name.clone(), + kind: "library".to_owned(), + root: root.path, + operations: vec![ + "read".to_owned(), + "plugin_discovery".to_owned(), + "core_executable_discovery".to_owned(), + ], + affected_games: Vec::new(), + revoked: false, + declared_by_plugin: root.declared, + logical_library: true, + library_id: Some(library.id.clone()), + watching: Some(root.watching), + })); + } + result.sort_by(|left, right| { + left.installation_name + .cmp(&right.installation_name) + .then(left.kind.cmp(&right.kind)) + }); + Ok(result) + } + + pub async fn revoke(&self, plugin_id: &str, publisher: &str, id: &str) -> Result { + let resolver = self.identity(plugin_id, publisher)?; + let epoch = self.profiles.epoch(); + let id = id.to_owned(); + let profiles = self.profiles.clone(); + self.storage + .run_for_host(&resolver, epoch, move |namespace| { + if namespace + .file_approvals()? + .iter() + .any(|approval| approval.id == id) + { + return namespace.revoke_approval(&id); + } + let Some((mut library, _)) = find_logical_root(namespace, &id)? else { + return Ok(false); + }; + let expected = library.revision; + library.roots.retain(|root| root.id != id); + let guard = profile_guard(profiles, epoch); + namespace.put_plugin_library(library, expected, &guard)?; + Ok(true) + }) + .await + .map_err(|error| error.message().to_owned()) + } + + /// Stops or resumes Core discovery for one standing logical-library root. File access still + /// requires the independent Files grant and per-installation approval. + pub async fn set_watching( + &self, + plugin_id: &str, + publisher: &str, + id: &str, + watching: bool, + ) -> Result { + let resolver = self.identity(plugin_id, publisher)?; + let epoch = self.profiles.epoch(); + let id = id.to_owned(); + let profiles = self.profiles.clone(); + self.storage + .run_for_host(&resolver, epoch, move |namespace| { + let Some((mut library, mut root)) = find_logical_root(namespace, &id)? else { + return Ok(false); + }; + if root.watching == watching { + return Ok(false); + } + let expected = library.revision; + root.watching = watching; + if let Some(target) = library.roots.iter_mut().find(|target| target.id == id) { + *target = root; + } + let guard = profile_guard(profiles, epoch); + namespace.put_plugin_library(library, expected, &guard)?; + Ok(true) + }) + .await + .map_err(|error| error.message().to_owned()) + } + + /// Replaces the selected root of an existing per-installation file approval after a fresh + /// user selection and confirmation. The persisted approval swap fences old handles. + pub async fn change_root( + &self, + plugin_id: &str, + publisher: &str, + id: &str, + ) -> Result<(), String> { + let resolver = self.identity(plugin_id, publisher)?; + let epoch = self.profiles.epoch(); + let _waiting = self + .files + .begin_approval(*resolver.storage_owner().key()) + .ok_or_else(|| "a folder approval is already pending for this plugin".to_owned())?; + let approval_id = id.to_owned(); + let current = self + .storage + .run_for_host(&resolver, epoch, move |namespace| { + namespace + .approval(&approval_id)? + .ok_or_else(|| Status::not_found("folder approval not found")) + }) + .await + .map_err(|error| error.message().to_owned())?; + if current.revoked_at.is_some() { + return Err("folder approval is revoked".into()); + } + + let operations = operation_names_static(current.operations); + let request = RootRequest { + plugin_id: plugin_id.to_owned(), + publisher_fingerprint: publisher.to_owned(), + installation_name: current.installation_id.clone(), + kind: current.kind.clone(), + operations: operations.clone(), + previously_approved: Some(super::files::PreviousRootApproval { + root: PathBuf::from(¤t.root), + operations: operations.clone(), + }), + suggested: None, + declared: Vec::new(), + preselected: Some(PathBuf::from(¤t.root)), + }; + let chosen = tokio::time::timeout(APPROVAL_TIMEOUT, self.bridge.choose_root(request)) + .await + .map_err(|_| "folder selection timed out".to_owned())? + .map_err(|error| error.message().to_owned())? + .ok_or_else(|| "folder change cancelled".to_owned())?; + + let files = self.files.clone(); + let feed = self.feed.clone(); + let (root, overlapping, volume_token) = tokio::task::spawn_blocking(move || { + let root = plugin_files::approve_root(&chosen, &files.reserved) + .map_err(|_| Status::failed_precondition("folder cannot be approved"))?; + let overlapping = files.overlapping(&feed, &root.path); + let volume_token = gamenode_platform::volume::volume_info(&root.path) + .map(|volume| volume.volume_identity_token) + .filter(|token| !token.is_empty()) + .ok_or_else(|| Status::failed_precondition("volume identity is unavailable"))?; + Ok::<_, Status>((root, overlapping, volume_token)) + }) + .await + .map_err(|_| "folder validation failed".to_owned())? + .map_err(|error| error.message().to_owned())?; + let scope = RootScope { + plugin_id: plugin_id.to_owned(), + publisher_fingerprint: publisher.to_owned(), + installation_name: current.installation_id.clone(), + kind: current.kind.clone(), + operations, + root: root.path.clone(), + declared_by_plugin: false, + affected: overlapping + .iter() + .map(|entry| AffectedGame { + name: entry.name.clone(), + game_id: entry.game_id, + }) + .collect(), + }; + if !tokio::time::timeout(APPROVAL_TIMEOUT, self.bridge.confirm(scope)) + .await + .map_err(|_| "folder approval timed out".to_owned())? + .map_err(|error| error.message().to_owned())? + { + return Err("folder change declined".into()); + } + if self.profiles.epoch() != epoch { + return Err("account profile changed while approval was open".into()); + } + + let mut replacement = current; + let mut bytes = [0_u8; 16]; + getrandom::fill(&mut bytes).map_err(|_| "no source of randomness".to_owned())?; + replacement.id = bytes.iter().map(|byte| format!("{byte:02x}")).collect(); + replacement.root = root + .path + .to_str() + .ok_or("folder path is not valid Unicode")? + .to_owned(); + replacement.root_volume = root.identity.volume; + replacement.root_node = root.identity.node; + replacement.volume_token = volume_token; + replacement.affected = super::files::affected_keys(&overlapping); + replacement.revoked_at = None; + replacement.origin = ORIGIN_USER.to_owned(); + replacement.approved_at = 0; + let profiles = self.profiles.clone(); + self.storage + .run_for_host(&resolver, epoch, move |namespace| { + let guard = profile_guard(profiles, epoch); + namespace.save_approval(&replacement, &guard) + }) + .await + .map_err(|error| error.message().to_owned()) + } +} + +fn find_logical_root( + namespace: &mut Namespace<'_>, + id: &str, +) -> Result, Status> { + for library in namespace + .plugin_libraries()? + .into_iter() + .filter(|row| !row.removed) + { + if let Some(root) = library.roots.iter().find(|root| root.id == id).cloned() { + return Ok(Some((library, root))); + } + } + Ok(None) +} + +fn profile_guard(profiles: Arc, epoch: u64) -> CommitGuard { + Box::new(move || { + if profiles.epoch() == epoch { + Ok(()) + } else { + Err(Status::failed_precondition("account profile changed")) + } + }) +} + +fn operation_names(operations: u8) -> Vec { + operation_names_static(operations) + .into_iter() + .map(str::to_owned) + .collect() +} + +fn operation_names_static(operations: u8) -> Vec<&'static str> { + [ + (operation::READ, "read"), + (operation::WRITE, "write"), + (operation::DELETE, "delete"), + ] + .into_iter() + .filter_map(|(bit, name)| (operations & bit != 0).then_some(name)) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + use gamenode_platform::plugin_storage::FileApproval; + + #[tokio::test] + async fn settings_list_can_revoke_file_scopes_and_manage_logical_root_monitoring() { + let temp = tempfile::tempdir().unwrap(); + let storage = Arc::new(PluginStorage::new(temp.path())); + let profiles = Arc::new(PluginProfiles::default()); + profiles.update(Some("account"), true); + let publisher = "ab".repeat(32); + let resolver = profiles.resolver("org.example", &publisher, None).unwrap(); + storage + .run_for_host(&resolver, profiles.epoch(), |namespace| { + let guard: CommitGuard = Box::new(|| Ok(())); + namespace.save_approval( + &FileApproval { + id: "file-approval".into(), + installation_id: "installation-1".into(), + game_id: "42".into(), + kind: "save".into(), + root: "/games/saves".into(), + volume_token: "volume".into(), + root_volume: 1, + root_node: 2, + operations: operation::READ, + affected: vec!["entry-1".into()], + approved_at: 100, + revoked_at: None, + origin: ORIGIN_USER.into(), + }, + &guard, + )?; + namespace.put_plugin_library( + PluginLibraryRow { + id: "library-1".into(), + name: "Scanned games".into(), + description: "Fixture".into(), + revision: 0, + removed: false, + roots: vec![PluginLibraryRoot { + id: "root-1".into(), + name: "Games".into(), + path: "/games".into(), + volume: 1, + node: 3, + volume_token: "volume".into(), + declared: true, + watching: true, + }], + }, + 0, + &guard, + )?; + Ok(()) + }) + .await + .unwrap(); + + let bridge = Arc::new(RootApprovalBridge::new(Arc::new(|_| true))); + let feed = LibraryFeed::new(); + let files = Arc::new(FileAccess::default()); + let approvals = PluginFolderApprovals::new(storage, profiles, files, feed, bridge); + + let listed = approvals.list("org.example", &publisher).await.unwrap(); + assert_eq!(listed.len(), 2); + assert!(listed.iter().any(|item| item.id == "root-1" + && item.logical_library + && item.watching == Some(true))); + assert!( + listed + .iter() + .any(|item| item.id == "file-approval" && item.operations == ["read"]) + ); + + assert!( + approvals + .set_watching("org.example", &publisher, "root-1", false) + .await + .unwrap() + ); + assert!( + approvals + .revoke("org.example", &publisher, "root-1") + .await + .unwrap() + ); + assert!( + approvals + .revoke("org.example", &publisher, "file-approval") + .await + .unwrap() + ); + assert!( + !approvals + .revoke("org.example", &publisher, "file-approval") + .await + .unwrap() + ); + + let listed = approvals.list("org.example", &publisher).await.unwrap(); + let file = listed + .iter() + .find(|item| item.id == "file-approval") + .unwrap(); + assert!(file.revoked); + assert!(listed.iter().all(|item| item.id != "root-1")); + assert!( + approvals + .list("org.other", &publisher) + .await + .unwrap() + .is_empty() + ); + } +} diff --git a/crates/app/src/plugin_host/files.rs b/crates/app/src/plugin_host/files.rs new file mode 100644 index 000000000..dca9f4886 --- /dev/null +++ b/crates/app/src/plugin_host/files.rs @@ -0,0 +1,530 @@ +//! Host side of the plugins' file access: who approves a folder, how handles are issued, and +//! which games a folder affects. +//! +//! A plugin never names a path. It asks (`FilesRequestAccess`) for access to one installation of +//! a game; the host asks the *user*, through a [`RootApprover`], to choose the folder and to +//! confirm the final scope, and keeps the approval per plugin and account profile +//! ([`gamenode_platform::plugin_storage::FileApproval`]). The plugin gets opaque handles: sealed +//! tokens ([`gamenode_platform::sealed::Sealer`]) that carry the approval and a relative path, +//! bound to the session that received them, so they cannot be read, forged, edited, shared with +//! another session or kept past the session. Every use re-derives what the handle may do from +//! the stored approval, the plugin's current grants and the folder as it is on disk now. + +use std::collections::{HashMap, HashSet}; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +use async_trait::async_trait; +use gamenode_platform::plugin_files::Reserved; +use gamenode_platform::sealed::Sealer; +use tokio::sync::oneshot; +use tonic::Status; + +use super::library::{EntryFolder, LibraryFeed}; + +/// What a folder is for. A plugin may ask for any of them for one installation. +pub const KINDS: [&str; 3] = ["installation", "save", "prefix"]; +/// The most bytes one read returns when the caller names no limit. +pub const DEFAULT_READ_BYTES: usize = 1024 * 1024; +/// The most bytes one read returns, and the most one write carries. +pub const MAX_CHUNK_BYTES: usize = 4 * 1024 * 1024; +/// How long the user has to answer an approval before it counts as declined. +pub const APPROVAL_TIMEOUT: Duration = Duration::from_secs(5 * 60); +/// How long the canonical form of a library folder is remembered. +const FOLDER_TTL: Duration = Duration::from_secs(60); +const HANDLE: u8 = 1; +const CURSOR: u8 = 2; +/// The longest relative path a handle carries, in bytes. +const MAX_HANDLE_PATH: usize = 2048; + +/// What the host asks the user to choose. +#[derive(Clone, Debug)] +pub struct RootRequest { + pub plugin_id: String, + pub publisher_fingerprint: String, + /// The library name of the installation, never a path. + pub installation_name: String, + pub kind: String, + /// `read`, `write` and `delete`, the ones the plugin asked for. + pub operations: Vec<&'static str>, + /// The prior scope when this request adds operations to an existing approval. The user must + /// see both this scope and the addition before approving the wider access. + pub previously_approved: Option, + /// Where the installation lives, to start the choice there; `None` when unknown. The host + /// knows it from the library, so it is trustworthy (installation kind only). + pub suggested: Option, + /// Folders the plugin suggested for this kind, in the plugin's priority order. They are + /// **declared by the plugin and not verified**: the dialog must label them so, and a plugin + /// can neither learn which exist nor which the user took. + pub declared: Vec, + /// The folder to start on: the first existing plugin-declared suggestion, then the host's + /// own suggestion. `None` when there is nothing to propose. + pub preselected: Option, +} + +#[derive(Clone, Debug)] +pub struct PreviousRootApproval { + pub root: PathBuf, + pub operations: Vec<&'static str>, +} + +/// A folder a plugin suggested, expanded for this system. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct DeclaredFolder { + pub path: PathBuf, + /// One line of plain text from the plugin; show it as text, never as markup. + pub description: String, + /// Whether the folder exists now (checked only for its existence; nothing was listed or read). + pub exists: bool, +} + +/// A game that shares the chosen folder. +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct AffectedGame { + pub name: String, + pub game_id: Option, +} + +/// The final scope the user confirms: exactly what the approval will allow. +#[derive(Clone, Debug)] +pub struct RootScope { + pub plugin_id: String, + pub publisher_fingerprint: String, + pub installation_name: String, + pub kind: String, + pub operations: Vec<&'static str>, + pub root: PathBuf, + /// Whether the chosen folder is one the plugin suggested (compared by canonical path), as + /// opposed to one the user picked or the host suggested. + pub declared_by_plugin: bool, + /// Every library entry whose folder is the root, inside it or contains it: the complete + /// set the approval covers. + pub affected: Vec, +} + +/// The user's side of a file approval. The host calls it off the UI thread, and a call that +/// takes longer than [`APPROVAL_TIMEOUT`] counts as declined. +#[async_trait] +pub trait RootApprover: Send + Sync { + /// Lets the user choose the folder. `None` is a refusal. + async fn choose_root(&self, request: RootRequest) -> Result, Status>; + /// Shows the final scope and asks for consent. + async fn confirm(&self, scope: RootScope) -> Result; +} + +/// The window event that asks the user to choose a folder for a plugin. +pub const ROOT_SELECT_EVENT: &str = "plugin:folder-approval-select"; +/// The window event that asks the user to approve the selected folder's scope. +pub const ROOT_CONFIRM_EVENT: &str = "plugin:folder-approval-confirm"; +/// The window event that closes a folder prompt that was withdrawn or timed out. +pub const ROOT_CLOSED_EVENT: &str = "plugin:folder-approval-closed"; + +/// Plain event data for choosing the folder. Plugin supplied descriptions and paths are shown as +/// text; declared suggestions are explicitly unverified and never imply approval. +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct RootSelectionPrompt { + pub id: String, + pub plugin_id: String, + pub publisher_fingerprint: String, + pub installation_name: String, + pub kind: String, + pub operations: Vec<&'static str>, + pub previously_approved: Option, + pub suggested: Option, + pub preselected: Option, + pub declared: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PreviousRootApprovalPrompt { + pub root: String, + pub operations: Vec<&'static str>, +} + +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct DeclaredFolderPrompt { + pub path: String, + pub description: String, + pub exists: bool, +} + +/// Plain event data for the final approval. `root` is intentionally shown so the user can see +/// the exact canonicalized location and all library entries affected by it. +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct RootConfirmationPrompt { + pub id: String, + pub plugin_id: String, + pub publisher_fingerprint: String, + pub installation_name: String, + pub kind: String, + pub operations: Vec<&'static str>, + pub root: String, + pub declared_by_plugin: bool, + pub affected: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum RootApprovalSignal { + Select(RootSelectionPrompt), + Confirm(RootConfirmationPrompt), + Closed(String), +} + +pub type RootApprovalEmit = Arc bool + Send + Sync>; +enum RootAnswer { + Selected(oneshot::Sender>), + Confirmed(oneshot::Sender), +} + +/// Bridges host approval requests to the React window without making the host wait on the UI +/// thread. The five-minute timeout remains owned by the call site in the resource host. +pub struct RootApprovalBridge { + emit: RootApprovalEmit, + waiting: Mutex>, +} + +struct ForgetRootPrompt<'a> { + bridge: &'a RootApprovalBridge, + id: String, +} + +impl Drop for ForgetRootPrompt<'_> { + fn drop(&mut self) { + let removed = self + .bridge + .waiting + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .remove(&self.id) + .is_some(); + if removed { + (self.bridge.emit)(RootApprovalSignal::Closed(self.id.clone())); + } + } +} + +impl RootApprovalBridge { + pub fn new(emit: RootApprovalEmit) -> Self { + Self { + emit, + waiting: Mutex::default(), + } + } + + fn id() -> Result { + let mut bytes = [0_u8; 16]; + getrandom::fill(&mut bytes).map_err(|_| Status::internal("no source of randomness"))?; + Ok(bytes.iter().map(|byte| format!("{byte:02x}")).collect()) + } + + pub fn answer_selection(&self, id: &str, selected: Option) -> bool { + let answer = self + .waiting + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .remove(id); + match answer { + Some(RootAnswer::Selected(sender)) => sender.send(selected).is_ok(), + Some(answer) => { + self.waiting + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .insert(id.to_owned(), answer); + false + } + None => false, + } + } + + pub fn answer_confirmation(&self, id: &str, approved: bool) -> bool { + let answer = self + .waiting + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .remove(id); + match answer { + Some(RootAnswer::Confirmed(sender)) => sender.send(approved).is_ok(), + Some(answer) => { + self.waiting + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .insert(id.to_owned(), answer); + false + } + None => false, + } + } + + async fn choose(&self, request: RootRequest) -> Result, Status> { + let id = Self::id()?; + let (send, receive) = oneshot::channel(); + self.waiting + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .insert(id.clone(), RootAnswer::Selected(send)); + let _forget = ForgetRootPrompt { + bridge: self, + id: id.clone(), + }; + let shown = (self.emit)(RootApprovalSignal::Select(RootSelectionPrompt { + id, + plugin_id: request.plugin_id, + publisher_fingerprint: request.publisher_fingerprint, + installation_name: request.installation_name, + kind: request.kind, + operations: request.operations, + previously_approved: request.previously_approved.map(|previous| { + PreviousRootApprovalPrompt { + root: previous.root.to_string_lossy().into_owned(), + operations: previous.operations, + } + }), + suggested: request + .suggested + .map(|path| path.to_string_lossy().into_owned()), + preselected: request + .preselected + .map(|path| path.to_string_lossy().into_owned()), + declared: request + .declared + .into_iter() + .map(|folder| DeclaredFolderPrompt { + path: folder.path.to_string_lossy().into_owned(), + description: folder.description, + exists: folder.exists, + }) + .collect(), + })); + if !shown { + return Err(Status::unavailable("there is no window to ask the user in")); + } + receive + .await + .map_err(|_| Status::unavailable("the folder selection was closed")) + } + + async fn confirm_scope(&self, scope: RootScope) -> Result { + let id = Self::id()?; + let (send, receive) = oneshot::channel(); + self.waiting + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .insert(id.clone(), RootAnswer::Confirmed(send)); + let _forget = ForgetRootPrompt { + bridge: self, + id: id.clone(), + }; + let shown = (self.emit)(RootApprovalSignal::Confirm(RootConfirmationPrompt { + id, + plugin_id: scope.plugin_id, + publisher_fingerprint: scope.publisher_fingerprint, + installation_name: scope.installation_name, + kind: scope.kind, + operations: scope.operations, + root: scope.root.to_string_lossy().into_owned(), + declared_by_plugin: scope.declared_by_plugin, + affected: scope.affected, + })); + if !shown { + return Err(Status::unavailable("there is no window to ask the user in")); + } + receive + .await + .map_err(|_| Status::unavailable("the folder approval was closed")) + } +} + +#[async_trait] +impl RootApprover for RootApprovalBridge { + async fn choose_root(&self, request: RootRequest) -> Result, Status> { + Ok(self.choose(request).await?.map(PathBuf::from)) + } + + async fn confirm(&self, scope: RootScope) -> Result { + self.confirm_scope(scope).await + } +} + +/// File access state shared by every plugin session. +pub struct FileAccess { + pub(crate) reserved: Reserved, + approver: Mutex>>, + runtime_approver: Mutex>>, + sealer: Sealer, + waiting: Mutex>, + canonical: Mutex)>>, +} + +impl Default for FileAccess { + fn default() -> Self { + Self::new(Reserved::default()) + } +} + +impl FileAccess { + /// `reserved` are the host folders no plugin may reach, such as the application data folder. + pub fn new(reserved: Reserved) -> Self { + Self { + reserved, + approver: Mutex::default(), + runtime_approver: Mutex::default(), + sealer: Sealer::new(), + waiting: Mutex::default(), + canonical: Mutex::default(), + } + } + + /// Connects the user's side. Until it is set, a new approval cannot be made (existing ones + /// keep working). + pub fn set_approver(&self, approver: Arc) { + *self.approver.lock().unwrap_or_else(|p| p.into_inner()) = Some(approver); + } + + pub(crate) fn approver(&self) -> Option> { + self.approver + .lock() + .unwrap_or_else(|p| p.into_inner()) + .clone() + } + + /// Connects the runtime picker. Until it is set, a plugin cannot request a new runtime + /// approval (existing approved runtimes keep launching). + pub fn set_runtime_approver(&self, approver: Arc) { + *self + .runtime_approver + .lock() + .unwrap_or_else(|p| p.into_inner()) = Some(approver); + } + + pub(crate) fn runtime_approver( + &self, + ) -> Option> { + self.runtime_approver + .lock() + .unwrap_or_else(|p| p.into_inner()) + .clone() + } + + /// Marks an approval of this namespace as waiting for the user. Only one at a time: the + /// user is never asked twice at once by one plugin. + pub(crate) fn begin_approval(self: &Arc, owner: [u8; 32]) -> Option { + let mut waiting = self.waiting.lock().unwrap_or_else(|p| p.into_inner()); + waiting.insert(owner).then(|| Waiting { + access: self.clone(), + owner, + }) + } + + /// A handle for `path` below the approval `approval_id`, usable only by `session_id`. + pub(crate) fn seal_handle( + &self, + session_id: &str, + approval_id: &str, + path: &[String], + ) -> String { + let mut payload = approval_id.as_bytes().to_vec(); + for part in path { + payload.push(0); + payload.extend_from_slice(part.as_bytes()); + } + self.sealer.seal(HANDLE, session_id, &payload) + } + + /// The approval id and relative path in a handle this session was given. + pub(crate) fn open_handle( + &self, + session_id: &str, + handle: &str, + ) -> Option<(String, Vec)> { + let payload = self.sealer.open(HANDLE, session_id, handle)?; + if payload.len() > MAX_HANDLE_PATH + 256 { + return None; + } + let mut parts = payload.split(|byte| *byte == 0); + let approval = String::from_utf8(parts.next()?.to_vec()).ok()?; + let path = parts + .map(|part| String::from_utf8(part.to_vec()).ok()) + .collect::>>()?; + Some((approval, path)) + } + + /// Whether a path of this size can be put in a handle. + pub(crate) fn fits_handle(path: &[String]) -> bool { + path.iter().map(|part| part.len() + 1).sum::() <= MAX_HANDLE_PATH + } + + /// A paging cursor over the directory behind `handle`, resuming after `last`. + pub(crate) fn seal_cursor(&self, session_id: &str, handle: &str, last: &str) -> String { + self.sealer + .seal(CURSOR, &format!("{session_id}\n{handle}"), last.as_bytes()) + } + + pub(crate) fn open_cursor( + &self, + session_id: &str, + handle: &str, + cursor: &str, + ) -> Option { + let payload = self + .sealer + .open(CURSOR, &format!("{session_id}\n{handle}"), cursor)?; + String::from_utf8(payload).ok() + } + + /// The library entries whose folder is `root`, lies inside it or contains it, in entry-key + /// order. Blocking: canonicalizes library folders (briefly remembered). + pub(crate) fn overlapping(&self, feed: &LibraryFeed, root: &Path) -> Vec { + let now = Instant::now(); + let mut cache = self.canonical.lock().unwrap_or_else(|p| p.into_inner()); + cache.retain(|_, (at, _)| now.duration_since(*at) < FOLDER_TTL); + feed.folders() + .into_iter() + .filter(|entry| { + let (_, canonical) = cache + .entry(entry.folder.clone()) + .or_insert_with(|| (now, std::fs::canonicalize(&entry.folder).ok())); + // A folder that no longer exists is compared as written. + let folder = canonical + .clone() + .unwrap_or_else(|| PathBuf::from(&entry.folder)); + folder.starts_with(root) || root.starts_with(&folder) + }) + .collect() + } +} + +/// Releases a namespace's pending-approval slot when dropped. +pub(crate) struct Waiting { + access: Arc, + owner: [u8; 32], +} + +impl Drop for Waiting { + fn drop(&mut self) { + self.access + .waiting + .lock() + .unwrap_or_else(|p| p.into_inner()) + .remove(&self.owner); + } +} + +/// The sorted entry keys of `entries`, the form an approval records. +pub(crate) fn affected_keys(entries: &[EntryFolder]) -> Vec { + let mut keys: Vec = entries + .iter() + .map(|entry| entry.entry_key.clone()) + .collect(); + keys.sort(); + keys.dedup(); + keys +} + +#[cfg(all(test, unix))] +mod tests; diff --git a/crates/app/src/plugin_host/files/tests.rs b/crates/app/src/plugin_host/files/tests.rs new file mode 100644 index 000000000..3b74132da --- /dev/null +++ b/crates/app/src/plugin_host/files/tests.rs @@ -0,0 +1,250 @@ +use std::os::unix::fs::symlink; + +use super::*; +use crate::plugin_host::library::LibrarySource; +use std::time::Duration; + +fn root_window() -> (RootApprovalEmit, Arc>>) { + let seen = Arc::new(Mutex::new(Vec::new())); + let emit = { + let seen = seen.clone(); + Arc::new(move |signal| { + seen.lock().unwrap().push(signal); + true + }) as RootApprovalEmit + }; + (emit, seen) +} + +async fn next_root_signal( + seen: &Arc>>, + index: usize, +) -> RootApprovalSignal { + for _ in 0..200 { + if let Some(signal) = seen.lock().unwrap().get(index).cloned() { + return signal; + } + tokio::time::sleep(Duration::from_millis(5)).await; + } + panic!("no folder prompt was emitted"); +} + +fn root_request() -> RootRequest { + RootRequest { + plugin_id: "org.example".into(), + publisher_fingerprint: "ab".repeat(32), + installation_name: "Game".into(), + kind: "save".into(), + operations: vec!["read", "write"], + previously_approved: Some(PreviousRootApproval { + root: PathBuf::from("/games/saves"), + operations: vec!["read"], + }), + suggested: None, + declared: vec![DeclaredFolder { + path: PathBuf::from("/plugin/suggested"), + description: "Saves".into(), + exists: true, + }], + preselected: Some(PathBuf::from("/plugin/suggested")), + } +} + +fn path(parts: &[&str]) -> Vec { + parts.iter().map(|part| (*part).to_owned()).collect() +} + +fn source(key: &str, folder: &Path) -> LibrarySource { + LibrarySource { + entry_key: key.into(), + provider_id: "p".into(), + game_id: None, + name: key.into(), + install_state: crate::plugin_host::library::InstallState::Installed, + display_name: None, + metadata_revision: 0, + artwork_revision: 0, + install_dir: folder.to_string_lossy().into_owned(), + detected_target: None, + } +} + +#[test] +fn handles_round_trip_their_approval_and_path_and_only_for_their_session() { + let access = FileAccess::default(); + let handle = access.seal_handle("s1", "approval-1", &path(&["saves", "slot 1.sav"])); + assert_eq!( + access.open_handle("s1", &handle), + Some(("approval-1".to_owned(), path(&["saves", "slot 1.sav"]))) + ); + let root = access.seal_handle("s1", "approval-1", &[]); + assert_eq!( + access.open_handle("s1", &root), + Some(("approval-1".to_owned(), vec![])) + ); + assert_eq!(access.open_handle("s2", &handle), None, "another session"); + assert_eq!( + FileAccess::default().open_handle("s1", &handle), + None, + "another process" + ); + // Neither the approval id nor any name can be read from a handle. + assert!(!handle.contains("approval") && !handle.contains("saves")); + assert_ne!( + handle, + access.seal_handle("s1", "approval-1", &path(&["saves", "slot 1.sav"])) + ); +} + +#[test] +fn a_cursor_is_bound_to_its_session_and_directory_and_is_not_a_handle() { + let access = FileAccess::default(); + let cursor = access.seal_cursor("s1", "dir-handle", "last-name"); + assert_eq!( + access.open_cursor("s1", "dir-handle", &cursor).as_deref(), + Some("last-name") + ); + assert_eq!(access.open_cursor("s1", "other-dir", &cursor), None); + assert_eq!(access.open_cursor("s2", "dir-handle", &cursor), None); + assert_eq!(access.open_handle("s1", &cursor), None); + let handle = access.seal_handle("s1", "a", &[]); + assert_eq!(access.open_cursor("s1", &handle, &handle), None); +} + +#[test] +fn paths_too_long_for_a_handle_are_refused_up_front() { + assert!(FileAccess::fits_handle(&path(&["a", "b"]))); + assert!(!FileAccess::fits_handle(&vec!["x".repeat(255); 9])); +} + +#[test] +fn only_one_approval_per_namespace_waits_at_a_time() { + let access = Arc::new(FileAccess::default()); + let first = access.begin_approval([1; 32]).expect("the first may wait"); + assert!(access.begin_approval([1; 32]).is_none()); + assert!( + access.begin_approval([2; 32]).is_some(), + "another plugin is independent" + ); + drop(first); + assert!( + access.begin_approval([1; 32]).is_some(), + "the slot is released" + ); +} + +#[tokio::test] +async fn the_window_bridge_correlates_folder_selection_and_scope_answers() { + let (emit, seen) = root_window(); + let bridge = Arc::new(RootApprovalBridge::new(emit)); + let selecting = tokio::spawn({ + let bridge = bridge.clone(); + async move { bridge.choose_root(root_request()).await } + }); + let RootApprovalSignal::Select(selection) = next_root_signal(&seen, 0).await else { + panic!("expected a folder selection prompt"); + }; + assert_eq!(selection.plugin_id, "org.example"); + assert_eq!( + selection.previously_approved.as_ref().unwrap().operations, + ["read"] + ); + assert_eq!(selection.declared[0].path, "/plugin/suggested"); + assert!(!bridge.answer_confirmation(&selection.id, true)); + assert!(bridge.answer_selection(&selection.id, Some("/games/new-saves".into()))); + assert_eq!( + selecting.await.unwrap().unwrap(), + Some(PathBuf::from("/games/new-saves")) + ); + + let confirming = tokio::spawn({ + let bridge = bridge.clone(); + async move { + bridge + .confirm(RootScope { + plugin_id: "org.example".into(), + publisher_fingerprint: "ab".repeat(32), + installation_name: "Game".into(), + kind: "save".into(), + operations: vec!["read", "write"], + root: PathBuf::from("/games/new-saves"), + declared_by_plugin: false, + affected: vec![AffectedGame { + name: "Game".into(), + game_id: Some(42), + }], + }) + .await + } + }); + let RootApprovalSignal::Confirm(scope) = next_root_signal(&seen, 1).await else { + panic!("expected a scope confirmation prompt"); + }; + assert_eq!(scope.root, "/games/new-saves"); + assert_eq!(scope.affected[0].name, "Game"); + assert!(bridge.answer_confirmation(&scope.id, true)); + assert!(confirming.await.unwrap().unwrap()); +} + +#[tokio::test(start_paused = true)] +async fn a_folder_prompt_closes_when_the_five_minute_limit_expires() { + let (emit, seen) = root_window(); + let bridge = Arc::new(RootApprovalBridge::new(emit)); + let request = tokio::spawn({ + let bridge = bridge.clone(); + async move { tokio::time::timeout(APPROVAL_TIMEOUT, bridge.choose_root(root_request())).await } + }); + let RootApprovalSignal::Select(selection) = next_root_signal(&seen, 0).await else { + panic!("expected a folder selection prompt"); + }; + tokio::time::advance(APPROVAL_TIMEOUT).await; + assert!(request.await.unwrap().is_err()); + assert_eq!( + seen.lock().unwrap().last(), + Some(&RootApprovalSignal::Closed(selection.id)) + ); +} + +#[test] +fn games_overlap_a_root_when_inside_equal_or_containing_it_even_through_links() { + let temp = tempfile::tempdir().unwrap(); + let base = std::fs::canonicalize(temp.path()).unwrap(); + for dir in ["games/a", "games/b", "other", "real/c"] { + std::fs::create_dir_all(base.join(dir)).unwrap(); + } + // A library folder reached through a link still counts for what it really is. + symlink(base.join("real/c"), base.join("games/c-link")).unwrap(); + let feed = LibraryFeed::new(); + feed.sync(vec![ + source("a", &base.join("games/a")), + source("b", &base.join("games/b")), + source("c", &base.join("games/c-link")), + source("o", &base.join("other")), + source("gone", &base.join("games/deleted")), + source("none", Path::new("")), + ]); + let access = FileAccess::default(); + let keys = |root: &Path| affected_keys(&access.overlapping(&feed, root)); + + assert_eq!(keys(&base.join("games/a")), ["a"], "equal"); + assert_eq!( + keys(&base.join("games/a/saves")), + ["a"], + "a folder inside a game" + ); + assert_eq!( + keys(&base.join("games")), + ["a", "b", "gone"], + "a parent holds its games" + ); + assert_eq!(keys(&base.join("real")), ["c"], "the link's real location"); + assert_eq!(keys(&base.join("real/c")), ["c"]); + assert_eq!( + keys(&base), + ["a", "b", "c", "gone", "o"], + "the empty folder never matches" + ); + assert_eq!(keys(&base.join("unrelated")), Vec::::new()); + // A sibling whose name merely starts the same is not inside. + assert_eq!(keys(&base.join("games/a2")), Vec::::new()); +} diff --git a/crates/app/src/plugin_host/fingerprints.rs b/crates/app/src/plugin_host/fingerprints.rs new file mode 100644 index 000000000..c5bae6ac8 --- /dev/null +++ b/crates/app/src/plugin_host/fingerprints.rs @@ -0,0 +1,430 @@ +//! Content fingerprints of approved places and their comparison (task 13.4, design section 12). +//! +//! A fingerprint is built from the *content* of the files, read again every time: a SHA-256 for +//! each file and one digest for the whole tree. Size and modification time are never taken as +//! proof of equality in either direction. The tree digest (`sha256-tree-v1`) is the SHA-256 of a +//! domain tag followed, for each entry in the order of its label's UTF-8 bytes, by the label's +//! length (8 bytes, big endian) and bytes, a type byte (0 directory, 1 file), the logical size +//! (8 bytes, big endian) and the file's own SHA-256 (32 zero bytes for a directory). Empty +//! directories are entries, case is kept, and a rename is a removal plus an addition. Dates and +//! permissions are metadata, not input. +//! +//! A snapshot keeps every entry's digest so two of them can be compared. It says whether it is +//! *complete*: a file that could not be read, changed while it was read, or a walk that was cut +//! makes it incomplete, and an incomplete snapshot never yields a digest or an "unchanged" +//! verdict. The consistency is `best_effort`: the files are not frozen while they are read. +//! +//! Snapshots live in the host's memory, a few per plugin, for an hour. + +use std::collections::HashMap; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +use sha2::{Digest, Sha256}; +use tonic::Status; + +use super::jobs::JobOwner; + +/// The algorithm id a plugin asks for as `sha256` and gets back as this. +pub const ALGORITHM: &str = "sha256-tree-v1"; +/// Snapshots one plugin keeps; the oldest go first. +pub const MAX_SNAPSHOTS_PER_OWNER: usize = 8; +/// How long a snapshot is kept. +pub const SNAPSHOT_TTL: Duration = Duration::from_secs(60 * 60); +/// Entries a fingerprint covers when the request does not say, and the most it may be asked to. +pub const DEFAULT_ENTRIES: usize = 10_000; +pub const MAX_ENTRIES: usize = 50_000; +/// The most bytes one fingerprint reads before it stops and says it is incomplete. +pub const MAX_BYTES: u64 = 4 * 1024 * 1024 * 1024; +/// The longest one fingerprint runs. +pub const MAX_TIME: Duration = Duration::from_secs(10 * 60); +/// How long a request waits for its fingerprint before answering with the job. +pub const FAST_WAIT: Duration = Duration::from_secs(2); +/// Fingerprints one plugin may have running, and all plugins together: reading is disk work. +pub const RUNNING_PER_OWNER: usize = 1; +pub const RUNNING_TOTAL: usize = 2; + +/// The job code of a finished fingerprint; its message is the snapshot id. +pub const CODE_READY: &str = "fingerprint_ready"; + +/// One entry of a snapshot. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Record { + /// The entry's path below the place, `/`-separated; for a profile `d/` comes first. + pub label: String, + /// What to seal a handle from, for an entry that still exists. + pub approval_id: String, + pub path: Vec, + pub directory: bool, + pub size: u64, + /// The file's SHA-256; `None` for a directory or a file that could not be hashed. + pub digest: Option<[u8; 32]>, + /// Could not be read. + pub unreadable: bool, + /// Changed while it was read. + pub unstable: bool, +} + +/// A fingerprint of a place at a moment. +#[derive(Clone, Debug)] +pub struct Snapshot { + pub id: String, + /// The permission that inspecting the place needs; comparing needs it too. + pub permission: &'static str, + /// What was fingerprinted: the place and its selection. Two snapshots compare only if equal. + pub scope: String, + pub revision: u64, + pub entries: Vec, + pub complete: bool, + pub unstable: bool, + /// The tree digest; only for a complete snapshot. + pub digest: Option<[u8; 32]>, + /// Unix seconds when the observation began and ended. + pub started_at: i64, + pub finished_at: i64, +} + +/// The digest of the tree these entries make (see the module documentation). +pub fn tree_digest(entries: &[Record]) -> [u8; 32] { + let mut sorted: Vec<&Record> = entries.iter().collect(); + sorted.sort_by(|a, b| a.label.as_bytes().cmp(b.label.as_bytes())); + let mut hash = Sha256::new(); + hash.update(b"gamenode.location.tree.v1\0"); + for entry in sorted { + hash.update((entry.label.len() as u64).to_be_bytes()); + hash.update(entry.label.as_bytes()); + hash.update([u8::from(!entry.directory)]); + hash.update(entry.size.to_be_bytes()); + hash.update(entry.digest.unwrap_or([0; 32])); + } + hash.finalize().into() +} + +/// How two snapshots compare. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Verdict { + /// Both complete and identical. + Unchanged, + /// Both complete and different. + Changed, + /// One of them is incomplete or unstable: what differs is real, but nothing is certified. + Indeterminate, + /// They do not describe the same place, selection, algorithm or revision. + Incomparable, +} + +impl Verdict { + pub const fn as_str(self) -> &'static str { + match self { + Self::Unchanged => "unchanged", + Self::Changed => "changed", + Self::Indeterminate => "indeterminate", + Self::Incomparable => "incomparable", + } + } +} + +/// How an entry differs. Declared in the order two changes of one label are listed in: what went +/// away comes before what took its place. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Kind { + Removed, + Added, + Modified, +} + +impl Kind { + pub const fn as_str(self) -> &'static str { + match self { + Self::Added => "added", + Self::Removed => "removed", + Self::Modified => "modified", + } + } +} + +/// One entry that differs. +#[derive(Clone, Debug)] +pub struct Change { + pub label: String, + pub kind: Kind, + pub previous_size: u64, + pub current_size: u64, + /// The entry as it is now, when it still exists. + pub current: Option, +} + +pub struct Comparison { + pub status: Verdict, + /// Sorted by label. + pub changes: Vec, +} + +/// Compares `before` with `after`. A file that became a directory (or the reverse) is a removal +/// plus an addition; a file is modified when its content digest or size differs, and an entry +/// that could not be read in either snapshot is never reported as unchanged. +pub fn compare(before: &Snapshot, after: &Snapshot) -> Comparison { + if before.scope != after.scope || before.revision != after.revision { + return Comparison { + status: Verdict::Incomparable, + changes: Vec::new(), + }; + } + let old: HashMap<&str, &Record> = before + .entries + .iter() + .map(|r| (r.label.as_str(), r)) + .collect(); + let new: HashMap<&str, &Record> = after + .entries + .iter() + .map(|r| (r.label.as_str(), r)) + .collect(); + let mut changes = Vec::new(); + for (label, record) in &new { + match old.get(label) { + None => changes.push(Change { + label: (*label).to_owned(), + kind: Kind::Added, + previous_size: 0, + current_size: record.size, + current: Some((*record).clone()), + }), + Some(previous) if previous.directory != record.directory => { + changes.push(Change { + label: (*label).to_owned(), + kind: Kind::Removed, + previous_size: previous.size, + current_size: 0, + current: None, + }); + changes.push(Change { + label: (*label).to_owned(), + kind: Kind::Added, + previous_size: 0, + current_size: record.size, + current: Some((*record).clone()), + }); + } + Some(previous) => { + let same = !record.directory + && previous.size == record.size + && previous.digest.is_some() + && previous.digest == record.digest + && !previous.unreadable + && !record.unreadable; + // An entry that could not be read in either snapshot is not known to have changed. + if !record.directory && !same && !previous.unreadable && !record.unreadable { + changes.push(Change { + label: (*label).to_owned(), + kind: Kind::Modified, + previous_size: previous.size, + current_size: record.size, + current: Some((*record).clone()), + }); + } + } + } + } + for (label, record) in &old { + if !new.contains_key(label) { + changes.push(Change { + label: (*label).to_owned(), + kind: Kind::Removed, + previous_size: record.size, + current_size: 0, + current: None, + }); + } + } + changes.sort_by(|a, b| { + a.label + .as_bytes() + .cmp(b.label.as_bytes()) + .then((a.kind as u8).cmp(&(b.kind as u8))) + }); + let status = if !before.complete || !after.complete || before.unstable || after.unstable { + Verdict::Indeterminate + } else if changes.is_empty() && before.digest == after.digest { + Verdict::Unchanged + } else { + Verdict::Changed + }; + Comparison { status, changes } +} + +type Clock = Arc Instant + Send + Sync>; + +struct Stored { + owner: JobOwner, + snapshot: Arc, + at: Instant, +} + +/// The snapshots the host holds and the fingerprints it is running. +pub struct Snapshots { + stored: Mutex>, + running: Mutex>, + clock: Clock, + #[cfg(test)] + hook: Mutex>, + #[cfg(test)] + fast_wait: Mutex>, +} + +/// Called after each file is hashed, so a test can change it as a concurrent writer would. +pub type Hook = Arc; + +impl Default for Snapshots { + fn default() -> Self { + Self { + stored: Mutex::default(), + running: Mutex::default(), + clock: Arc::new(Instant::now), + #[cfg(test)] + hook: Mutex::default(), + #[cfg(test)] + fast_wait: Mutex::default(), + } + } +} + +/// Releases a running-fingerprint slot when dropped. +pub struct Running { + snapshots: Arc, + owner: JobOwner, +} + +impl Drop for Running { + fn drop(&mut self) { + let mut running = self + .snapshots + .running + .lock() + .unwrap_or_else(|p| p.into_inner()); + if let Some(count) = running.get_mut(&self.owner) { + *count -= 1; + if *count == 0 { + running.remove(&self.owner); + } + } + } +} + +impl Snapshots { + #[cfg(test)] + pub(crate) fn with_clock( + mut self, + clock: impl Fn() -> Instant + Send + Sync + 'static, + ) -> Self { + self.clock = Arc::new(clock); + self + } + + /// Makes the next fingerprints call `hook` after hashing each file. + #[cfg(test)] + pub(crate) fn set_hook(&self, hook: impl Fn(&[String]) + Send + Sync + 'static) { + *self.hook.lock().unwrap_or_else(|p| p.into_inner()) = Some(Arc::new(hook)); + } + + /// How long a request waits for its fingerprint before answering with the job. + pub fn fast_wait(&self) -> Duration { + #[cfg(test)] + if let Some(wait) = *self.fast_wait.lock().unwrap_or_else(|p| p.into_inner()) { + return wait; + } + FAST_WAIT + } + + /// Shortens the wait of the next requests, for tests of the job path. + #[cfg(test)] + pub(crate) fn set_fast_wait(&self, wait: Duration) { + *self.fast_wait.lock().unwrap_or_else(|p| p.into_inner()) = Some(wait); + } + + /// The test hook, or nothing outside tests. + pub fn after_hash(&self) -> Option { + #[cfg(test)] + { + self.hook.lock().unwrap_or_else(|p| p.into_inner()).clone() + } + #[cfg(not(test))] + { + None + } + } + + /// Claims the right to run a fingerprint, or refuses when this plugin already has one running + /// or the host as a whole has [`RUNNING_TOTAL`]. + pub fn begin(self: &Arc, owner: &JobOwner) -> Result { + let mut running = self.running.lock().unwrap_or_else(|p| p.into_inner()); + if running.get(owner).copied().unwrap_or(0) >= RUNNING_PER_OWNER { + return Err(Status::resource_exhausted( + "a fingerprint of this plugin is already running; wait for it or cancel it", + )); + } + if running.values().sum::() >= RUNNING_TOTAL { + return Err(Status::resource_exhausted( + "the host is fingerprinting as much as it allows; try again later", + )); + } + *running.entry(owner.clone()).or_default() += 1; + Ok(Running { + snapshots: Arc::clone(self), + owner: owner.clone(), + }) + } + + /// Keeps `snapshot` for `owner`, dropping what expired and the owner's oldest beyond the cap. + pub fn keep(&self, owner: &JobOwner, snapshot: Snapshot) -> Arc { + let now = (self.clock)(); + let snapshot = Arc::new(snapshot); + let mut stored = self.stored.lock().unwrap_or_else(|p| p.into_inner()); + stored.retain(|_, kept| now.duration_since(kept.at) < SNAPSHOT_TTL); + let own: Vec<_> = stored + .iter() + .filter(|(_, kept)| kept.owner == *owner) + .map(|(id, kept)| (kept.at, id.clone())) + .collect(); + if own.len() >= MAX_SNAPSHOTS_PER_OWNER { + let mut own = own; + own.sort(); + for (_, id) in &own[..own.len() + 1 - MAX_SNAPSHOTS_PER_OWNER] { + stored.remove(id); + } + } + stored.insert( + snapshot.id.clone(), + Stored { + owner: owner.clone(), + snapshot: snapshot.clone(), + at: now, + }, + ); + snapshot + } + + /// The owner's snapshot `id`; another owner's, an unknown one and an expired one are the same. + pub fn get(&self, owner: &JobOwner, id: &str) -> Option> { + let now = (self.clock)(); + let mut stored = self.stored.lock().unwrap_or_else(|p| p.into_inner()); + stored.retain(|_, kept| now.duration_since(kept.at) < SNAPSHOT_TTL); + stored + .get(id) + .filter(|kept| kept.owner == *owner) + .map(|kept| kept.snapshot.clone()) + } +} + +/// A new snapshot id. +pub fn new_snapshot_id() -> Result { + let mut bytes = [0_u8; 16]; + getrandom::fill(&mut bytes).map_err(|_| Status::internal("no source of randomness"))?; + Ok(format!( + "snap-{}", + bytes.iter().map(|b| format!("{b:02x}")).collect::() + )) +} + +#[cfg(test)] +mod tests; diff --git a/crates/app/src/plugin_host/fingerprints/tests.rs b/crates/app/src/plugin_host/fingerprints/tests.rs new file mode 100644 index 000000000..8a4a5c965 --- /dev/null +++ b/crates/app/src/plugin_host/fingerprints/tests.rs @@ -0,0 +1,297 @@ +//! The tree digest, the comparison and the snapshot store (task 13.4), without a plugin session. +//! The service is tested over the real socket in `resources/tests/fingerprints.rs`. + +use std::sync::Mutex as StdMutex; + +use super::*; + +fn digest(byte: u8) -> Option<[u8; 32]> { + Some([byte; 32]) +} + +fn file(label: &str, size: u64, byte: u8) -> Record { + Record { + label: label.into(), + approval_id: "a".into(), + path: label.split('/').map(str::to_owned).collect(), + directory: false, + size, + digest: digest(byte), + unreadable: false, + unstable: false, + } +} + +fn folder(label: &str) -> Record { + Record { + directory: true, + size: 0, + digest: None, + ..file(label, 0, 0) + } +} + +fn snapshot(id: &str, entries: Vec) -> Snapshot { + let complete = entries.iter().all(|e| !e.unreadable && !e.unstable); + Snapshot { + id: id.into(), + permission: "game.saves.inspect", + scope: "place".into(), + revision: 0, + digest: complete.then(|| tree_digest(&entries)), + entries, + complete, + unstable: false, + started_at: 1, + finished_at: 2, + } +} + +#[test] +fn the_tree_digest_follows_names_types_sizes_and_contents_and_not_the_order_given() { + let base = vec![file("a.sav", 3, 1), folder("saves"), file("saves/s1", 5, 2)]; + let reordered = vec![file("saves/s1", 5, 2), file("a.sav", 3, 1), folder("saves")]; + assert_eq!(tree_digest(&base), tree_digest(&reordered)); + + let differs = |entries: Vec| tree_digest(&entries) != tree_digest(&base); + // A byte of content, a size, a name, a case, a type, an empty folder: each changes it. + assert!(differs(vec![ + file("a.sav", 3, 9), + folder("saves"), + file("saves/s1", 5, 2) + ])); + assert!(differs(vec![ + file("a.sav", 4, 1), + folder("saves"), + file("saves/s1", 5, 2) + ])); + assert!(differs(vec![ + file("b.sav", 3, 1), + folder("saves"), + file("saves/s1", 5, 2) + ])); + assert!(differs(vec![ + file("A.sav", 3, 1), + folder("saves"), + file("saves/s1", 5, 2) + ])); + assert!(differs(vec![ + folder("a.sav"), + folder("saves"), + file("saves/s1", 5, 2) + ])); + let mut with_empty = base.clone(); + with_empty.push(folder("empty")); + assert!(differs(with_empty)); + // The lengths keep names from running together: "ab"+"c" is not "a"+"bc". + assert_ne!( + tree_digest(&[file("ab", 1, 1), file("c", 1, 1)]), + tree_digest(&[file("a", 1, 1), file("bc", 1, 1)]) + ); +} + +#[test] +fn the_tree_digest_has_a_fixed_known_value() { + // A change to the encoding must be a new algorithm id, so the value is pinned. + let entries = vec![file("a.sav", 3, 1)]; + let mut hash = Sha256::new(); + hash.update(b"gamenode.location.tree.v1\0"); + hash.update(5_u64.to_be_bytes()); + hash.update(b"a.sav"); + hash.update([1_u8]); + hash.update(3_u64.to_be_bytes()); + hash.update([1_u8; 32]); + assert_eq!(tree_digest(&entries), <[u8; 32]>::from(hash.finalize())); + assert_eq!(ALGORITHM, "sha256-tree-v1"); +} + +#[test] +fn identical_complete_snapshots_are_unchanged() { + let entries = vec![file("a", 1, 1), folder("d")]; + let result = compare(&snapshot("s1", entries.clone()), &snapshot("s2", entries)); + assert_eq!( + (result.status, result.changes.len()), + (Verdict::Unchanged, 0) + ); +} + +#[test] +fn a_change_of_bytes_with_the_same_size_is_a_modification() { + let before = snapshot("s1", vec![file("a", 4, 1)]); + let after = snapshot("s2", vec![file("a", 4, 2)]); + let result = compare(&before, &after); + assert_eq!(result.status, Verdict::Changed); + assert_eq!(result.changes.len(), 1); + assert_eq!( + ( + result.changes[0].kind, + result.changes[0].previous_size, + result.changes[0].current_size + ), + (Kind::Modified, 4, 4) + ); +} + +#[test] +fn additions_deletions_and_empty_folders_are_found_and_a_rename_is_a_removal_plus_an_addition() { + let before = snapshot( + "s1", + vec![ + file("keep", 1, 1), + file("gone", 2, 2), + file("old-name", 3, 3), + folder("empty-old"), + ], + ); + let after = snapshot( + "s2", + vec![ + file("keep", 1, 1), + file("new-name", 3, 3), + file("fresh", 9, 9), + folder("empty-new"), + ], + ); + let result = compare(&before, &after); + assert_eq!(result.status, Verdict::Changed); + let seen: Vec<_> = result + .changes + .iter() + .map(|c| (c.label.as_str(), c.kind)) + .collect(); + assert_eq!( + seen, + [ + ("empty-new", Kind::Added), + ("empty-old", Kind::Removed), + ("fresh", Kind::Added), + ("gone", Kind::Removed), + ("new-name", Kind::Added), + ("old-name", Kind::Removed), + ] + ); + // An added entry carries where it is now; a removed one does not. + assert!(result.changes[0].current.is_some() && result.changes[1].current.is_none()); +} + +#[test] +fn a_file_that_became_a_folder_is_a_removal_plus_an_addition() { + let result = compare( + &snapshot("s1", vec![file("x", 4, 1)]), + &snapshot("s2", vec![folder("x")]), + ); + let kinds: Vec<_> = result.changes.iter().map(|c| c.kind).collect(); + assert_eq!(kinds, [Kind::Removed, Kind::Added]); + assert_eq!(result.status, Verdict::Changed); +} + +#[test] +fn an_incomplete_or_unstable_snapshot_never_gives_unchanged() { + let entries = vec![file("a", 1, 1)]; + let complete = snapshot("s1", entries.clone()); + + let mut unreadable = entries.clone(); + unreadable[0].unreadable = true; + unreadable[0].digest = None; + let partial = snapshot("s2", unreadable); + assert!(!partial.complete && partial.digest.is_none()); + // Identical on every readable entry, and still not certified; the unreadable one is not + // reported as modified either. + let result = compare(&complete, &partial); + assert_eq!( + (result.status, result.changes.len()), + (Verdict::Indeterminate, 0) + ); + assert_eq!(compare(&partial, &complete).status, Verdict::Indeterminate); + + let mut cut = snapshot("s3", entries.clone()); + cut.complete = false; + assert_eq!(compare(&complete, &cut).status, Verdict::Indeterminate); + let mut unstable = snapshot("s4", entries); + unstable.unstable = true; + assert_eq!(compare(&unstable, &complete).status, Verdict::Indeterminate); + // A real difference is still reported, with the verdict held back. + let other = snapshot("s5", vec![file("a", 1, 7)]); + let mut incomplete_other = other.clone(); + incomplete_other.complete = false; + let result = compare(&complete, &incomplete_other); + assert_eq!( + (result.status, result.changes.len()), + (Verdict::Indeterminate, 1) + ); +} + +#[test] +fn snapshots_of_another_place_selection_or_revision_are_incomparable() { + let a = snapshot("s1", vec![file("a", 1, 1)]); + let mut other_scope = snapshot("s2", vec![file("a", 1, 1)]); + other_scope.scope = "another place".into(); + let mut other_revision = snapshot("s3", vec![file("a", 1, 1)]); + other_revision.revision = 4; + for other in [&other_scope, &other_revision] { + let result = compare(&a, other); + assert_eq!( + (result.status, result.changes.len()), + (Verdict::Incomparable, 0) + ); + } +} + +fn owner(key: u8) -> JobOwner { + JobOwner::for_tests(key, 1) +} + +#[test] +fn snapshots_belong_to_their_owner_expire_and_are_bounded() { + let now = Arc::new(StdMutex::new(Instant::now())); + let store = Snapshots::default().with_clock({ + let now = now.clone(); + move || *now.lock().unwrap() + }); + let kept = store.keep(&owner(1), snapshot("snap-mine", vec![])); + assert_eq!(kept.id, "snap-mine"); + assert!(store.get(&owner(1), "snap-mine").is_some()); + // Another owner, and an unknown id, are the same nothing. + assert!(store.get(&owner(2), "snap-mine").is_none()); + assert!(store.get(&owner(1), "snap-none").is_none()); + + // The oldest goes when the owner has too many. + for n in 0..MAX_SNAPSHOTS_PER_OWNER { + *now.lock().unwrap() += Duration::from_secs(1); + store.keep(&owner(1), snapshot(&format!("snap-{n}"), vec![])); + } + assert!(store.get(&owner(1), "snap-mine").is_none()); + assert!(store.get(&owner(1), "snap-0").is_some()); + + // And an hour later nothing is left. + *now.lock().unwrap() += SNAPSHOT_TTL; + assert!(store.get(&owner(1), "snap-0").is_none()); +} + +#[test] +fn only_so_many_fingerprints_run_at_once() { + let store = Arc::new(Snapshots::default()); + let first = store.begin(&owner(1)).unwrap(); + // The same plugin may not run a second one. + assert_eq!( + store.begin(&owner(1)).err().unwrap().code(), + tonic::Code::ResourceExhausted + ); + let second = store.begin(&owner(2)).unwrap(); + // The host as a whole is limited too. + assert_eq!( + store.begin(&owner(3)).err().unwrap().code(), + tonic::Code::ResourceExhausted + ); + drop(first); + let third = store.begin(&owner(3)).unwrap(); + drop((second, third)); + assert!(store.begin(&owner(1)).is_ok()); +} + +#[test] +fn snapshot_ids_are_host_made_and_never_repeat() { + let first = new_snapshot_id().unwrap(); + assert!(first.starts_with("snap-") && first.len() == 37); + assert_ne!(first, new_snapshot_id().unwrap()); +} diff --git a/crates/app/src/plugin_host/grants.rs b/crates/app/src/plugin_host/grants.rs new file mode 100644 index 000000000..e32c86400 --- /dev/null +++ b/crates/app/src/plugin_host/grants.rs @@ -0,0 +1,1477 @@ +//! Persistent third-party permission grants and domain-resource authorization. +//! +//! This module models consent separately from a live RPC session. A session receives only the +//! current effective grant revision; a grant update is persisted before it can become effective. + +use super::package::Manifest; +use serde::{Deserialize, Serialize}; +use std::{ + collections::{BTreeMap, BTreeSet}, + fs::{self, File, OpenOptions}, + io::{self, Read, Write}, + path::{Path, PathBuf}, + sync::atomic::{AtomicU64, Ordering}, +}; +use thiserror::Error; + +const STORE_FILE: &str = "plugin-permissions.json"; +const MAX_STORE_BYTES: u64 = 8 * 1024 * 1024; +const MAX_AUDIT_EVENTS: usize = 20_000; +static NEXT_TEMP: AtomicU64 = AtomicU64::new(1); + +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum DomainCategory { + Runtime, + LibraryRoot, + SaveProfile, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum Operation { + Read, + Create, + Update, + Delete, +} + +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(tag = "scope", rename_all = "kebab-case", deny_unknown_fields)] +pub enum GrantScope { + /// The caller may act on records whose immutable creator is the caller. + OwnCreator { category: DomainCategory }, + /// The caller may act on published records in this category. + PublicCategory { category: DomainCategory }, + /// The caller may act only on the listed published record ids. + SelectedRecords { + category: DomainCategory, + record_ids: BTreeSet, + }, + /// Exact host-approved scope for non-domain permissions, such as a game handle or origin. + Declared { value: String }, + /// Reserved for a caller's own private durable namespace. + OwnPrivateNamespace, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct PluginIdentity { + pub plugin_id: String, + pub publisher_fingerprint: String, + pub profile_id: String, +} + +impl PluginIdentity { + pub(crate) fn validate(&self) -> Result<(), GrantError> { + if !valid_identity_part(&self.plugin_id, 256) + || !valid_identity_part(&self.profile_id, 256) + || self.publisher_fingerprint.len() > 128 + || self.publisher_fingerprint.trim().is_empty() + || self.publisher_fingerprint.chars().any(char::is_control) + { + return Err(GrantError::InvalidIdentity); + } + Ok(()) + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct PermissionRequest { + pub permission_id: String, + pub required: bool, + pub allowed_scopes: BTreeSet, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct PermissionDecision { + pub permission_id: String, + pub scope: GrantScope, + pub granted: bool, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum PermissionState { + Granted, + Denied, + Unsupported, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct EffectiveGrant { + pub permission_id: String, + pub required: bool, + pub scope: GrantScope, + pub state: PermissionState, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct PluginGrantRecord { + identity: PluginIdentity, + revision: u64, + grants: Vec, +} + +#[derive(Clone, Debug, Default, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct StoreFile { + schema: u32, + plugins: BTreeMap, + audit: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum AuditOperation { + Create, + Update, + Delete, + PrivateCleanup, +} + +/// An audit event is produced from the authenticated caller identity, never request provenance. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct AuditEvent { + pub actor_plugin_id: String, + pub target_record_id: String, + pub operation: AuditOperation, + pub previous_revision: Option, + pub resulting_revision: Option, + pub grant_revision: u64, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct DomainRecord { + pub id: String, + pub category: DomainCategory, + /// Immutable host-owned creator attribution. + creator_plugin_id: String, + /// Whether the producer requested publication and the user authorized it. + pub published: bool, + pub revision: u64, +} + +#[derive(Debug, Error)] +pub enum GrantError { + #[error("plugin identity is invalid")] + InvalidIdentity, + #[error("permission request is malformed")] + InvalidRequest, + #[error("required permission is not supported by this host")] + RequiredPermissionUnsupported, + #[error("permission decision is outside the manifest request")] + DecisionNotRequested, + #[error("permission scope is not valid for this operation")] + InvalidScope, + #[error("permission is not granted for this operation and resource")] + Denied, + #[error("resource revision is stale")] + StaleRevision, + #[error("the requested namespace is not owned by the authenticated plugin")] + ForeignPrivateNamespace, + #[error("grant store is invalid: {0}")] + InvalidStore(String), + #[error(transparent)] + Io(#[from] io::Error), +} + +impl PartialEq for GrantError { + fn eq(&self, other: &Self) -> bool { + use GrantError::*; + match (self, other) { + (InvalidIdentity, InvalidIdentity) + | (InvalidRequest, InvalidRequest) + | (RequiredPermissionUnsupported, RequiredPermissionUnsupported) + | (DecisionNotRequested, DecisionNotRequested) + | (InvalidScope, InvalidScope) + | (Denied, Denied) + | (StaleRevision, StaleRevision) + | (ForeignPrivateNamespace, ForeignPrivateNamespace) => true, + (InvalidStore(a), InvalidStore(b)) => a == b, + _ => false, + } + } +} + +impl Eq for GrantError {} + +impl DomainRecord { + /// Host code assigns creator attribution from authenticated publisher identity. + pub fn new( + id: String, + category: DomainCategory, + creator: &PluginIdentity, + published: bool, + revision: u64, + ) -> Result { + creator.validate()?; + Ok(Self { + id, + category, + creator_plugin_id: creator.plugin_id.clone(), + published, + revision, + }) + } + + pub fn creator_plugin_id(&self) -> &str { + &self.creator_plugin_id + } +} + +pub struct PermissionGrantStore { + path: PathBuf, + state: StoreFile, +} + +impl PermissionGrantStore { + /// Opens `/plugin-permissions.json`; absent grants are default-deny. + pub fn open(private_dir: impl AsRef) -> Result { + let directory = private_dir.as_ref(); + ensure_private_dir(directory)?; + let path = directory.join(STORE_FILE); + let state = match fs::symlink_metadata(&path) { + Ok(meta) if meta.file_type().is_file() && !meta.file_type().is_symlink() => { + if meta.len() > MAX_STORE_BYTES { + return Err(GrantError::InvalidStore("file exceeds size limit".into())); + } + ensure_private_file(&path)?; + let mut bytes = Vec::with_capacity(meta.len() as usize); + File::open(&path)? + .take(MAX_STORE_BYTES + 1) + .read_to_end(&mut bytes)?; + if bytes.len() as u64 > MAX_STORE_BYTES { + return Err(GrantError::InvalidStore("file exceeds size limit".into())); + } + let state: StoreFile = serde_json::from_slice(&bytes) + .map_err(|error| GrantError::InvalidStore(error.to_string()))?; + if state.schema != 1 { + return Err(GrantError::InvalidStore("unsupported schema".into())); + } + for record in state.plugins.values() { + record.identity.validate()?; + } + state + } + Ok(_) => return Err(GrantError::InvalidStore("unsafe grant file".into())), + Err(error) if error.kind() == io::ErrorKind::NotFound => StoreFile { + schema: 1, + ..StoreFile::default() + }, + Err(error) => return Err(error.into()), + }; + Ok(Self { path, state }) + } + + pub fn revision(&self, identity: &PluginIdentity) -> u64 { + self.state + .plugins + .get(&identity_key(identity)) + .filter(|entry| entry.identity == *identity) + .map_or(0, |entry| entry.revision) + } + + /// Plugin identities with persisted grant records in this account profile. + pub fn identities(&self) -> Vec { + self.state + .plugins + .values() + .map(|record| record.identity.clone()) + .collect() + } + + pub fn effective_grants(&self, identity: &PluginIdentity) -> Vec { + self.state + .plugins + .get(&identity_key(identity)) + .filter(|entry| entry.identity == *identity) + .map(|entry| entry.grants.clone()) + .unwrap_or_default() + } + + /// Permanently denies every saved scope for the selected permissions. Used when an approved + /// package update changes the declaration behind an existing permission id; a failed package + /// activation must never restore the old authorization. + pub fn revoke_permissions( + &mut self, + identity: &PluginIdentity, + permission_ids: &BTreeSet, + ) -> Result { + identity.validate()?; + if permission_ids.is_empty() { + return Ok(self.revision(identity)); + } + let key = identity_key(identity); + let Some(previous) = self.state.plugins.get(&key) else { + return Ok(0); + }; + if previous.identity != *identity { + return Err(GrantError::InvalidIdentity); + } + let mut next = self.state.clone(); + let record = next.plugins.get_mut(&key).expect("record was just checked"); + let mut changed = false; + for grant in &mut record.grants { + if permission_ids.contains(&grant.permission_id) + && grant.state == PermissionState::Granted + { + grant.state = PermissionState::Denied; + changed = true; + } + } + if changed { + record.revision = record.revision.saturating_add(1); + let revision = record.revision; + self.persist(&next)?; + self.state = next; + Ok(revision) + } else { + Ok(record.revision) + } + } + + /// Removes all saved grant records for a plugin in this account profile. Audit history is + /// retained and private plugin data lives in a separate store. + pub fn remove_plugin(&mut self, plugin_id: &str) -> Result<(), GrantError> { + if !valid_identity_part(plugin_id, 256) { + return Err(GrantError::InvalidIdentity); + } + let mut next = self.state.clone(); + next.plugins + .retain(|_, record| record.identity.plugin_id != plugin_id); + if next.plugins.len() != self.state.plugins.len() { + self.persist(&next)?; + self.state = next; + } + Ok(()) + } + + /// Restricts a persisted grant set to permissions whose identifier and declared scope are + /// unchanged in the selected package. New or widened requests remain default-deny; changing + /// a required bit updates disclosure metadata but does not create a grant. + pub fn intersect_with_selected_manifest( + &mut self, + identity: &PluginIdentity, + previous: &Manifest, + selected: &Manifest, + ) -> Result { + identity.validate()?; + let key = identity_key(identity); + let Some(existing) = self.state.plugins.get(&key) else { + return Ok(0); + }; + if existing.identity != *identity { + return Err(GrantError::InvalidIdentity); + } + let old_scopes: BTreeMap<_, _> = previous + .permissions + .iter() + .map(|permission| (permission.id.as_str(), permission.scope.as_str())) + .collect(); + let selected_permissions: BTreeMap<_, _> = selected + .permissions + .iter() + .map(|permission| { + ( + permission.id.as_str(), + (permission.scope.as_str(), permission.required), + ) + }) + .collect(); + let record = self + .state + .plugins + .get(&key) + .expect("record was checked above"); + let mut narrowed = record.clone(); + narrowed.grants.retain_mut(|grant| { + let Some((scope, required)) = selected_permissions.get(grant.permission_id.as_str()) + else { + return false; + }; + if old_scopes.get(grant.permission_id.as_str()) != Some(scope) { + return false; + } + grant.required = *required; + true + }); + if narrowed.grants == record.grants { + return Ok(record.revision); + } + narrowed.revision = record.revision.saturating_add(1); + let revision = narrowed.revision; + let mut next = self.state.clone(); + next.plugins.insert(key, narrowed); + self.persist(&next)?; + self.state = next; + Ok(revision) + } + + /// Required requests gate activation when denied or unsupported. + pub fn required_permissions_granted(&self, identity: &PluginIdentity) -> bool { + let grants = self.effective_grants(identity); + let required: BTreeSet<_> = grants + .iter() + .filter(|grant| grant.required) + .map(|grant| grant.permission_id.as_str()) + .collect(); + required.into_iter().all(|permission_id| { + grants.iter().any(|grant| { + grant.permission_id == permission_id && grant.state == PermissionState::Granted + }) + }) + } + + /// Replaces a plugin's grant set atomically. Request limits come from its validated manifest; + /// decisions are host/UI inputs. Unknown optional permissions are retained as unsupported, + /// never granted. The old in-memory state survives any persistence failure. + pub fn replace_grants( + &mut self, + identity: PluginIdentity, + requests: &[PermissionRequest], + decisions: &[PermissionDecision], + ) -> Result { + identity.validate()?; + let mut request_map = BTreeMap::new(); + for request in requests { + validate_permission_request(request)?; + if request_map + .insert(request.permission_id.clone(), request) + .is_some() + { + return Err(GrantError::InvalidRequest); + } + if request.required && !is_known_permission(&request.permission_id) { + return Err(GrantError::RequiredPermissionUnsupported); + } + } + let mut decisions_by_permission: BTreeMap<&str, Vec<&PermissionDecision>> = BTreeMap::new(); + let mut seen_decisions = BTreeSet::new(); + for decision in decisions { + let request = request_map + .get(&decision.permission_id) + .ok_or(GrantError::DecisionNotRequested)?; + if !request.allowed_scopes.contains(&decision.scope) { + return Err(GrantError::DecisionNotRequested); + } + if !seen_decisions.insert((decision.permission_id.as_str(), &decision.scope)) { + return Err(GrantError::InvalidRequest); + } + if !is_known_permission(&decision.permission_id) { + return Err(GrantError::DecisionNotRequested); + } + validate_scope_for_permission(&decision.permission_id, &decision.scope)?; + decisions_by_permission + .entry(&decision.permission_id) + .or_default() + .push(decision); + } + + let mut grants = Vec::new(); + for request in requests { + let supported = is_known_permission(&request.permission_id); + if !supported { + if request.allowed_scopes.is_empty() { + grants.push(EffectiveGrant { + permission_id: request.permission_id.clone(), + required: request.required, + scope: GrantScope::Declared { + value: "unsupported".into(), + }, + state: PermissionState::Unsupported, + }); + } else { + grants.extend(request.allowed_scopes.iter().cloned().map(|scope| { + EffectiveGrant { + permission_id: request.permission_id.clone(), + required: request.required, + scope, + state: PermissionState::Unsupported, + } + })); + } + continue; + } + let scopes = decisions_by_permission + .get(request.permission_id.as_str()) + .into_iter() + .flatten(); + let any_granted = scopes.clone().any(|decision| decision.granted); + if request.permission_id == gamenode_plugin_protocol::capability::STORAGE_PERSIST { + grants.push(EffectiveGrant { + permission_id: request.permission_id.clone(), + required: request.required, + scope: GrantScope::OwnPrivateNamespace, + state: if any_granted { + PermissionState::Granted + } else { + PermissionState::Denied + }, + }); + } else { + for scope in &request.allowed_scopes { + let granted = scopes + .clone() + .any(|decision| decision.scope == *scope && decision.granted); + grants.push(EffectiveGrant { + permission_id: request.permission_id.clone(), + required: request.required, + scope: scope.clone(), + state: if granted { + PermissionState::Granted + } else { + PermissionState::Denied + }, + }); + } + } + } + grants.sort_by(|a, b| (&a.permission_id, &a.scope).cmp(&(&b.permission_id, &b.scope))); + let key = identity_key(&identity); + let previous = self.state.plugins.get(&key); + if previous.is_some_and(|entry| entry.identity != identity) { + return Err(GrantError::InvalidIdentity); + } + let revision = previous.map_or(1, |entry| entry.revision.saturating_add(1)); + let mut next = self.state.clone(); + next.schema = 1; + next.plugins.insert( + key, + PluginGrantRecord { + identity, + revision, + grants, + }, + ); + self.persist(&next)?; + self.state = next; + Ok(revision) + } + + pub fn authorize_domain( + &self, + identity: &PluginIdentity, + record: &DomainRecord, + operation: Operation, + ) -> Result { + identity.validate()?; + if !valid_identity_part(&record.id, 256) + || !valid_identity_part(&record.creator_plugin_id, 256) + { + return Err(GrantError::InvalidRequest); + } + let permission_id = permission_id(&record.category, operation); + let grants = self.effective_grants(identity); + let allowed = grants.iter().any(|grant| { + if grant.permission_id != permission_id || grant.state != PermissionState::Granted { + return false; + } + match &grant.scope { + GrantScope::OwnCreator { category } => { + category == &record.category && record.creator_plugin_id == identity.plugin_id + } + GrantScope::PublicCategory { category } => { + category == &record.category + && if operation == Operation::Create { + record.creator_plugin_id == identity.plugin_id && record.published + } else { + record.creator_plugin_id != identity.plugin_id && record.published + } + } + GrantScope::SelectedRecords { + category, + record_ids, + } => { + category == &record.category + && record.creator_plugin_id != identity.plugin_id + && record.published + && record_ids.contains(&record.id) + } + GrantScope::Declared { .. } => false, + GrantScope::OwnPrivateNamespace => false, + } + }); + if allowed { + Ok(self.revision(identity)) + } else { + Err(GrantError::Denied) + } + } + + /// Rechecks the grant revision and expected record revision at commit, then records the + /// authenticated actor. Callers must persist the record effect transactionally with this audit. + pub fn audit_domain_commit( + &mut self, + identity: &PluginIdentity, + record: &DomainRecord, + operation: Operation, + expected_record_revision: Option, + expected_grant_revision: u64, + ) -> Result { + let current_grant_revision = self.authorize_domain(identity, record, operation)?; + if current_grant_revision != expected_grant_revision { + return Err(GrantError::Denied); + } + if operation != Operation::Create && expected_record_revision != Some(record.revision) { + return Err(GrantError::StaleRevision); + } + if operation == Operation::Create && expected_record_revision.is_some() { + return Err(GrantError::InvalidRequest); + } + let event = AuditEvent { + actor_plugin_id: identity.plugin_id.clone(), + target_record_id: record.id.clone(), + operation: match operation { + Operation::Create => AuditOperation::Create, + Operation::Update => AuditOperation::Update, + Operation::Delete => AuditOperation::Delete, + Operation::Read => return Err(GrantError::InvalidRequest), + }, + previous_revision: (operation != Operation::Create).then_some(record.revision), + resulting_revision: (operation != Operation::Delete) + .then_some(record.revision.saturating_add(1)), + grant_revision: current_grant_revision, + }; + let mut next = self.state.clone(); + next.audit.push(event.clone()); + if next.audit.len() > MAX_AUDIT_EVENTS { + next.audit.drain(..next.audit.len() - MAX_AUDIT_EVENTS); + } + self.persist(&next)?; + self.state = next; + Ok(event) + } + + pub fn audit_events(&self) -> &[AuditEvent] { + &self.state.audit + } + + /// storage.persist grants cleanup only for the authenticated caller's private namespace; + /// it does not grant Storage.Delete or any foreign namespace selection. + pub fn authorize_private_cleanup( + &self, + identity: &PluginIdentity, + requested_owner_plugin_id: &str, + ) -> Result { + if requested_owner_plugin_id != identity.plugin_id { + return Err(GrantError::ForeignPrivateNamespace); + } + let permitted = self.effective_grants(identity).iter().any(|grant| { + grant.permission_id == gamenode_plugin_protocol::capability::STORAGE_PERSIST + && grant.scope == GrantScope::OwnPrivateNamespace + && grant.state == PermissionState::Granted + }); + if permitted { + Ok(self.revision(identity)) + } else { + Err(GrantError::Denied) + } + } + + fn persist(&self, state: &StoreFile) -> Result<(), GrantError> { + let parent = self + .path + .parent() + .ok_or_else(|| GrantError::InvalidStore("store has no parent".into()))?; + ensure_private_dir(parent)?; + let bytes = serde_json::to_vec(state) + .map_err(|error| GrantError::InvalidStore(error.to_string()))?; + if bytes.len() as u64 > MAX_STORE_BYTES { + return Err(GrantError::InvalidStore( + "serialized file exceeds size limit".into(), + )); + } + let temp = parent.join(format!( + ".plugin-permissions-{}-{}", + std::process::id(), + NEXT_TEMP.fetch_add(1, Ordering::Relaxed) + )); + let mut options = OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600); + } + let mut file = options.open(&temp)?; + let result = (|| -> io::Result<()> { + file.write_all(&bytes)?; + file.sync_all()?; + atomic_replace(&temp, &self.path)?; + sync_dir(parent) + })(); + if result.is_err() { + let _ = fs::remove_file(&temp); + } + result?; + ensure_private_file(&self.path)?; + Ok(()) + } +} + +pub fn permission_id(category: &DomainCategory, operation: Operation) -> String { + let stem = match category { + DomainCategory::Runtime => "game.runtime", + DomainCategory::LibraryRoot => "library.roots", + DomainCategory::SaveProfile => "game.saves", + }; + format!( + "{stem}.{}", + match operation { + Operation::Read => "read", + Operation::Create => "create", + Operation::Update => "update", + Operation::Delete => "delete", + } + ) +} + +pub(crate) fn permission_category(permission: &str) -> Option<(DomainCategory, Operation)> { + [ + DomainCategory::Runtime, + DomainCategory::LibraryRoot, + DomainCategory::SaveProfile, + ] + .into_iter() + .flat_map(|category| { + [ + Operation::Read, + Operation::Create, + Operation::Update, + Operation::Delete, + ] + .into_iter() + .map(move |operation| (category.clone(), operation)) + }) + .find(|(category, operation)| self::permission_id(category, *operation) == permission) +} + +/// Convert the permission declaration in the verified package manifest to the exact typed scope +/// choices the host can enforce. The manifest's scope remains a declaration; it never supplies a +/// permission id or a host grant directly. +pub(crate) fn manifest_permission_requests( + manifest: &[super::package::PermissionRequest], +) -> Result, GrantError> { + manifest + .iter() + .map(|request| { + let allowed_scopes = + if request.id == gamenode_plugin_protocol::capability::STORAGE_PERSIST { + if request.scope != "own-provider" { + return Err(GrantError::InvalidScope); + } + BTreeSet::from([GrantScope::OwnPrivateNamespace]) + } else if request.id == gamenode_plugin_protocol::capability::NETWORK_FETCH { + if request.scope.len() > 512 { + return Err(GrantError::InvalidScope); + } + request + .scope + .split(',') + .map(|origin| { + super::network::canonical_origin(origin.trim()) + .map(|value| GrantScope::Declared { value }) + .ok_or(GrantError::InvalidScope) + }) + .collect::>()? + } else if let Some((category, _)) = permission_category(&request.id) { + let scope = match request.scope.as_str() { + "own-provider" => GrantScope::OwnCreator { category }, + "published-category" => GrantScope::PublicCategory { category }, + _ => return Err(GrantError::InvalidScope), + }; + BTreeSet::from([scope]) + } else if is_known_permission(&request.id) { + if !valid_identity_part(&request.scope, 512) { + return Err(GrantError::InvalidScope); + } + BTreeSet::from([GrantScope::Declared { + value: request.scope.clone(), + }]) + } else if request.required { + return Err(GrantError::RequiredPermissionUnsupported); + } else { + BTreeSet::new() + }; + Ok(PermissionRequest { + permission_id: request.id.clone(), + required: request.required, + allowed_scopes, + }) + }) + .collect() +} + +fn is_known_permission(permission: &str) -> bool { + gamenode_plugin_protocol::capability::KNOWN.contains(&permission) +} + +fn validate_permission_request(request: &PermissionRequest) -> Result<(), GrantError> { + if request.permission_id.trim().is_empty() + || request.permission_id.len() > 128 + || request.permission_id.chars().any(char::is_control) + { + return Err(GrantError::InvalidRequest); + } + if request.permission_id == gamenode_plugin_protocol::capability::STORAGE_PERSIST { + if request + .allowed_scopes + .iter() + .any(|scope| *scope != GrantScope::OwnPrivateNamespace) + { + return Err(GrantError::InvalidScope); + } + return Ok(()); + } + if is_known_permission(&request.permission_id) && request.allowed_scopes.is_empty() { + return Err(GrantError::InvalidRequest); + } + if !is_known_permission(&request.permission_id) { + return Ok(()); + } + for scope in &request.allowed_scopes { + validate_scope_for_permission(&request.permission_id, scope)?; + } + Ok(()) +} + +fn validate_scope_for_permission( + permission_id_value: &str, + scope: &GrantScope, +) -> Result<(), GrantError> { + if permission_id_value == gamenode_plugin_protocol::capability::STORAGE_PERSIST { + return if scope == &GrantScope::OwnPrivateNamespace { + Ok(()) + } else { + Err(GrantError::InvalidScope) + }; + } + let Some((category, operation)) = permission_category(permission_id_value) else { + if permission_id_value == gamenode_plugin_protocol::capability::NETWORK_FETCH { + return if matches!(scope, GrantScope::Declared { value } + if super::network::canonical_origin(value).as_ref() == Some(value)) + { + Ok(()) + } else { + Err(GrantError::InvalidScope) + }; + } + return if is_known_permission(permission_id_value) + && matches!(scope, GrantScope::Declared { value } if valid_identity_part(value, 512)) + { + Ok(()) + } else { + Err(GrantError::InvalidScope) + }; + }; + let matching_category = match scope { + GrantScope::OwnCreator { + category: scope_category, + } + | GrantScope::PublicCategory { + category: scope_category, + } + | GrantScope::SelectedRecords { + category: scope_category, + .. + } => scope_category == &category, + GrantScope::Declared { .. } => false, + GrantScope::OwnPrivateNamespace => false, + }; + if !matching_category { + return Err(GrantError::InvalidScope); + } + if operation == Operation::Create && matches!(scope, GrantScope::SelectedRecords { .. }) { + return Err(GrantError::InvalidScope); + } + if let GrantScope::SelectedRecords { record_ids, .. } = scope + && (record_ids.is_empty() + || record_ids.len() > 1000 + || record_ids.iter().any(|id| !valid_identity_part(id, 256))) + { + return Err(GrantError::InvalidScope); + } + Ok(()) +} + +fn identity_key(identity: &PluginIdentity) -> String { + format!( + "{}\0{}\0{}", + identity.plugin_id, identity.publisher_fingerprint, identity.profile_id + ) +} + +fn valid_identity_part(value: &str, max_len: usize) -> bool { + !value.trim().is_empty() && value.len() <= max_len && !value.chars().any(char::is_control) +} + +#[cfg(unix)] +pub(crate) fn ensure_private_dir(path: &Path) -> io::Result<()> { + use std::os::unix::fs::{DirBuilderExt, PermissionsExt}; + match fs::symlink_metadata(path) { + Ok(meta) if meta.file_type().is_symlink() || !meta.is_dir() => Err(io::Error::new( + io::ErrorKind::InvalidInput, + "unsafe grant directory", + )), + Ok(meta) => { + if meta.permissions().mode() & 0o077 != 0 { + fs::set_permissions(path, fs::Permissions::from_mode(0o700))?; + } + Ok(()) + } + Err(error) if error.kind() == io::ErrorKind::NotFound => { + match fs::DirBuilder::new().mode(0o700).create(path) { + Ok(()) => Ok(()), + Err(error) if error.kind() == io::ErrorKind::AlreadyExists => { + ensure_private_dir(path) + } + Err(error) => Err(error), + } + } + Err(error) => Err(error), + } +} + +#[cfg(not(unix))] +pub(crate) fn ensure_private_dir(path: &Path) -> io::Result<()> { + match fs::symlink_metadata(path) { + Ok(meta) if meta.file_type().is_symlink() || !meta.is_dir() => Err(io::Error::new( + io::ErrorKind::InvalidInput, + "unsafe grant directory", + )), + Ok(_) => Ok(()), + Err(error) if error.kind() == io::ErrorKind::NotFound => match fs::create_dir(path) { + Ok(()) => Ok(()), + Err(error) if error.kind() == io::ErrorKind::AlreadyExists => ensure_private_dir(path), + Err(error) => Err(error), + }, + Err(error) => Err(error), + } +} + +#[cfg(unix)] +pub(crate) fn ensure_private_file(path: &Path) -> io::Result<()> { + use std::os::unix::fs::PermissionsExt; + let meta = fs::symlink_metadata(path)?; + if meta.file_type().is_symlink() || !meta.is_file() { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "unsafe grant file", + )); + } + if meta.permissions().mode() & 0o077 != 0 { + fs::set_permissions(path, fs::Permissions::from_mode(0o600))?; + } + Ok(()) +} + +#[cfg(not(unix))] +pub(crate) fn ensure_private_file(path: &Path) -> io::Result<()> { + let meta = fs::symlink_metadata(path)?; + if meta.file_type().is_symlink() || !meta.is_file() { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "unsafe grant file", + )); + } + Ok(()) +} + +pub(crate) fn sync_dir(path: &Path) -> io::Result<()> { + #[cfg(unix)] + File::open(path)?.sync_all()?; + #[cfg(not(unix))] + let _ = path; + Ok(()) +} + +pub(crate) fn atomic_replace(from: &Path, to: &Path) -> io::Result<()> { + #[cfg(windows)] + { + use std::os::windows::ffi::OsStrExt; + use windows_sys::Win32::Storage::FileSystem::{ + MOVEFILE_REPLACE_EXISTING, MOVEFILE_WRITE_THROUGH, MoveFileExW, + }; + let from = from + .as_os_str() + .encode_wide() + .chain(Some(0)) + .collect::>(); + let to = to + .as_os_str() + .encode_wide() + .chain(Some(0)) + .collect::>(); + // SAFETY: both paths are NUL-terminated UTF-16 buffers valid for this call. + let result = unsafe { + MoveFileExW( + from.as_ptr(), + to.as_ptr(), + MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH, + ) + }; + if result == 0 { + Err(io::Error::last_os_error()) + } else { + Ok(()) + } + } + #[cfg(not(windows))] + { + fs::rename(from, to) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use tempfile::tempdir; + + fn identity() -> PluginIdentity { + PluginIdentity { + plugin_id: "org.example.consumer".into(), + publisher_fingerprint: "SHA256:consumer".into(), + profile_id: "default".into(), + } + } + + fn scopes() -> BTreeSet { + BTreeSet::from([ + GrantScope::OwnCreator { + category: DomainCategory::Runtime, + }, + GrantScope::PublicCategory { + category: DomainCategory::Runtime, + }, + GrantScope::SelectedRecords { + category: DomainCategory::Runtime, + record_ids: BTreeSet::from(["runtime-a".into()]), + }, + ]) + } + + fn request(permission_id: &str, allowed_scopes: BTreeSet) -> PermissionRequest { + PermissionRequest { + permission_id: permission_id.into(), + required: false, + allowed_scopes, + } + } + + #[test] + fn grants_are_default_deny_persisted_and_operation_scoped() { + let dir = tempdir().unwrap(); + let mut store = PermissionGrantStore::open(dir.path()).unwrap(); + let actor = identity(); + let record = DomainRecord { + id: "runtime-a".into(), + category: DomainCategory::Runtime, + creator_plugin_id: "org.example.producer".into(), + published: true, + revision: 7, + }; + assert_eq!( + store.authorize_domain(&actor, &record, Operation::Read), + Err(GrantError::Denied) + ); + let read_id = permission_id(&DomainCategory::Runtime, Operation::Read); + let update_id = permission_id(&DomainCategory::Runtime, Operation::Update); + let delete_id = permission_id(&DomainCategory::Runtime, Operation::Delete); + let reqs = vec![ + request(&read_id, scopes()), + request(&update_id, scopes()), + request(&delete_id, scopes()), + ]; + let dec = vec![ + PermissionDecision { + permission_id: read_id.clone(), + scope: GrantScope::SelectedRecords { + category: DomainCategory::Runtime, + record_ids: BTreeSet::from(["runtime-a".into()]), + }, + granted: true, + }, + PermissionDecision { + permission_id: update_id.clone(), + scope: GrantScope::SelectedRecords { + category: DomainCategory::Runtime, + record_ids: BTreeSet::from(["runtime-a".into()]), + }, + granted: true, + }, + ]; + assert_eq!(store.replace_grants(actor.clone(), &reqs, &dec).unwrap(), 1); + assert_eq!( + store.authorize_domain(&actor, &record, Operation::Read), + Ok(1) + ); + assert_eq!( + store.authorize_domain(&actor, &record, Operation::Update), + Ok(1) + ); + assert_eq!( + store.authorize_domain(&actor, &record, Operation::Delete), + Err(GrantError::Denied) + ); + let restarted = PermissionGrantStore::open(dir.path()).unwrap(); + assert_eq!( + restarted.authorize_domain(&actor, &record, Operation::Read), + Ok(1) + ); + assert_eq!( + restarted.authorize_domain(&actor, &record, Operation::Delete), + Err(GrantError::Denied) + ); + } + + #[test] + fn selected_read_does_not_require_category_grant_and_revocation_changes_revision() { + let dir = tempdir().unwrap(); + let mut store = PermissionGrantStore::open(dir.path()).unwrap(); + let actor = identity(); + let permission = permission_id(&DomainCategory::Runtime, Operation::Read); + let selected = GrantScope::SelectedRecords { + category: DomainCategory::Runtime, + record_ids: BTreeSet::from(["runtime-a".into()]), + }; + let reqs = vec![request( + &permission, + BTreeSet::from([ + selected.clone(), + GrantScope::PublicCategory { + category: DomainCategory::Runtime, + }, + ]), + )]; + store + .replace_grants( + actor.clone(), + &reqs, + &[PermissionDecision { + permission_id: permission.clone(), + scope: selected.clone(), + granted: true, + }], + ) + .unwrap(); + let record = DomainRecord { + id: "runtime-a".into(), + category: DomainCategory::Runtime, + creator_plugin_id: "org.example.producer".into(), + published: true, + revision: 1, + }; + assert!( + store + .authorize_domain(&actor, &record, Operation::Read) + .is_ok() + ); + let revision = store.replace_grants(actor.clone(), &reqs, &[]).unwrap(); + assert_eq!(revision, 2); + assert_eq!( + store.authorize_domain(&actor, &record, Operation::Read), + Err(GrantError::Denied) + ); + } + + #[test] + fn create_is_category_scoped_and_creator_scope_requires_user_consent() { + let id = permission_id(&DomainCategory::Runtime, Operation::Create); + let selected = GrantScope::SelectedRecords { + category: DomainCategory::Runtime, + record_ids: BTreeSet::from(["new".into()]), + }; + assert_eq!( + validate_scope_for_permission(&id, &selected), + Err(GrantError::InvalidScope) + ); + let dir = tempdir().unwrap(); + let mut store = PermissionGrantStore::open(dir.path()).unwrap(); + let actor = identity(); + let own = GrantScope::OwnCreator { + category: DomainCategory::Runtime, + }; + store + .replace_grants( + actor.clone(), + &[request(&id, BTreeSet::from([own.clone()]))], + &[PermissionDecision { + permission_id: id.clone(), + scope: own, + granted: true, + }], + ) + .unwrap(); + let record = DomainRecord { + id: "created".into(), + category: DomainCategory::Runtime, + creator_plugin_id: actor.plugin_id.clone(), + published: false, + revision: 0, + }; + assert!( + store + .authorize_domain(&actor, &record, Operation::Create) + .is_ok() + ); + } + + #[test] + fn private_cleanup_is_own_namespace_only_and_does_not_grant_public_delete() { + let dir = tempdir().unwrap(); + let mut store = PermissionGrantStore::open(dir.path()).unwrap(); + let actor = identity(); + let persist = gamenode_plugin_protocol::capability::STORAGE_PERSIST; + store + .replace_grants( + actor.clone(), + &[request( + persist, + BTreeSet::from([GrantScope::OwnPrivateNamespace]), + )], + &[PermissionDecision { + permission_id: persist.into(), + scope: GrantScope::OwnPrivateNamespace, + granted: true, + }], + ) + .unwrap(); + assert!( + store + .authorize_private_cleanup(&actor, &actor.plugin_id) + .is_ok() + ); + assert_eq!( + store.authorize_private_cleanup(&actor, "org.example.other"), + Err(GrantError::ForeignPrivateNamespace) + ); + let public = DomainRecord { + id: "r".into(), + category: DomainCategory::Runtime, + creator_plugin_id: "org.example.producer".into(), + published: true, + revision: 1, + }; + assert_eq!( + store.authorize_domain(&actor, &public, Operation::Delete), + Err(GrantError::Denied) + ); + } + + #[test] + fn commit_audit_uses_authenticated_actor_preserves_record_creator_and_checks_revision() { + let dir = tempdir().unwrap(); + let mut store = PermissionGrantStore::open(dir.path()).unwrap(); + let actor = identity(); + let permission = permission_id(&DomainCategory::Runtime, Operation::Update); + let scope = GrantScope::SelectedRecords { + category: DomainCategory::Runtime, + record_ids: BTreeSet::from(["runtime-a".into()]), + }; + let reqs = vec![request(&permission, BTreeSet::from([scope.clone()]))]; + store + .replace_grants( + actor.clone(), + &reqs, + &[PermissionDecision { + permission_id: permission, + scope, + granted: true, + }], + ) + .unwrap(); + let record = DomainRecord { + id: "runtime-a".into(), + category: DomainCategory::Runtime, + creator_plugin_id: "org.example.producer".into(), + published: true, + revision: 5, + }; + assert_eq!( + store.audit_domain_commit(&actor, &record, Operation::Update, Some(4), 1), + Err(GrantError::StaleRevision) + ); + let event = store + .audit_domain_commit(&actor, &record, Operation::Update, Some(5), 1) + .unwrap(); + assert_eq!(event.actor_plugin_id, actor.plugin_id); + assert_eq!(record.creator_plugin_id, "org.example.producer"); + assert_eq!(event.previous_revision, Some(5)); + assert_eq!(event.resulting_revision, Some(6)); + assert_eq!(store.audit_events(), &[event]); + } + + #[test] + fn failed_persistence_does_not_change_effective_in_memory_grants() { + let dir = tempdir().unwrap(); + let mut store = PermissionGrantStore::open(dir.path()).unwrap(); + let actor = identity(); + let permission = permission_id(&DomainCategory::Runtime, Operation::Read); + let own = GrantScope::OwnCreator { + category: DomainCategory::Runtime, + }; + let reqs = vec![request(&permission, BTreeSet::from([own.clone()]))]; + store + .replace_grants( + actor.clone(), + &reqs, + &[PermissionDecision { + permission_id: permission.clone(), + scope: own.clone(), + granted: true, + }], + ) + .unwrap(); + let target_path = store.path.clone(); + fs::remove_file(&target_path).unwrap(); + fs::create_dir(&target_path).unwrap(); + let err = store.replace_grants(actor.clone(), &reqs, &[]).unwrap_err(); + assert!(matches!(err, GrantError::Io(_))); + assert!( + store + .effective_grants(&actor) + .iter() + .any(|grant| grant.permission_id == permission + && grant.state == PermissionState::Granted) + ); + } + + #[test] + fn revoking_updated_permission_persists_denial_and_advances_revision() { + let dir = tempdir().unwrap(); + let actor = identity(); + let permission = permission_id(&DomainCategory::Runtime, Operation::Read); + let scope = GrantScope::OwnCreator { + category: DomainCategory::Runtime, + }; + let mut store = PermissionGrantStore::open(dir.path()).unwrap(); + store + .replace_grants( + actor.clone(), + &[request(&permission, BTreeSet::from([scope.clone()]))], + &[PermissionDecision { + permission_id: permission.clone(), + scope, + granted: true, + }], + ) + .unwrap(); + let previous_revision = store.revision(&actor); + let ids = BTreeSet::from([permission.clone()]); + let next_revision = store.revoke_permissions(&actor, &ids).unwrap(); + + assert_eq!(next_revision, previous_revision + 1); + assert_eq!( + store.effective_grants(&actor)[0].state, + PermissionState::Denied + ); + let reopened = PermissionGrantStore::open(dir.path()).unwrap(); + assert_eq!(reopened.revision(&actor), next_revision); + assert_eq!( + reopened.effective_grants(&actor)[0].state, + PermissionState::Denied + ); + } + + #[test] + fn unknown_optional_permissions_remain_unsupported_and_unknown_required_are_blocked() { + let dir = tempdir().unwrap(); + let mut store = PermissionGrantStore::open(dir.path()).unwrap(); + let actor = identity(); + let unknown = request( + "future.capability", + BTreeSet::from([GrantScope::Declared { + value: "game:one".into(), + }]), + ); + store + .replace_grants(actor.clone(), std::slice::from_ref(&unknown), &[]) + .unwrap(); + assert_eq!( + store.effective_grants(&actor)[0].state, + PermissionState::Unsupported + ); + let required = PermissionRequest { + required: true, + ..unknown + }; + assert!(matches!( + store.replace_grants(actor, &[required], &[]), + Err(GrantError::RequiredPermissionUnsupported) + )); + } + + #[test] + fn domain_catalog_maps_each_operation_to_a_distinct_known_permission() { + for category in [ + DomainCategory::Runtime, + DomainCategory::LibraryRoot, + DomainCategory::SaveProfile, + ] { + let ids: BTreeSet<_> = [ + Operation::Read, + Operation::Create, + Operation::Update, + Operation::Delete, + ] + .into_iter() + .map(|operation| permission_id(&category, operation)) + .collect(); + assert_eq!(ids.len(), 4); + assert!(ids.iter().all(|permission| { + gamenode_plugin_protocol::capability::KNOWN.contains(&permission.as_str()) + })); + } + assert!(!gamenode_plugin_protocol::capability::KNOWN.contains(&"library.roots.write")); + assert!(!gamenode_plugin_protocol::capability::KNOWN.contains(&"game.runtime.write")); + } + + #[test] + fn manifest_requests_map_only_to_host_supported_typed_scopes() { + let domain = permission_id(&DomainCategory::Runtime, Operation::Read); + let requests = manifest_permission_requests(&[ + super::super::package::PermissionRequest { + id: domain.clone(), + required: false, + scope: "published-category".into(), + reason: "test".into(), + impact_if_disabled: None, + }, + super::super::package::PermissionRequest { + id: gamenode_plugin_protocol::capability::STORAGE_PERSIST.into(), + required: false, + scope: "own-provider".into(), + reason: "test".into(), + impact_if_disabled: None, + }, + ]) + .unwrap(); + assert_eq!( + requests[0].allowed_scopes, + BTreeSet::from([GrantScope::PublicCategory { + category: DomainCategory::Runtime, + }]) + ); + assert_eq!( + requests[1].allowed_scopes, + BTreeSet::from([GrantScope::OwnPrivateNamespace]) + ); + let malformed = super::super::package::PermissionRequest { + id: domain, + required: false, + scope: "any-record".into(), + reason: "test".into(), + impact_if_disabled: None, + }; + assert_eq!( + manifest_permission_requests(&[malformed]), + Err(GrantError::InvalidScope) + ); + } +} diff --git a/crates/app/src/plugin_host/intents.rs b/crates/app/src/plugin_host/intents.rs new file mode 100644 index 000000000..eacc934b4 --- /dev/null +++ b/crates/app/src/plugin_host/intents.rs @@ -0,0 +1,301 @@ +//! Host-issued user intents (task 10.10, design section 20). +//! +//! `GamesRequestLaunch` and `GamesRequestInstall` execute nothing unless the user explicitly +//! wanted it. That is host state, never a claim the plugin makes, and it comes in two forms: +//! +//! * a **pre-issued intent**: an opaque, unguessable id the host creates from a user action in +//! Core and hands to the plugin it concerns. It is bound to the plugin and publisher, the +//! profile epoch, the game and installation, the operation and (for launch) the detected-target +//! revision; it is single use and valid for [`INTENT_TTL`]; +//! * an **on-request confirmation**: with no id, the host asks the user through a [`Prompter`] +//! (a dialog), which may also offer to remember the answer for that plugin and game +//! (`plugin_storage::IntentApproval`, kept in the plugin's own store and revoked from the +//! settings). +//! +//! A refusal never says which part of an id was wrong. Nothing here starts a game: the caller +//! checks the intent and then runs the operation. + +use std::collections::{HashMap, HashSet}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +use async_trait::async_trait; +use tonic::Status; + +/// How long a pre-issued intent is valid. +pub const INTENT_TTL: Duration = Duration::from_secs(60); +/// Pre-issued intents the host holds at once; the oldest go first. +pub const MAX_ISSUED: usize = 256; +/// How long the dialog may stay unanswered before the request fails (the limit of folder +/// approvals). +pub const CONFIRMATION_TIMEOUT: Duration = Duration::from_secs(5 * 60); +/// Confirmations one plugin may have waiting for the user at once. +pub const MAX_PENDING_PER_PLUGIN: usize = 4; + +/// What an intent allows. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Operation { + Launch, + CustomLaunch, + Install, + BackupRestore, + RuntimeSessionContext, +} + +impl Operation { + /// The word stored with a remembered confirmation and shown in the dialog. + pub const fn as_str(self) -> &'static str { + match self { + Self::Launch => "launch", + Self::CustomLaunch => "custom_launch", + Self::Install => "install", + Self::BackupRestore => "backup_restore", + Self::RuntimeSessionContext => "runtime_session_context", + } + } +} + +/// Everything an intent is bound to. A different value in any field is a different request. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Binding { + pub plugin_id: String, + pub publisher_fingerprint: String, + pub profile_epoch: u64, + pub game_id: String, + pub installation_id: String, + pub operation: Operation, + /// The detected-target revision a launch was requested at; 0 for an install. + pub target_revision: u64, + /// The custom recipe being approved; empty for other operations. + pub recipe_id: String, + /// The custom recipe revision for custom launch; 0 for other operations. + pub recipe_revision: u64, + /// Canonical versioned fingerprint of the complete resolved launch plan; empty for install. + pub plan_fingerprint: String, +} + +struct Issued { + binding: Binding, + at: Instant, +} + +/// What the dialog shows. `game_name` comes from the provider's library entry and is untrusted +/// text: show it as plain text. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ConfirmationRequest { + pub plugin_id: String, + pub publisher_fingerprint: String, + pub game_name: String, + pub operation: Operation, + /// Host-resolved restore paths and snapshot identity; never a plugin explanation. + pub details: Vec, + /// Exact resolved launch details when this confirmation covers a launch plan. + pub launch_plan: Option, +} + +/// The user's answer. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Answer { + pub approved: bool, + /// Only meaningful when approved: remember it for this plugin and game. + pub remember: bool, +} + +/// The user's side of a confirmation. The host calls it off the UI thread, and a call that takes +/// longer than [`CONFIRMATION_TIMEOUT`] counts as declined. +#[async_trait] +pub trait Prompter: Send + Sync { + async fn confirm(&self, request: ConfirmationRequest) -> Result; +} + +/// How a confirmation ended without an answer being given. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Verdict { + Approved { remember: bool }, + Declined, + TimedOut, +} + +type Clock = Arc Instant + Send + Sync>; + +/// The host's intent table and the port to the user. Shared by every plugin session. +pub struct Intents { + issued: Mutex>, + pending: Mutex>, + prompter: Mutex>>, + clock: Clock, + timeout: Duration, +} + +impl Default for Intents { + fn default() -> Self { + Self { + issued: Mutex::default(), + pending: Mutex::default(), + prompter: Mutex::default(), + clock: Arc::new(Instant::now), + timeout: CONFIRMATION_TIMEOUT, + } + } +} + +fn invalid() -> Status { + // One answer for every cause, so an id cannot be probed for what is wrong with it. + Status::failed_precondition( + "the user intent is missing, expired, already used, or not for this request", + ) +} + +/// Who is waiting: plugin, publisher, game, installation and operation. +type PendingKey = (String, String, String, String, Operation); + +/// Releases a pending-confirmation slot when dropped. +pub struct Pending { + intents: Arc, + key: PendingKey, +} + +impl Drop for Pending { + fn drop(&mut self) { + self.intents + .pending + .lock() + .unwrap_or_else(|p| p.into_inner()) + .remove(&self.key); + } +} + +impl Intents { + #[cfg(test)] + pub(crate) fn with_clock( + mut self, + clock: impl Fn() -> Instant + Send + Sync + 'static, + ) -> Self { + self.clock = Arc::new(clock); + self + } + + #[cfg(test)] + pub(crate) fn with_timeout(mut self, timeout: Duration) -> Self { + self.timeout = timeout; + self + } + + /// Connects the user's side. Until it is set, a request with no pre-issued intent cannot be + /// confirmed and fails with `FAILED_PRECONDITION`. + pub fn set_prompter(&self, prompter: Arc) { + *self.prompter.lock().unwrap_or_else(|p| p.into_inner()) = Some(prompter); + } + + /// Creates an intent for `binding`, from an explicit user action in Core. The id is for the + /// plugin the binding names; nothing else can redeem it. + pub fn issue(&self, binding: Binding) -> Result { + let mut bytes = [0_u8; 16]; + getrandom::fill(&mut bytes).map_err(|_| Status::internal("no source of randomness"))?; + let id = format!( + "intent-{}", + bytes.iter().map(|b| format!("{b:02x}")).collect::() + ); + let now = (self.clock)(); + let mut issued = self.issued.lock().unwrap_or_else(|p| p.into_inner()); + issued.retain(|_, intent| now.duration_since(intent.at) < INTENT_TTL); + if issued.len() >= MAX_ISSUED + && let Some(oldest) = issued + .iter() + .min_by_key(|(_, intent)| intent.at) + .map(|(id, _)| id.clone()) + { + issued.remove(&oldest); + } + issued.insert(id.clone(), Issued { binding, at: now }); + Ok(id) + } + + /// Discards a pre-issued intent when the host could not complete the matching startup. + pub(crate) fn revoke_issued(&self, id: &str) { + self.issued + .lock() + .unwrap_or_else(|p| p.into_inner()) + .remove(id); + } + + /// Spends `id` for a request bound to `binding`. Only a match, once, within its lifetime. + /// A failed attempt spends nothing. + pub fn redeem(&self, binding: &Binding, id: &str) -> Result<(), Status> { + let now = (self.clock)(); + let mut issued = self.issued.lock().unwrap_or_else(|p| p.into_inner()); + issued.retain(|_, intent| now.duration_since(intent.at) < INTENT_TTL); + match issued.get(id) { + Some(intent) if intent.binding == *binding => { + issued.remove(id); + Ok(()) + } + _ => Err(invalid()), + } + } + + /// Claims the right to ask the user about this game, or refuses when the plugin already has + /// a confirmation waiting for it or too many waiting. + pub fn begin_pending(self: &Arc, binding: &Binding) -> Result { + let key = ( + binding.plugin_id.clone(), + binding.publisher_fingerprint.clone(), + binding.game_id.clone(), + binding.installation_id.clone(), + binding.operation, + ); + let mut pending = self.pending.lock().unwrap_or_else(|p| p.into_inner()); + if pending.contains(&key) { + return Err(Status::failed_precondition( + "a confirmation for this game is already waiting for the user", + )); + } + let own = pending + .iter() + .filter(|(plugin, publisher, ..)| { + *plugin == binding.plugin_id && *publisher == binding.publisher_fingerprint + }) + .count(); + if own >= MAX_PENDING_PER_PLUGIN { + return Err(Status::resource_exhausted( + "too many confirmations are waiting for the user for this plugin", + )); + } + pending.insert(key.clone()); + Ok(Pending { + intents: Arc::clone(self), + key, + }) + } + + /// Whether this build can ask the user at all. + pub fn can_confirm(&self) -> bool { + self.prompter + .lock() + .unwrap_or_else(|p| p.into_inner()) + .is_some() + } + + /// Asks the user. `FAILED_PRECONDITION` when this build has no dialog. + pub async fn confirm(&self, request: ConfirmationRequest) -> Result { + let prompter = self + .prompter + .lock() + .unwrap_or_else(|p| p.into_inner()) + .clone() + .ok_or_else(|| { + Status::failed_precondition("this GameNode build cannot ask for confirmations yet") + })?; + match tokio::time::timeout(self.timeout, prompter.confirm(request)).await { + Err(_) => Ok(Verdict::TimedOut), + Ok(Err(status)) => Err(status), + Ok(Ok(answer)) if answer.approved => Ok(Verdict::Approved { + remember: answer.remember, + }), + Ok(Ok(_)) => Ok(Verdict::Declined), + } + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/app/src/plugin_host/intents/tests.rs b/crates/app/src/plugin_host/intents/tests.rs new file mode 100644 index 000000000..790c1a592 --- /dev/null +++ b/crates/app/src/plugin_host/intents/tests.rs @@ -0,0 +1,262 @@ +//! The intent table and the user's port (task 10.10), without a plugin session. The requests +//! that use them are tested over the real socket in `resources/tests/games.rs`. + +use std::sync::Mutex as StdMutex; + +use super::*; + +fn binding() -> Binding { + Binding { + plugin_id: "org.example".into(), + publisher_fingerprint: "ab".repeat(32), + profile_epoch: 3, + game_id: "42".into(), + installation_id: "inst-1".into(), + operation: Operation::Launch, + target_revision: 7, + recipe_id: String::new(), + recipe_revision: 0, + plan_fingerprint: String::new(), + } +} + +fn clocked() -> (Intents, Arc>) { + let now = Arc::new(StdMutex::new(Instant::now())); + let intents = Intents::default().with_clock({ + let now = now.clone(); + move || *now.lock().unwrap() + }); + (intents, now) +} + +#[test] +fn an_intent_is_spent_by_its_first_redemption_only() { + let intents = Intents::default(); + let id = intents.issue(binding()).unwrap(); + assert!(id.starts_with("intent-") && id.len() > 20); + assert_ne!( + id, + intents.issue(binding()).unwrap(), + "ids are never repeated" + ); + intents.redeem(&binding(), &id).unwrap(); + assert_eq!( + intents.redeem(&binding(), &id).unwrap_err().code(), + tonic::Code::FailedPrecondition + ); +} + +#[test] +fn an_intent_cannot_be_shifted_to_another_plugin_profile_game_operation_or_revision() { + let intents = Intents::default(); + let id = intents.issue(binding()).unwrap(); + let shifted = [ + Binding { + plugin_id: "org.other".into(), + ..binding() + }, + Binding { + publisher_fingerprint: "cd".repeat(32), + ..binding() + }, + Binding { + profile_epoch: 4, + ..binding() + }, + Binding { + game_id: "43".into(), + ..binding() + }, + Binding { + installation_id: "inst-2".into(), + ..binding() + }, + Binding { + operation: Operation::Install, + ..binding() + }, + Binding { + target_revision: 8, + ..binding() + }, + Binding { + recipe_revision: 2, + ..binding() + }, + Binding { + recipe_id: "another-recipe".into(), + ..binding() + }, + Binding { + plan_fingerprint: "v1:changed".into(), + ..binding() + }, + ]; + let unknown = intents.redeem(&binding(), "intent-nothing").unwrap_err(); + for other in &shifted { + let refused = intents.redeem(other, &id).unwrap_err(); + // Every cause answers the same, so an id cannot be probed. + assert_eq!(refused.code(), tonic::Code::FailedPrecondition); + assert_eq!(refused.message(), unknown.message()); + } + // The failed attempts spent nothing: the right request still works, once. + intents.redeem(&binding(), &id).unwrap(); +} + +#[test] +fn an_intent_expires() { + let (intents, now) = clocked(); + let id = intents.issue(binding()).unwrap(); + *now.lock().unwrap() += INTENT_TTL - Duration::from_secs(1); + let still = intents.issue(binding()).unwrap(); + *now.lock().unwrap() += Duration::from_secs(2); + assert!(intents.redeem(&binding(), &id).is_err()); + intents.redeem(&binding(), &still).unwrap(); +} + +#[test] +fn the_table_is_bounded_and_the_oldest_intent_goes_first() { + let (intents, now) = clocked(); + let first = intents.issue(binding()).unwrap(); + for _ in 1..MAX_ISSUED { + *now.lock().unwrap() += Duration::from_millis(1); + intents.issue(binding()).unwrap(); + } + *now.lock().unwrap() += Duration::from_millis(1); + let newest = intents.issue(binding()).unwrap(); + assert!(intents.redeem(&binding(), &first).is_err()); + intents.redeem(&binding(), &newest).unwrap(); +} + +#[test] +fn one_confirmation_per_game_and_a_few_per_plugin_may_wait() { + let intents = Arc::new(Intents::default()); + let first = intents.begin_pending(&binding()).unwrap(); + assert_eq!( + intents.begin_pending(&binding()).err().unwrap().code(), + tonic::Code::FailedPrecondition + ); + // Another game, or the same game's other operation, may wait too, up to the cap. + let install = Binding { + operation: Operation::Install, + ..binding() + }; + let mut held = vec![intents.begin_pending(&install).unwrap()]; + for game in 0..MAX_PENDING_PER_PLUGIN - 2 { + held.push( + intents + .begin_pending(&Binding { + game_id: format!("g{game}"), + ..binding() + }) + .unwrap(), + ); + } + assert_eq!( + intents + .begin_pending(&Binding { + game_id: "one-too-many".into(), + ..binding() + }) + .err() + .unwrap() + .code(), + tonic::Code::ResourceExhausted + ); + // Another plugin is not held back. + let other = Binding { + plugin_id: "org.other".into(), + ..binding() + }; + let _theirs = intents.begin_pending(&other).unwrap(); + // Dropping a slot frees it. + drop(first); + held.push(intents.begin_pending(&binding()).unwrap()); +} + +struct Scripted(StdMutex>>, Duration); + +#[async_trait] +impl Prompter for Scripted { + async fn confirm(&self, request: ConfirmationRequest) -> Result { + assert_eq!(request.plugin_id, "org.example"); + tokio::time::sleep(self.1).await; + self.0.lock().unwrap().take().unwrap() + } +} + +fn request() -> ConfirmationRequest { + ConfirmationRequest { + plugin_id: "org.example".into(), + publisher_fingerprint: "ab".repeat(32), + game_name: "Game".into(), + operation: Operation::Launch, + details: vec![], + launch_plan: None, + } +} + +fn answering(answer: Result, after: Duration) -> Arc { + Arc::new(Scripted(StdMutex::new(Some(answer)), after)) +} + +#[tokio::test] +async fn without_a_dialog_a_confirmation_cannot_be_asked() { + let status = Intents::default().confirm(request()).await.unwrap_err(); + assert_eq!(status.code(), tonic::Code::FailedPrecondition); +} + +#[tokio::test] +async fn the_users_answer_is_reported_as_given() { + for (answer, expected) in [ + ( + Answer { + approved: true, + remember: true, + }, + Verdict::Approved { remember: true }, + ), + ( + Answer { + approved: true, + remember: false, + }, + Verdict::Approved { remember: false }, + ), + // Remembering is part of an approval, never of a refusal. + ( + Answer { + approved: false, + remember: true, + }, + Verdict::Declined, + ), + ] { + let intents = Intents::default(); + intents.set_prompter(answering(Ok(answer), Duration::ZERO)); + assert_eq!(intents.confirm(request()).await.unwrap(), expected); + } +} + +#[tokio::test] +async fn an_unanswered_dialog_times_out_as_declined_and_an_error_is_passed_on() { + let intents = Intents::default().with_timeout(Duration::from_millis(20)); + intents.set_prompter(answering( + Ok(Answer { + approved: true, + remember: false, + }), + Duration::from_secs(5), + )); + assert_eq!(intents.confirm(request()).await.unwrap(), Verdict::TimedOut); + + let failing = Intents::default(); + failing.set_prompter(answering( + Err(Status::unavailable("no window")), + Duration::ZERO, + )); + assert_eq!( + failing.confirm(request()).await.unwrap_err().code(), + tonic::Code::Unavailable + ); +} diff --git a/crates/app/src/plugin_host/jobs.rs b/crates/app/src/plugin_host/jobs.rs new file mode 100644 index 000000000..c5ae2ab74 --- /dev/null +++ b/crates/app/src/plugin_host/jobs.rs @@ -0,0 +1,777 @@ +//! Caller-owned jobs of third-party plugins, served through `ResourceHost.JobsGet/Watch/Cancel`. +//! +//! A long operation (an install, a backup, a restore) answers with a job instead of blocking the +//! call. The job belongs to the host-authenticated owner ([`ExternalNamespaceResolver::job_owner`]: +//! plugin id, pinned publisher fingerprint and account profile) and to the profile epoch it was +//! created in. A request names a job by its opaque id and nothing else: an id that is unknown, +//! another owner's, from an earlier profile or already forgotten is the same `NOT_FOUND`, so an +//! id says nothing about jobs it does not own. +//! +//! Every job remembers the permission of the operation that created it. Reading, watching and +//! cancelling it need that permission *still*; the host checks it on every call and before every +//! event a watch delivers. The work itself rechecks through [`JobContext::check`] before it +//! commits an effect, so a permission lost, a profile switched or a cancellation asked for +//! between the start and the commit stops the effect. +//! +//! Retrying a request with the same idempotency key answers with the same job and starts no new +//! work; the same key for a different request is refused. Keys are remembered for 24 hours, but +//! a finished job is only kept for an hour (and at most [`MAX_FINISHED_PER_OWNER`] of them), so +//! a retry that finds its job already forgotten is refused rather than run again. +//! +//! Jobs live in the host's memory: a host restart forgets them and their keys, and the work they +//! stood for does not resume. An operation whose effect must never repeat across a restart has to +//! be idempotent in its own domain (it is, for the installs and backups that will use this). + +use std::collections::HashMap; +use std::future::Future; +use std::pin::Pin; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +use gamenode_plugin_protocol::proto::{JobEvent, JobReply, JobState}; +use tokio::sync::watch; +use tonic::Status; + +use super::profile::ProfileContext; +use super::provider::ResourceCaller; + +/// Jobs one owner may have running at once. +pub const MAX_ACTIVE_PER_OWNER: usize = 8; +/// Jobs running at once, across every plugin. +pub const MAX_ACTIVE_TOTAL: usize = 32; +/// Finished jobs one owner keeps; the oldest go first. +pub const MAX_FINISHED_PER_OWNER: usize = 32; +/// How long a finished job stays readable. +pub const FINISHED_RETENTION: Duration = Duration::from_secs(60 * 60); +/// How long an idempotency key is remembered. +pub const KEY_RETENTION: Duration = Duration::from_secs(24 * 60 * 60); +/// Idempotency keys one owner keeps; the oldest go first. +pub const MAX_KEYS_PER_OWNER: usize = 1024; +/// How long a cancellation waits for the work to stop before answering with the state it is in. +pub const CANCEL_GRACE: Duration = Duration::from_secs(2); +/// The longest result message, in bytes. +pub const MAX_MESSAGE_BYTES: usize = 512; +/// The longest result code, in bytes. +pub const MAX_CODE_BYTES: usize = 64; + +/// The code a job gets when its work panics or stops unexpectedly. +pub const CODE_INTERNAL: &str = "internal"; +/// The code a job gets when its work reaches the commit after the requesting session ended. +pub const CODE_SESSION_ENDED: &str = "session_ended"; + +/// The check a job's work makes before committing: the caller's permission and session still +/// stand. Built by the service that creates the job, from the same guard its mutations use. +pub type Fence = Arc Result<(), Status> + Send + Sync>; + +/// A job's work: runs once, away from the caller's request. +pub type Work = + Box Pin + Send>> + Send + 'static>; + +/// Wraps an async block as a job's work. +pub fn work(run: F) -> Work +where + F: FnOnce(JobContext) -> Fut + Send + 'static, + Fut: Future + Send + 'static, +{ + Box::new(move |context| Box::pin(run(context))) +} + +/// How a job ended. The code is a short machine-readable word; the message is for people. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Outcome { + Succeeded { code: String, message: String }, + Failed { code: String, message: String }, + Cancelled { message: String }, +} + +impl Outcome { + pub fn succeeded(code: &str, message: &str) -> Self { + Self::Succeeded { + code: code.to_owned(), + message: message.to_owned(), + } + } + + pub fn failed(code: &str, message: &str) -> Self { + Self::Failed { + code: code.to_owned(), + message: message.to_owned(), + } + } + + pub fn cancelled(message: &str) -> Self { + Self::Cancelled { + message: message.to_owned(), + } + } + + /// The outcome of work stopped by a refused [`JobContext::check`]. + pub fn stopped(status: &Status) -> Self { + match status.code() { + tonic::Code::Cancelled => Self::cancelled("cancelled before anything was committed"), + // The session that asked for the operation is gone (the plugin stopped or + // restarted): the authority it gave ended with it. + tonic::Code::Unauthenticated => Self::failed( + CODE_SESSION_ENDED, + "the plugin's session ended before the effect was committed; nothing was committed", + ), + tonic::Code::PermissionDenied => Self::failed( + "permission_denied", + "the plugin lost the permission; nothing was committed", + ), + _ => Self::failed( + "failed_precondition", + "the plugin's permissions or profile changed; nothing was committed", + ), + } + } +} + +/// Who owns a job: the host-authenticated plugin/publisher/profile and the profile epoch. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct JobOwner { + key: [u8; 32], + epoch: u64, +} + +impl JobOwner { + /// The owner of the caller's jobs. Only authenticated third-party plugins have a namespace + /// and so jobs; official providers use the host's own adapters. + pub(crate) fn of(caller: &ResourceCaller) -> Result { + let resolver = caller.namespace.as_ref().ok_or_else(|| { + Status::failed_precondition("jobs are available to third-party plugins only") + })?; + Ok(Self { + key: *resolver.job_owner().key(), + epoch: caller.profile_epoch, + }) + } + + #[cfg(test)] + pub(crate) fn for_tests(key: u8, epoch: u64) -> Self { + Self { + key: [key; 32], + epoch, + } + } +} + +/// What the service that starts a job decides, besides the work itself. +pub struct Submission { + /// The permission of the operation that creates the job; every later call needs it too. + pub permission: &'static str, + /// The request's idempotency key and a digest of its meaningful fields. + pub key: String, + pub hash: [u8; 32], + /// Rechecked by the work before it commits. + pub fence: Fence, + /// The account profile; a change ends the job. + pub profile: watch::Receiver>, + /// `Some(message)` when the work first waits for something the user must do: the job stays + /// `QUEUED` with this message until the work calls [`JobContext::start`]. + pub awaiting: Option<&'static str>, +} + +/// What the work sees of its own job. +pub struct JobContext { + id: String, + jobs: Jobs, + cancel: watch::Receiver, + fence: Fence, +} + +impl JobContext { + /// The same cancellation/authorization check, usable by a blocking domain worker. + pub fn checkpoint(&self) -> Fence { + let cancel = self.cancel.clone(); + let fence = self.fence.clone(); + Arc::new(move || { + if *cancel.borrow() { + return Err(Status::cancelled("the job was cancelled")); + } + fence() + }) + } + + pub fn id(&self) -> &str { + &self.id + } + + pub fn is_cancelled(&self) -> bool { + *self.cancel.borrow() + } + + /// Resolves when cancellation is requested (at once if it already was). + pub async fn cancelled(&mut self) { + let _ = self.cancel.wait_for(|cancelled| *cancelled).await; + } + + /// Moves a job that was waiting for the user to `RUNNING`. Refused when the job was cancelled + /// while it waited (it ends as cancelled and the work must stop). A job that does not wait is + /// started by the host and needs no call. + pub fn start(&self) -> Result<(), Status> { + if self.jobs.begin(&self.id) { + Ok(()) + } else { + Err(Status::cancelled("the job was cancelled before it started")) + } + } + + /// Reports progress, 0 to 100. A value that does not go forward is ignored, which also keeps + /// the events a job can ever produce bounded. + pub fn progress(&self, percent: u32) { + self.jobs.progress(&self.id, percent.min(100)); + } + + /// Call right before committing an effect: refuses after a cancellation was requested, a + /// permission was lost or changed, or the profile changed. + pub fn check(&self) -> Result<(), Status> { + if self.is_cancelled() { + return Err(Status::cancelled("the job was cancelled")); + } + (self.fence)() + } +} + +struct Job { + owner: JobOwner, + permission: &'static str, + state: JobState, + code: String, + message: String, + progress: u32, + /// Every event so far. Progress only moves forward, so at most 103 exist. + events: Vec, + cancel: watch::Sender, + changed: watch::Sender, + finished_at: Option, +} + +impl Job { + fn is_terminal(&self) -> bool { + matches!( + self.state, + JobState::Succeeded | JobState::Failed | JobState::Cancelled + ) + } + + fn sequence(&self) -> u64 { + self.events.len() as u64 + } + + fn record(&mut self) { + let sequence = self.sequence() + 1; + self.events.push(JobEvent { + job_id: String::new(), + sequence, + state: self.state as i32, + progress_percent: self.progress, + result_code: self.code.clone(), + message: self.message.clone(), + }); + self.changed.send_replace(sequence); + } + + fn reply(&self, id: &str) -> JobReply { + JobReply { + job_id: id.to_owned(), + state: self.state as i32, + result_code: self.code.clone(), + message: self.message.clone(), + revision: self.sequence(), + } + } +} + +struct Key { + hash: [u8; 32], + job_id: String, + at: Instant, +} + +#[derive(Default)] +struct State { + jobs: HashMap, + keys: HashMap<(JobOwner, String), Key>, + /// The newest profile epoch any caller has presented. + newest_epoch: u64, +} + +type Clock = Arc Instant + Send + Sync>; + +/// The host's job registry. Cheap to clone; clones share the same jobs. +#[derive(Clone)] +pub struct Jobs { + state: Arc>, + clock: Clock, + cancel_grace: Duration, +} + +impl Default for Jobs { + fn default() -> Self { + Self { + state: Arc::default(), + clock: Arc::new(Instant::now), + cancel_grace: CANCEL_GRACE, + } + } +} + +fn clip(text: &str, limit: usize) -> String { + let mut clean: String = text + .chars() + .map(|c| if c.is_control() { ' ' } else { c }) + .collect(); + if clean.len() > limit { + let mut end = limit; + while !clean.is_char_boundary(end) { + end -= 1; + } + clean.truncate(end); + } + clean +} + +fn not_found() -> Status { + Status::not_found("job not found") +} + +fn new_id() -> Result { + let mut bytes = [0_u8; 16]; + getrandom::fill(&mut bytes).map_err(|_| Status::internal("no source of randomness"))?; + Ok(format!( + "job-{}", + bytes.iter().map(|b| format!("{b:02x}")).collect::() + )) +} + +impl Jobs { + #[cfg(test)] + pub(crate) fn with_clock( + mut self, + clock: impl Fn() -> Instant + Send + Sync + 'static, + ) -> Self { + self.clock = Arc::new(clock); + self + } + + #[cfg(test)] + pub(crate) fn with_cancel_grace(mut self, grace: Duration) -> Self { + self.cancel_grace = grace; + self + } + + fn lock(&self) -> std::sync::MutexGuard<'_, State> { + self.state.lock().unwrap_or_else(|p| p.into_inner()) + } + + /// Forgets what expired and what belongs to a profile that is over. + fn prune(&self, state: &mut State, epoch: u64) { + let now = (self.clock)(); + state.newest_epoch = state.newest_epoch.max(epoch); + let newest = state.newest_epoch; + for job in state.jobs.values() { + if !job.is_terminal() && job.owner.epoch < newest { + job.cancel.send_replace(true); + } + } + state.jobs.retain(|_, job| match job.finished_at { + Some(at) => now.duration_since(at) < FINISHED_RETENTION && job.owner.epoch >= newest, + None => true, + }); + // The oldest finished jobs of an owner beyond the cap. + let mut finished: HashMap> = HashMap::new(); + for (id, job) in &state.jobs { + if let Some(at) = job.finished_at { + finished + .entry(job.owner.clone()) + .or_default() + .push((at, id.clone())); + } + } + for (_, mut ids) in finished { + if ids.len() > MAX_FINISHED_PER_OWNER { + ids.sort(); + for (_, id) in &ids[..ids.len() - MAX_FINISHED_PER_OWNER] { + state.jobs.remove(id); + } + } + } + state.keys.retain(|(owner, _), key| { + now.duration_since(key.at) < KEY_RETENTION && owner.epoch >= newest + }); + } + + /// The job an earlier request with the same idempotency key started, if any: `Ok(None)` when + /// the key is new, and the same refusals as [`submit`](Self::submit) for a key used for + /// another request or whose job is no longer kept. Lets a caller answer a retry before it + /// spends anything (an intent, a dialog) on the request. + pub fn replay( + &self, + owner: &JobOwner, + key: &str, + hash: [u8; 32], + ) -> Result, Status> { + let mut state = self.lock(); + self.prune(&mut state, owner.epoch); + let Some(seen) = state.keys.get(&(owner.clone(), key.to_owned())) else { + return Ok(None); + }; + if seen.hash != hash { + return Err(Status::failed_precondition( + "the idempotency key was already used for a different request", + )); + } + match state.jobs.get(&seen.job_id) { + Some(job) => Ok(Some(job.reply(&seen.job_id))), + None => Err(Status::failed_precondition( + "the job of this idempotency key finished and is no longer kept; \ + use a new key to start it again", + )), + } + } + + /// Starts `work` as a job of `owner`, or answers with the job an earlier request with the + /// same idempotency key already started (`true`: it is a replay and nothing was started). + /// + /// Must be called inside the Tokio runtime. + pub fn submit( + &self, + owner: &JobOwner, + submission: Submission, + work: Work, + ) -> Result<(JobReply, bool), Status> { + let Submission { + permission, + key, + hash, + fence, + profile, + awaiting, + } = submission; + let id = new_id()?; + let (cancel, cancel_rx) = watch::channel(false); + let (reply, context) = { + let mut state = self.lock(); + self.prune(&mut state, owner.epoch); + if owner.epoch < state.newest_epoch { + return Err(Status::failed_precondition("resource context is stale")); + } + if let Some(seen) = state.keys.get(&(owner.clone(), key.clone())) { + if seen.hash != hash { + return Err(Status::failed_precondition( + "the idempotency key was already used for a different request", + )); + } + return match state.jobs.get(&seen.job_id) { + Some(job) => Ok((job.reply(&seen.job_id), true)), + None => Err(Status::failed_precondition( + "the job of this idempotency key finished and is no longer kept; \ + use a new key to start it again", + )), + }; + } + let active = |job: &&Job| !job.is_terminal(); + if state.jobs.values().filter(active).count() >= MAX_ACTIVE_TOTAL { + return Err(Status::resource_exhausted( + "the host is running as many plugin jobs as it allows; try again later", + )); + } + if state + .jobs + .values() + .filter(active) + .filter(|job| job.owner == *owner) + .count() + >= MAX_ACTIVE_PER_OWNER + { + return Err(Status::resource_exhausted( + "too many jobs are running for this plugin; wait for one to finish", + )); + } + // The oldest key goes when the owner has too many. + let own: Vec<_> = state + .keys + .iter() + .filter(|((o, _), _)| o == owner) + .map(|(id, seen)| (seen.at, id.clone())) + .collect(); + if own.len() >= MAX_KEYS_PER_OWNER + && let Some((_, oldest)) = own.into_iter().min_by_key(|(at, _)| *at) + { + state.keys.remove(&oldest); + } + let (changed, _) = watch::channel(0); + let now = (self.clock)(); + let mut job = Job { + owner: owner.clone(), + permission, + state: JobState::Queued, + code: String::new(), + message: awaiting + .map(|text| clip(text, MAX_MESSAGE_BYTES)) + .unwrap_or_default(), + progress: 0, + events: Vec::new(), + cancel, + changed, + finished_at: None, + }; + job.record(); + let reply = job.reply(&id); + state.jobs.insert(id.clone(), job); + state.keys.insert( + (owner.clone(), key), + Key { + hash, + job_id: id.clone(), + at: now, + }, + ); + ( + reply, + JobContext { + id: id.clone(), + jobs: self.clone(), + cancel: cancel_rx, + fence, + }, + ) + }; + tokio::spawn( + self.clone() + .run(id, owner.epoch, profile, work, context, awaiting.is_some()), + ); + Ok((reply, false)) + } + + async fn run( + self, + id: String, + epoch: u64, + mut profile: watch::Receiver>, + work: Work, + context: JobContext, + awaits_start: bool, + ) { + // A profile that already changed while the job was being set up ends it before it starts. + if profile.borrow().as_ref().map(ProfileContext::epoch) != Some(epoch) { + self.cancel_job(&id); + } + // A job that waits for the user is started by its own work, once the user has decided. + if !awaits_start && !self.begin(&id) { + return; + } + // The work runs in its own task so that a panic ends the job instead of leaving it + // running for good. + let mut handle = tokio::spawn(work(context)); + let mut watching = true; + let outcome = loop { + tokio::select! { + joined = &mut handle => { + break joined.unwrap_or_else(|_| { + Outcome::failed(CODE_INTERNAL, "the job stopped unexpectedly") + }); + } + changed = profile.changed(), if watching => { + if changed.is_err() { + watching = false; + } else if profile.borrow().as_ref().map(ProfileContext::epoch) != Some(epoch) { + // The profile is over: the work is told to stop and its outcome is + // recorded for nobody, since no one in the new profile can see it. + self.cancel_job(&id); + watching = false; + } + } + } + }; + self.finish(&id, outcome); + } + + /// Queued → running, unless the job was cancelled before it started (then it ends here). + fn begin(&self, id: &str) -> bool { + let mut state = self.lock(); + let Some(job) = state.jobs.get_mut(id) else { + return false; + }; + if *job.cancel.borrow() { + drop(state); + self.finish(id, Outcome::cancelled("cancelled before it started")); + return false; + } + if job.state == JobState::Queued { + job.state = JobState::Running; + job.message.clear(); + job.record(); + } + true + } + + fn progress(&self, id: &str, percent: u32) { + let mut state = self.lock(); + if let Some(job) = state.jobs.get_mut(id) + && !job.is_terminal() + && percent > job.progress + { + job.progress = percent; + job.record(); + } + } + + fn finish(&self, id: &str, outcome: Outcome) { + let mut state = self.lock(); + let Some(job) = state.jobs.get_mut(id) else { + return; + }; + if job.is_terminal() { + return; + } + let (state_now, code, message) = match outcome { + Outcome::Succeeded { code, message } => (JobState::Succeeded, code, message), + Outcome::Failed { code, message } => (JobState::Failed, code, message), + Outcome::Cancelled { message } => (JobState::Cancelled, String::new(), message), + }; + job.state = state_now; + job.code = clip(&code, MAX_CODE_BYTES); + job.message = clip(&message, MAX_MESSAGE_BYTES); + if state_now == JobState::Succeeded { + job.progress = 100; + } + job.finished_at = Some((self.clock)()); + job.record(); + } + + /// Asks the work to stop (the job ends when the work does). + fn cancel_job(&self, id: &str) { + if let Some(job) = self.lock().jobs.get(id) { + job.cancel.send_replace(true); + } + } + + // ---- What a plugin's calls use. Every one takes the caller's own owner. ---- + + fn with( + &self, + owner: &JobOwner, + id: &str, + read: impl FnOnce(&Job) -> T, + ) -> Result { + let mut state = self.lock(); + self.prune(&mut state, owner.epoch); + state + .jobs + .get(id) + .filter(|job| job.owner == *owner) + .map(read) + .ok_or_else(not_found) + } + + /// The permission of the operation that created the job. + pub fn permission(&self, owner: &JobOwner, id: &str) -> Result<&'static str, Status> { + self.with(owner, id, |job| job.permission) + } + + pub fn get(&self, owner: &JobOwner, id: &str) -> Result { + self.with(owner, id, |job| job.reply(id)) + } + + /// The events after `after_sequence`, whether the job is over, and a receiver that signals + /// each new event. A position beyond the newest event is `OUT_OF_RANGE`. + pub fn events_after( + &self, + owner: &JobOwner, + id: &str, + after_sequence: u64, + ) -> Result<(Vec, bool, watch::Receiver), Status> { + self.with(owner, id, |job| { + if after_sequence > job.sequence() { + return Err(Status::out_of_range("watch position is in the future")); + } + let events = job.events[after_sequence as usize..] + .iter() + .map(|event| JobEvent { + job_id: id.to_owned(), + ..event.clone() + }) + .collect(); + Ok((events, job.is_terminal(), job.changed.subscribe())) + })? + } + + /// Waits up to `limit` for the job to end and answers with how it stands: its outcome if it + /// ended, its state then if it did not. + pub async fn wait_over( + &self, + owner: &JobOwner, + id: &str, + limit: Duration, + ) -> Result { + let mut changed = self.with(owner, id, |job| job.changed.subscribe())?; + let wait = async { + loop { + let reply = self.get(owner, id)?; + if is_over(reply.state()) { + return Ok(reply); + } + if changed.changed().await.is_err() { + return self.get(owner, id); + } + } + }; + match tokio::time::timeout(limit, wait).await { + Ok(reply) => reply, + Err(_) => self.get(owner, id), + } + } + + /// Asks the job to stop and waits a short while for it to. Cancelling a finished job answers + /// with how it finished, unchanged. A job whose work ignores the request keeps running and + /// the reply says so (`Running`); the work decides, because stopping it halfway could leave + /// an effect half done. + pub async fn cancel(&self, owner: &JobOwner, id: &str) -> Result { + let mut changed = self.with(owner, id, |job| { + if !job.is_terminal() { + job.cancel.send_replace(true); + } + job.changed.subscribe() + })?; + let wait = async { + loop { + match self.get(owner, id) { + Ok(reply) if is_over(reply.state()) => { + return Ok(reply); + } + Ok(_) => {} + Err(status) => return Err(status), + } + if changed.changed().await.is_err() { + return self.get(owner, id); + } + } + }; + match tokio::time::timeout(self.cancel_grace, wait).await { + Ok(reply) => reply, + Err(_) => self.get(owner, id), + } + } + + /// Jobs not yet over, across every owner. + #[cfg(test)] + pub(crate) fn active(&self) -> usize { + self.lock() + .jobs + .values() + .filter(|job| !job.is_terminal()) + .count() + } +} + +fn is_over(state: JobState) -> bool { + matches!( + state, + JobState::Succeeded | JobState::Failed | JobState::Cancelled + ) +} + +#[cfg(test)] +mod tests; diff --git a/crates/app/src/plugin_host/jobs/tests.rs b/crates/app/src/plugin_host/jobs/tests.rs new file mode 100644 index 000000000..70e2e8ec4 --- /dev/null +++ b/crates/app/src/plugin_host/jobs/tests.rs @@ -0,0 +1,690 @@ +//! The job registry on its own (task 7.1): ownership, retries, cancellation, limits, retention +//! and profile changes, without a plugin session. The RPCs are tested over the real socket in +//! `resources/tests/jobs.rs`. + +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex}; + +use super::*; +use crate::plugin_host::profile::PluginProfiles; + +const PERMISSION: &str = "fixture.permission"; + +struct Env { + profiles: Arc, + jobs: Jobs, + now: Arc>, +} + +impl Env { + fn new() -> Self { + let profiles = Arc::new(PluginProfiles::default()); + profiles.update(Some("a"), true); + let now = Arc::new(Mutex::new(Instant::now())); + let jobs = Jobs::default() + .with_cancel_grace(Duration::from_millis(100)) + .with_clock({ + let now = now.clone(); + move || *now.lock().unwrap() + }); + Self { + profiles, + jobs, + now, + } + } + + fn owner(&self, key: u8) -> JobOwner { + JobOwner::for_tests(key, self.profiles.epoch()) + } + + fn advance(&self, by: Duration) { + *self.now.lock().unwrap() += by; + } + + fn submission(&self, key: &str, hash: u8) -> Submission { + Submission { + permission: PERMISSION, + key: key.to_owned(), + hash: [hash; 32], + fence: Arc::new(|| Ok(())), + profile: self.profiles.subscribe(), + awaiting: None, + } + } + + fn start(&self, owner: &JobOwner, key: &str, run: Work) -> JobReply { + self.jobs + .submit(owner, self.submission(key, 1), run) + .unwrap() + .0 + } + + /// Waits until the work has started. + async fn running(&self, owner: &JobOwner, id: &str) { + for _ in 0..400 { + if self.jobs.get(owner, id).unwrap().state() != JobState::Queued { + return; + } + tokio::time::sleep(Duration::from_millis(5)).await; + } + panic!("the job did not start"); + } + + /// Waits until the job is over. + async fn over(&self, owner: &JobOwner, id: &str) -> JobReply { + for _ in 0..400 { + let reply = self.jobs.get(owner, id).unwrap(); + if is_over(reply.state()) { + return reply; + } + tokio::time::sleep(Duration::from_millis(5)).await; + } + panic!("the job did not finish"); + } +} + +/// Work that finishes when told to, keeping the job running until then. +fn held() -> (Work, tokio::sync::oneshot::Sender<()>) { + let (release, wait) = tokio::sync::oneshot::channel::<()>(); + ( + work(move |_| async move { + let _ = wait.await; + Outcome::succeeded("released", "") + }), + release, + ) +} + +fn quick() -> Work { + work(|_| async { Outcome::succeeded("ok", "done") }) +} + +#[tokio::test] +async fn a_job_runs_to_its_outcome_and_reports_ordered_events() { + let env = Env::new(); + let owner = env.owner(1); + let reply = env.start( + &owner, + "k", + work(|ctx| async move { + ctx.progress(30); + ctx.progress(20); // backwards: ignored + ctx.progress(30); // not forward: ignored + ctx.progress(60); + Outcome::succeeded("installed", "3 files") + }), + ); + assert!(reply.job_id.starts_with("job-")); + assert_eq!(reply.state(), JobState::Queued); + + let done = env.over(&owner, &reply.job_id).await; + assert_eq!( + ( + done.state(), + done.result_code.as_str(), + done.message.as_str() + ), + (JobState::Succeeded, "installed", "3 files") + ); + let (events, over, _) = env.jobs.events_after(&owner, &reply.job_id, 0).unwrap(); + assert!(over); + let seen: Vec<_> = events + .iter() + .map(|e| (e.sequence, e.state(), e.progress_percent)) + .collect(); + assert_eq!( + seen, + [ + (1, JobState::Queued, 0), + (2, JobState::Running, 0), + (3, JobState::Running, 30), + (4, JobState::Running, 60), + (5, JobState::Succeeded, 100), + ] + ); + assert!(events.iter().all(|e| e.job_id == reply.job_id)); + assert_eq!(done.revision, 5, "the reply's revision is its newest event"); + + // Resuming after an event gives only what followed; the end of the list is not an error. + let (rest, _, _) = env.jobs.events_after(&owner, &reply.job_id, 3).unwrap(); + assert_eq!(rest.iter().map(|e| e.sequence).collect::>(), [4, 5]); + assert!( + env.jobs + .events_after(&owner, &reply.job_id, 5) + .unwrap() + .0 + .is_empty() + ); + assert_eq!( + env.jobs + .events_after(&owner, &reply.job_id, 6) + .unwrap_err() + .code(), + tonic::Code::OutOfRange + ); +} + +#[tokio::test] +async fn a_retry_with_the_same_key_starts_no_new_work() { + let env = Env::new(); + let owner = env.owner(1); + let runs = Arc::new(AtomicUsize::new(0)); + let counted = |runs: &Arc| { + let runs = runs.clone(); + work(move |_| async move { + runs.fetch_add(1, Ordering::SeqCst); + Outcome::succeeded("ok", "") + }) + }; + + let first = env + .jobs + .submit(&owner, env.submission("same", 7), counted(&runs)) + .unwrap(); + let again = env + .jobs + .submit(&owner, env.submission("same", 7), counted(&runs)) + .unwrap(); + assert!(!first.1 && again.1, "the retry is a replay"); + assert_eq!(first.0.job_id, again.0.job_id); + env.over(&owner, &first.0.job_id).await; + // After it finished too: still the same job, still one run. + let late = env + .jobs + .submit(&owner, env.submission("same", 7), counted(&runs)) + .unwrap(); + assert!(late.1); + assert_eq!(late.0.state(), JobState::Succeeded); + assert_eq!(runs.load(Ordering::SeqCst), 1); + + // The key for a different request is refused; another key is another job. + let other = env + .jobs + .submit(&owner, env.submission("same", 8), counted(&runs)); + assert_eq!(other.unwrap_err().code(), tonic::Code::FailedPrecondition); + let fresh = env + .jobs + .submit(&owner, env.submission("other", 7), counted(&runs)) + .unwrap(); + assert_ne!(fresh.0.job_id, first.0.job_id); + env.over(&owner, &fresh.0.job_id).await; + assert_eq!(runs.load(Ordering::SeqCst), 2); + + // Another owner's key space is its own. + let stranger = env.owner(2); + let theirs = env + .jobs + .submit(&stranger, env.submission("same", 9), counted(&runs)) + .unwrap(); + assert!(!theirs.1); + assert_ne!(theirs.0.job_id, first.0.job_id); +} + +#[tokio::test] +async fn nobody_else_sees_or_touches_a_job() { + let env = Env::new(); + let owner = env.owner(1); + let stranger = env.owner(2); + let (run, release) = held(); + let id = env.start(&owner, "k", run).job_id; + env.running(&owner, &id).await; + + // Another owner, or an id nobody has: the same refusal, word for word. + let unknown = env.jobs.get(&owner, "job-nothing").unwrap_err(); + for status in [ + env.jobs.get(&stranger, &id).unwrap_err(), + env.jobs.permission(&stranger, &id).unwrap_err(), + env.jobs.events_after(&stranger, &id, 0).unwrap_err(), + env.jobs.cancel(&stranger, &id).await.unwrap_err(), + ] { + assert_eq!(status.code(), tonic::Code::NotFound); + assert_eq!(status.message(), unknown.message()); + } + // The failed attempts changed nothing: the job was not cancelled. + assert_eq!( + env.jobs.get(&owner, &id).unwrap().state(), + JobState::Running + ); + release.send(()).unwrap(); + assert_eq!(env.over(&owner, &id).await.state(), JobState::Succeeded); +} + +#[tokio::test] +async fn cancelling_stops_cooperating_work_and_is_repeatable() { + let env = Env::new(); + let owner = env.owner(1); + let id = env + .start( + &owner, + "k", + work(|mut ctx| async move { + ctx.cancelled().await; + assert!(ctx.check().is_err(), "a cancelled job commits nothing"); + Outcome::cancelled("stopped by the plugin") + }), + ) + .job_id; + env.running(&owner, &id).await; + + let first = env.jobs.cancel(&owner, &id).await.unwrap(); + assert_eq!(first.state(), JobState::Cancelled); + assert_eq!(first.message, "stopped by the plugin"); + let again = env.jobs.cancel(&owner, &id).await.unwrap(); + assert_eq!( + (again.state(), again.revision), + (JobState::Cancelled, first.revision) + ); +} + +#[tokio::test] +async fn cancelling_a_finished_job_reports_how_it_finished() { + let env = Env::new(); + let owner = env.owner(1); + let id = env.start(&owner, "k", quick()).job_id; + env.over(&owner, &id).await; + let reply = env.jobs.cancel(&owner, &id).await.unwrap(); + assert_eq!(reply.state(), JobState::Succeeded); + assert_eq!(reply.result_code, "ok"); +} + +#[tokio::test] +async fn a_job_cancelled_before_it_starts_never_runs() { + let env = Env::new(); + let owner = env.owner(1); + let runs = Arc::new(AtomicUsize::new(0)); + let id = env + .start(&owner, "k", { + let runs = runs.clone(); + work(move |_| async move { + runs.fetch_add(1, Ordering::SeqCst); + Outcome::succeeded("ok", "") + }) + }) + .job_id; + // The runtime has not run the job yet: cancel first. + let reply = env.jobs.cancel(&owner, &id).await.unwrap(); + assert_eq!(reply.state(), JobState::Cancelled); + assert_eq!(runs.load(Ordering::SeqCst), 0); +} + +#[tokio::test] +async fn work_that_ignores_cancellation_is_reported_as_still_running() { + let env = Env::new(); + let owner = env.owner(1); + let (run, release) = held(); + let id = env.start(&owner, "k", run).job_id; + env.running(&owner, &id).await; + // The reply is honest: the work did not stop within the grace period. + let reply = env.jobs.cancel(&owner, &id).await.unwrap(); + assert_eq!(reply.state(), JobState::Running); + release.send(()).unwrap(); + // It finished its effect, so that is what the job says. + assert_eq!(env.over(&owner, &id).await.state(), JobState::Succeeded); +} + +#[tokio::test] +async fn a_panic_ends_the_job_as_failed() { + let env = Env::new(); + let owner = env.owner(1); + let id = env + .start(&owner, "k", work(|_| async { panic!("the work broke") })) + .job_id; + let reply = env.over(&owner, &id).await; + assert_eq!( + (reply.state(), reply.result_code.as_str()), + (JobState::Failed, CODE_INTERNAL) + ); + assert!(!reply.message.contains("broke"), "no internal detail leaks"); + assert_eq!(env.jobs.active(), 0); +} + +#[tokio::test] +async fn results_are_clipped_and_cleaned() { + let env = Env::new(); + let owner = env.owner(1); + let id = env + .start( + &owner, + "k", + work(|_| async { + Outcome::failed( + &"c".repeat(500), + &format!("line\u{7}one\n{}", "é".repeat(600)), + ) + }), + ) + .job_id; + let reply = env.over(&owner, &id).await; + assert_eq!(reply.result_code.len(), MAX_CODE_BYTES); + assert!(reply.message.len() <= MAX_MESSAGE_BYTES); + assert!(reply.message.starts_with("line one ")); + assert!(!reply.message.chars().any(char::is_control)); +} + +#[tokio::test] +async fn running_jobs_are_bounded_per_owner_and_overall() { + let env = Env::new(); + let owner = env.owner(1); + let mut releases = Vec::new(); + for n in 0..MAX_ACTIVE_PER_OWNER { + let (run, release) = held(); + env.start(&owner, &format!("k{n}"), run); + releases.push(release); + } + let (run, _release) = held(); + let refused = env + .jobs + .submit(&owner, env.submission("one-too-many", 1), run) + .unwrap_err(); + assert_eq!(refused.code(), tonic::Code::ResourceExhausted); + // A retry of a job already running is still answered at the limit. + let replay = env + .jobs + .submit(&owner, env.submission("k0", 1), quick()) + .unwrap(); + assert!(replay.1); + // Another plugin is not held back by this one's jobs. + let (run, release) = held(); + env.start(&env.owner(2), "k", run); + releases.push(release); + + // The host as a whole is bounded too. + let mut owner_key = 3; + while env.jobs.active() < MAX_ACTIVE_TOTAL { + for n in 0..MAX_ACTIVE_PER_OWNER.min(MAX_ACTIVE_TOTAL - env.jobs.active()) { + let (run, release) = held(); + env.start(&env.owner(owner_key), &format!("k{n}"), run); + releases.push(release); + } + owner_key += 1; + } + let (run, _release) = held(); + let refused = env + .jobs + .submit(&env.owner(owner_key), env.submission("late", 1), run) + .unwrap_err(); + assert_eq!(refused.code(), tonic::Code::ResourceExhausted); + + // Finishing one makes room again. + releases.remove(0).send(()).unwrap(); + for _ in 0..200 { + if env.jobs.active() < MAX_ACTIVE_TOTAL { + break; + } + tokio::time::sleep(Duration::from_millis(5)).await; + } + env.jobs + .submit(&owner, env.submission("room", 1), quick()) + .unwrap(); +} + +#[tokio::test] +async fn finished_jobs_are_forgotten_but_their_key_never_runs_the_work_twice() { + let env = Env::new(); + let owner = env.owner(1); + let runs = Arc::new(AtomicUsize::new(0)); + let counted = |runs: &Arc| { + let runs = runs.clone(); + work(move |_| async move { + runs.fetch_add(1, Ordering::SeqCst); + Outcome::succeeded("ok", "") + }) + }; + let id = env + .jobs + .submit(&owner, env.submission("k", 1), counted(&runs)) + .unwrap() + .0 + .job_id; + env.over(&owner, &id).await; + + // An hour later the job is gone, and its id is the same refusal as any unknown id. + env.advance(FINISHED_RETENTION + Duration::from_secs(1)); + assert_eq!( + env.jobs.get(&owner, &id).unwrap_err().code(), + tonic::Code::NotFound + ); + // The retry is refused, not run again. + let retry = env + .jobs + .submit(&owner, env.submission("k", 1), counted(&runs)) + .unwrap_err(); + assert_eq!(retry.code(), tonic::Code::FailedPrecondition); + assert_eq!(runs.load(Ordering::SeqCst), 1); + + // After the key's own 24 hours it is free to use again. + env.advance(KEY_RETENTION); + let again = env + .jobs + .submit(&owner, env.submission("k", 1), counted(&runs)) + .unwrap(); + assert!(!again.1); + env.over(&owner, &again.0.job_id).await; + assert_eq!(runs.load(Ordering::SeqCst), 2); +} + +#[tokio::test] +async fn an_owner_keeps_only_so_many_finished_jobs() { + let env = Env::new(); + let owner = env.owner(1); + let mut ids = Vec::new(); + for n in 0..MAX_FINISHED_PER_OWNER + 3 { + let id = env.start(&owner, &format!("k{n}"), quick()).job_id; + env.over(&owner, &id).await; + env.advance(Duration::from_secs(1)); + ids.push(id); + } + assert_eq!( + env.jobs.get(&owner, &ids[0]).unwrap_err().code(), + tonic::Code::NotFound + ); + assert_eq!( + env.jobs.get(&owner, &ids[2]).unwrap_err().code(), + tonic::Code::NotFound + ); + assert!(env.jobs.get(&owner, &ids[3]).is_ok()); + assert!(env.jobs.get(&owner, ids.last().unwrap()).is_ok()); +} + +#[tokio::test] +async fn a_profile_switch_ends_the_jobs_of_the_old_profile_and_hides_them() { + let env = Env::new(); + let old = env.owner(1); + let ran = Arc::new(AtomicUsize::new(0)); + let id = env + .start(&old, "k", { + let ran = ran.clone(); + work(move |mut ctx| async move { + ctx.cancelled().await; + // A fence that would pass still cannot commit: the job was cancelled. + if ctx.check().is_ok() { + ran.fetch_add(1, Ordering::SeqCst); + } + Outcome::cancelled("profile changed") + }) + }) + .job_id; + tokio::time::sleep(Duration::from_millis(20)).await; + assert_eq!(env.jobs.get(&old, &id).unwrap().state(), JobState::Running); + + env.profiles.update(Some("b"), true); + let new = env.owner(1); // the same plugin, the new profile epoch + assert_ne!(old, new); + // The new profile cannot see it, whatever it asks. + assert_eq!( + env.jobs.get(&new, &id).unwrap_err().code(), + tonic::Code::NotFound + ); + assert_eq!( + env.jobs.events_after(&new, &id, 0).unwrap_err().code(), + tonic::Code::NotFound + ); + // The old job was told to stop and committed nothing. + for _ in 0..400 { + if env.jobs.active() == 0 { + break; + } + tokio::time::sleep(Duration::from_millis(5)).await; + } + assert_eq!(env.jobs.active(), 0); + assert_eq!(ran.load(Ordering::SeqCst), 0); + // Once the new profile asks anything, the old profile's records are gone for good. + let _ = env.jobs.get(&new, "job-x"); + assert_eq!( + env.jobs.get(&old, &id).unwrap_err().code(), + tonic::Code::NotFound + ); + // A request still carrying the old epoch cannot start anything. + let late = env + .jobs + .submit(&old, env.submission("late", 1), quick()) + .unwrap_err(); + assert_eq!(late.code(), tonic::Code::FailedPrecondition); + assert_eq!(env.jobs.active(), 0); +} + +#[tokio::test] +async fn a_profile_that_changed_before_the_job_started_never_starts_it() { + let env = Env::new(); + let old = env.owner(1); + let submission = env.submission("k", 1); + // The profile changes after the caller was authorized and before the job is registered. + env.profiles.update(Some("b"), true); + let runs = Arc::new(AtomicUsize::new(0)); + env.jobs + .submit(&old, submission, { + let runs = runs.clone(); + work(move |_| async move { + runs.fetch_add(1, Ordering::SeqCst); + Outcome::succeeded("ok", "") + }) + }) + .unwrap(); + for _ in 0..400 { + if env.jobs.active() == 0 { + break; + } + tokio::time::sleep(Duration::from_millis(5)).await; + } + assert_eq!(runs.load(Ordering::SeqCst), 0); +} + +#[tokio::test] +async fn stopped_work_reports_why_without_internal_detail() { + assert_eq!( + Outcome::stopped(&Status::cancelled("x")), + Outcome::cancelled("cancelled before anything was committed") + ); + assert!(matches!( + Outcome::stopped(&Status::permission_denied("secret detail")), + Outcome::Failed { code, message } if code == "permission_denied" && !message.contains("secret") + )); + assert!(matches!( + Outcome::stopped(&Status::failed_precondition("secret detail")), + Outcome::Failed { code, .. } if code == "failed_precondition" + )); +} + +#[tokio::test] +async fn a_job_that_waits_for_the_user_stays_queued_until_its_work_starts_it() { + let env = Env::new(); + let owner = env.owner(1); + let (release, wait) = tokio::sync::oneshot::channel::<()>(); + let mut submission = env.submission("k", 1); + submission.awaiting = Some("awaiting confirmation"); + let (reply, _) = env + .jobs + .submit( + &owner, + submission, + work(move |ctx| async move { + let _ = wait.await; + ctx.start().unwrap(); + ctx.progress(40); + Outcome::succeeded("done", "") + }), + ) + .unwrap(); + assert_eq!( + (reply.state(), reply.message.as_str()), + (JobState::Queued, "awaiting confirmation") + ); + // It stays queued, with its message, for as long as the work waits. + tokio::time::sleep(Duration::from_millis(30)).await; + let waiting = env.jobs.get(&owner, &reply.job_id).unwrap(); + assert_eq!( + (waiting.state(), waiting.message.as_str()), + (JobState::Queued, "awaiting confirmation") + ); + + release.send(()).unwrap(); + let done = env.over(&owner, &reply.job_id).await; + assert_eq!(done.state(), JobState::Succeeded); + let (events, _, _) = env.jobs.events_after(&owner, &reply.job_id, 0).unwrap(); + let seen: Vec<_> = events + .iter() + .map(|e| (e.state(), e.message.as_str(), e.progress_percent)) + .collect(); + assert_eq!( + seen, + [ + (JobState::Queued, "awaiting confirmation", 0), + (JobState::Running, "", 0), + (JobState::Running, "", 40), + (JobState::Succeeded, "", 100), + ] + ); +} + +#[tokio::test] +async fn cancelling_a_job_that_waits_for_the_user_withdraws_it() { + let env = Env::new(); + let owner = env.owner(1); + let mut submission = env.submission("k", 1); + submission.awaiting = Some("awaiting confirmation"); + let started = Arc::new(AtomicUsize::new(0)); + let (reply, _) = env + .jobs + .submit( + &owner, + submission, + work({ + let started = started.clone(); + move |mut ctx| async move { + ctx.cancelled().await; + // Cancelled while waiting: it may not start, whatever the user decides next. + if ctx.start().is_ok() { + started.fetch_add(1, Ordering::SeqCst); + } + Outcome::cancelled("withdrawn") + } + }), + ) + .unwrap(); + let cancelled = env.jobs.cancel(&owner, &reply.job_id).await.unwrap(); + assert_eq!(cancelled.state(), JobState::Cancelled); + assert_eq!(started.load(Ordering::SeqCst), 0); +} + +#[tokio::test] +async fn a_retry_can_be_answered_before_anything_is_spent_on_it() { + let env = Env::new(); + let owner = env.owner(1); + assert_eq!(env.jobs.replay(&owner, "k", [1; 32]).unwrap(), None); + let id = env.start(&owner, "k", quick()).job_id; + let replayed = env.jobs.replay(&owner, "k", [1; 32]).unwrap().unwrap(); + assert_eq!(replayed.job_id, id); + assert_eq!( + env.jobs.replay(&owner, "k", [2; 32]).unwrap_err().code(), + tonic::Code::FailedPrecondition + ); + // Another owner's key space is its own. + assert_eq!(env.jobs.replay(&env.owner(2), "k", [1; 32]).unwrap(), None); + env.over(&owner, &id).await; + env.advance(FINISHED_RETENTION + Duration::from_secs(1)); + assert_eq!( + env.jobs.replay(&owner, "k", [1; 32]).unwrap_err().code(), + tonic::Code::FailedPrecondition + ); +} diff --git a/crates/app/src/plugin_host/launch_plan.rs b/crates/app/src/plugin_host/launch_plan.rs new file mode 100644 index 000000000..ce29fac53 --- /dev/null +++ b/crates/app/src/plugin_host/launch_plan.rs @@ -0,0 +1,508 @@ +//! Host-owned resolution of an authenticated request into the plan that user approval covers. + +use crate::plugin_host::library::{CustomLaunchDispatch, Projected}; +use crate::plugin_host::provider::ResourceCaller; +use gamenode_core::library::{ + CustomLaunchRecipe, LaunchPlan, LaunchPlanComponent, LaunchPlanResource, LaunchPlanTarget, +}; +use tonic::Status; + +/// Plain, host-resolved data shown by the shared launch-plan review. Environment values are +/// included for exact review and remain masked in the UI until the user explicitly reveals them. +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct LaunchPlanReview { + pub source_id: String, + pub requester_plugin_id: String, + pub requester_publisher: String, + pub requester_package_version: String, + pub target: String, + pub components: Vec, + pub arguments: Vec, + pub working_directory: String, + pub environment_set: std::collections::BTreeMap, + pub environment_unset: Vec, + pub differences: Vec, + pub fingerprint: String, +} + +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct LaunchPlanReviewComponent { + pub kind: String, + pub id: String, + pub owner_plugin_id: String, + pub owner_publisher: String, + pub version: String, + pub revision: u64, +} + +pub fn review(plan: &LaunchPlan, fingerprint: String) -> LaunchPlanReview { + let target = match &plan.target { + LaunchPlanTarget::Detected { fingerprint } => { + format!("Detected target (revision {fingerprint})") + } + LaunchPlanTarget::Uri { uri, handler } => handler.as_ref().map_or_else( + || uri.clone(), + |handler| format!("{uri} (handler: {handler})"), + ), + LaunchPlanTarget::Executable { + path, + file_identity, + } => format!("{path} (file identity: {file_identity})"), + }; + let mut differences = Vec::new(); + if !plan.recipe_id.is_empty() { + differences.push("recipe-selected".into()); + } + if !matches!(&plan.target, LaunchPlanTarget::Detected { .. }) { + differences.push("custom-target".into()); + } + if !plan.components.is_empty() { + differences.push("known-components".into()); + } + if !plan.arguments.is_empty() { + differences.push("custom-arguments".into()); + } + if !plan.working_directory.is_empty() { + differences.push("custom-working-directory".into()); + } + if !plan.environment.is_empty() { + differences.push("environment-changes".into()); + } + LaunchPlanReview { + source_id: plan.source_id.clone(), + requester_plugin_id: plan.requester_plugin_id.clone(), + requester_publisher: plan.requester_publisher.clone(), + requester_package_version: plan.requester_package_version.clone(), + target, + components: plan + .components + .iter() + .map(|component| LaunchPlanReviewComponent { + kind: component.kind.clone(), + id: component.id.clone(), + owner_plugin_id: component.owner_plugin_id.clone(), + owner_publisher: component.owner_publisher.clone(), + version: component.version.clone(), + revision: component.revision, + }) + .collect(), + arguments: plan.arguments.clone(), + working_directory: plan.working_directory.clone(), + environment_set: plan.environment.set.clone(), + environment_unset: plan.environment.unset.iter().cloned().collect(), + differences, + fingerprint, + } +} + +pub(super) fn resolve( + caller: &ResourceCaller, + entry: &Projected, + target_revision: u64, + recipe: Option<&CustomLaunchRecipe>, + dispatch: Option<&CustomLaunchDispatch>, + resources: &[LaunchPlanResource], +) -> Result { + let identity = caller + .namespace + .as_ref() + .ok_or_else(|| Status::failed_precondition("launch plans require a plugin namespace"))? + .identity(); + let (target, arguments, working_directory, environment) = match dispatch { + None => ( + LaunchPlanTarget::Detected { + fingerprint: target_revision, + }, + Vec::new(), + String::new(), + Default::default(), + ), + Some(CustomLaunchDispatch::Uri { + uri, + arguments, + working_directory, + environment, + }) => ( + LaunchPlanTarget::Uri { + uri: uri.as_str().to_owned(), + handler: None, + }, + arguments.clone(), + working_directory.clone(), + environment.clone(), + ), + Some(CustomLaunchDispatch::Executable(command)) => ( + LaunchPlanTarget::Executable { + path: command.executable.clone(), + file_identity: command.file_identity.clone(), + }, + command.arguments.clone(), + command.working_directory.clone(), + command.environment.clone(), + ), + Some(CustomLaunchDispatch::Detected { command }) => ( + LaunchPlanTarget::Detected { + fingerprint: target_revision, + }, + command.arguments.clone(), + command.working_directory.clone(), + command.environment.clone(), + ), + Some(CustomLaunchDispatch::Runtime { + command, + runtime_id, + runtime_version, + runtime_revision, + content_id, + binding_revision, + .. + }) => { + let mut components = vec![LaunchPlanComponent { + kind: "runtime".into(), + id: runtime_id.clone(), + owner_plugin_id: identity.plugin_id.clone(), + owner_publisher: identity.publisher_fingerprint.clone(), + version: runtime_version.clone(), + revision: *runtime_revision, + }]; + if !content_id.is_empty() { + components.push(LaunchPlanComponent { + kind: "content".into(), + id: content_id.clone(), + owner_plugin_id: identity.plugin_id.clone(), + owner_publisher: identity.publisher_fingerprint.clone(), + version: String::new(), + revision: binding_revision.unwrap_or_default(), + }); + } + let mut resources = resources.to_vec(); + resources.push(LaunchPlanResource { + id: format!("runtime:{runtime_id}"), + revision: *runtime_revision, + }); + if let Some(revision) = binding_revision { + resources.push(LaunchPlanResource { + id: format!("content-binding:{content_id}"), + revision: *revision, + }); + } + components.extend(mod_layer_components(identity, recipe)); + return make( + caller, + identity, + entry, + target_revision, + recipe, + LaunchPlanTarget::Executable { + path: command.executable.clone(), + file_identity: command.file_identity.clone(), + }, + command.arguments.clone(), + command.working_directory.clone(), + command.environment.clone(), + components, + resources, + ); + } + }; + let components = mod_layer_components(identity, recipe); + make( + caller, + identity, + entry, + target_revision, + recipe, + target, + arguments, + working_directory, + environment, + components, + resources.to_vec(), + ) +} + +fn mod_layer_components( + identity: &crate::plugin_host::grants::PluginIdentity, + recipe: Option<&CustomLaunchRecipe>, +) -> Vec { + recipe + .map(|recipe| { + recipe + .mod_layers + .iter() + .map(|layer| LaunchPlanComponent { + kind: "mod-layer".into(), + id: layer.id.clone(), + owner_plugin_id: identity.plugin_id.clone(), + owner_publisher: identity.publisher_fingerprint.clone(), + version: layer.version.clone(), + revision: layer.revision, + }) + .collect() + }) + .unwrap_or_default() +} + +#[allow(clippy::too_many_arguments)] +fn make( + caller: &ResourceCaller, + identity: &crate::plugin_host::grants::PluginIdentity, + entry: &Projected, + target_revision: u64, + recipe: Option<&CustomLaunchRecipe>, + target: LaunchPlanTarget, + arguments: Vec, + working_directory: String, + environment: gamenode_core::drm_free::LaunchEnvironmentDelta, + components: Vec, + mut resources: Vec, +) -> Result { + if let Some(recipe) = recipe { + resources.push(LaunchPlanResource { + id: format!("recipe:{}", recipe.recipe_id), + revision: recipe.revision, + }); + if recipe.base_target_revision > 0 { + resources.push(LaunchPlanResource { + id: format!("base-target:{}", entry.provider_id), + revision: recipe.base_target_revision, + }); + } + } + let plan = LaunchPlan { + version: gamenode_core::library::LAUNCH_PLAN_VERSION, + game_id: entry.game_id.map(|id| id.to_string()).unwrap_or_default(), + installation_id: entry.installation_id.clone(), + profile_id: identity.profile_id.clone(), + source_id: entry.provider_id.clone(), + requester_plugin_id: identity.plugin_id.clone(), + requester_publisher: identity.publisher_fingerprint.clone(), + requester_package_version: caller.package_version.clone(), + target_revision, + recipe_id: recipe + .map(|recipe| recipe.recipe_id.clone()) + .unwrap_or_default(), + recipe_revision: recipe.map(|recipe| recipe.revision).unwrap_or_default(), + grant_revision: caller.grant_revision, + target, + components, + resources, + arguments, + working_directory, + environment, + }; + if !plan.validate() { + return Err(Status::failed_precondition("the launch plan is invalid")); + } + Ok(plan) +} + +#[cfg(test)] +mod review_tests { + use super::*; + use gamenode_core::drm_free::LaunchEnvironmentDelta; + + #[test] + fn executable_wrapper_plan_keeps_original_game_installation_and_source() { + use crate::plugin_host::{ + grants::PluginIdentity, + library::{CustomLaunchDispatch, InstallState}, + namespace::ExternalNamespaceResolver, + }; + + let identity = PluginIdentity { + plugin_id: "org.example.wrapper".into(), + publisher_fingerprint: "ab".repeat(32), + profile_id: "account-1".into(), + }; + let namespace = ExternalNamespaceResolver::new(identity, None, 1).unwrap(); + let caller = ResourceCaller { + session_id: "session".into(), + provider_id: String::new(), + declared_developer: String::new(), + origin: String::new(), + package_digest: vec![], + package_version: "1.0.0".into(), + grants: Default::default(), + grant_revision: 1, + profile_epoch: 1, + namespace: Some(namespace), + }; + let entry = Projected { + installation_id: "manual:original-installation".into(), + provider_id: "official-store".into(), + game_id: Some(42), + name: "Original game".into(), + install_state: InstallState::Installed, + display_name: None, + metadata_revision: 0, + artwork_revision: 0, + revision: 7, + }; + let dispatch = + CustomLaunchDispatch::Executable(gamenode_core::drm_free::CustomLaunchCommand { + executable: "/approved/proton".into(), + file_identity: "linux:1:2:3:4:5:6:7:8".into(), + arguments: vec!["run".into(), "Z:/Games/original.exe".into()], + working_directory: "/approved/prefix".into(), + environment: LaunchEnvironmentDelta { + set: [("PROTON_LOG".into(), "1".into())].into(), + unset: Default::default(), + }, + }); + + let plan = resolve(&caller, &entry, 9, None, Some(&dispatch), &[]).unwrap(); + assert_eq!(plan.game_id, "42"); + assert_eq!(plan.installation_id, "manual:original-installation"); + assert_eq!(plan.source_id, "official-store"); + assert_eq!(plan.arguments, ["run", "Z:/Games/original.exe"]); + assert_eq!(plan.working_directory, "/approved/prefix"); + assert_eq!(plan.environment.set["PROTON_LOG"], "1"); + } + + #[test] + fn a_runtime_recipe_without_a_detected_target_omits_the_base_target_resource() { + use crate::plugin_host::{ + grants::PluginIdentity, library::InstallState, namespace::ExternalNamespaceResolver, + }; + + let identity = PluginIdentity { + plugin_id: "org.example.launcher".into(), + publisher_fingerprint: "ab".repeat(32), + profile_id: "account-1".into(), + }; + let namespace = ExternalNamespaceResolver::new(identity.clone(), None, 1).unwrap(); + let caller = ResourceCaller { + session_id: "session".into(), + provider_id: String::new(), + declared_developer: String::new(), + origin: String::new(), + package_digest: vec![], + package_version: "1.0.0".into(), + grants: Default::default(), + grant_revision: 1, + profile_epoch: 1, + namespace: Some(namespace), + }; + let entry = Projected { + installation_id: "manual:install".into(), + provider_id: "rom-store".into(), + game_id: Some(42), + name: "Pikmin".into(), + install_state: InstallState::Installed, + display_name: None, + metadata_revision: 0, + artwork_revision: 0, + revision: 7, + }; + let recipe = gamenode_core::library::CustomLaunchRecipe { + recipe_id: "recipe-1".into(), + revision: 1, + game_id: 42, + installation_id: "manual:install".into(), + base_target_revision: 0, + base_launch_fingerprint: 9, + runtime_handle: "runtime-1".into(), + content_id: "content-1".into(), + ..Default::default() + }; + let plan = make( + &caller, + &identity, + &entry, + 0, + Some(&recipe), + LaunchPlanTarget::Detected { fingerprint: 0 }, + Vec::new(), + String::new(), + LaunchEnvironmentDelta::default(), + Vec::new(), + Vec::new(), + ) + .unwrap(); + + assert!( + plan.resources + .iter() + .all(|resource| !resource.id.starts_with("base-target")) + ); + assert!( + plan.resources + .iter() + .any(|resource| resource.id == "recipe:recipe-1") + ); + assert_eq!(plan.target_revision, 0); + } + + #[test] + fn review_preserves_provenance_component_order_literals_and_environment_changes() { + let plan = LaunchPlan { + version: gamenode_core::library::LAUNCH_PLAN_VERSION, + game_id: "620".into(), + installation_id: "install-1".into(), + profile_id: "profile-1".into(), + source_id: "steam".into(), + requester_plugin_id: "org.example.launcher".into(), + requester_publisher: "ab".repeat(32), + requester_package_version: "2.1.0".into(), + target_revision: 4, + recipe_id: "recipe-1".into(), + recipe_revision: 3, + grant_revision: 7, + target: LaunchPlanTarget::Executable { + path: "C:\\Games\\Portal 2\\Portal2.exe".into(), + file_identity: "volume:file-id".into(), + }, + components: vec![ + LaunchPlanComponent { + kind: "runtime".into(), + id: "proton".into(), + owner_plugin_id: "org.example.runtime".into(), + owner_publisher: "cd".repeat(32), + version: "9.0".into(), + revision: 2, + }, + LaunchPlanComponent { + kind: "mod-layer".into(), + id: "compat-layer".into(), + owner_plugin_id: "org.example.mods".into(), + owner_publisher: "ef".repeat(32), + version: "1.4".into(), + revision: 5, + }, + ], + resources: vec![], + arguments: vec!["--profile".into(), "a profile & literal".into()], + working_directory: "C:\\Games\\Portal 2".into(), + environment: LaunchEnvironmentDelta { + set: [("GAME_MODE".into(), "custom".into())].into(), + unset: ["OLD_MODE".into()].into(), + }, + }; + let fingerprint = format!("v1:{}", "aa".repeat(32)); + let review = review(&plan, fingerprint.clone()); + assert_eq!(review.source_id, "steam"); + assert_eq!(review.requester_package_version, "2.1.0"); + assert_eq!(review.arguments, plan.arguments); + assert_eq!(review.working_directory, plan.working_directory); + assert_eq!(review.environment_set["GAME_MODE"], "custom"); + assert_eq!(review.environment_unset, ["OLD_MODE"]); + assert_eq!( + review + .components + .iter() + .map(|part| part.id.as_str()) + .collect::>(), + ["proton", "compat-layer"] + ); + assert_eq!(review.fingerprint, fingerprint); + assert!( + review + .differences + .iter() + .any(|line| line == "custom-target") + ); + } +} diff --git a/crates/app/src/plugin_host/launch_supervisor.rs b/crates/app/src/plugin_host/launch_supervisor.rs new file mode 100644 index 000000000..e33204e01 --- /dev/null +++ b/crates/app/src/plugin_host/launch_supervisor.rs @@ -0,0 +1,356 @@ +//! Host-owned lifetime management for reviewed custom launches. +//! +//! The platform tree is responsible for providing a fenced identity that cannot be confused +//! with a reused PID. An inspection failure is never interpreted as process exit. + +use super::resource_leases::{ + ResourceLease, ResourceLeaseCoordinator, ResourceLeaseError, ResourceLeaseKey, +}; +use std::collections::BTreeMap; +use std::sync::{Arc, Mutex}; + +#[cfg(target_os = "linux")] +mod linux_helper; +#[cfg(windows)] +mod windows; + +#[cfg(target_os = "linux")] +pub(crate) fn spawn_native(command: &gamenode_core::drm_free::CustomLaunchCommand) -> SpawnOutcome { + linux_helper::spawn(command) +} + +/// Handles the private helper mode before the desktop, IPC, or a Tokio runtime is initialized. +#[cfg(target_os = "linux")] +pub fn run_linux_helper_if_requested() -> Option>> { + (std::env::args_os().nth(1).as_deref() == Some(std::ffi::OsStr::new(linux_helper::HELPER_ARG))) + .then(linux_helper::run) +} + +#[cfg(windows)] +pub(crate) fn spawn_native(command: &gamenode_core::drm_free::CustomLaunchCommand) -> SpawnOutcome { + windows::spawn(command) +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum TreeState { + Running, + Exited, + Unknown, +} + +pub(crate) trait LaunchTree: Send { + fn state(&mut self) -> TreeState; + /// Terminate and fence the entire tree; success requires a later confirmed `Exited` state. + fn terminate(&mut self) -> Result<(), ()>; +} + +/// A platform may return `NotStarted` only when it can prove no process was created. If a +/// process might have started, it must return its tree even when its state is indeterminate. +pub(crate) enum SpawnOutcome { + Started(Box), + /// The spawn request may have reached the operating system but could not be confirmed. + /// Keep the tree and its lease; report the failed confirmation to the caller. + Uncertain(Box), + NotStarted, +} + +struct Launch { + tree: Box, + entry_key: Option, + // Retained through every indeterminate state and released only after confirmed exit. + _lease: Option>, +} + +#[derive(Default)] +pub(crate) struct LaunchSupervisor { + launches: Mutex>, + next_id: std::sync::atomic::AtomicU64, +} + +impl LaunchSupervisor { + /// Creates a supervisor whose monitor runs on a dedicated worker thread. Inspection failures + /// keep launches registered and their leases held; no UI or async executor thread waits. + pub(crate) fn start_monitor() -> std::io::Result> { + let supervisor = Arc::new(Self::default()); + let weak = Arc::downgrade(&supervisor); + std::thread::Builder::new() + .name("custom-launch-supervisor".into()) + .spawn(move || { + loop { + std::thread::sleep(std::time::Duration::from_secs(1)); + let Some(supervisor) = weak.upgrade() else { + break; + }; + let _ = supervisor.refresh_all(); + } + })?; + Ok(supervisor) + } + /// Acquires the complete lease set before invoking the platform spawn operation. + #[cfg(test)] + pub(crate) fn start( + &self, + coordinator: &dyn ResourceLeaseCoordinator, + keys: &[ResourceLeaseKey], + spawn: impl FnOnce() -> SpawnOutcome, + ) -> Result { + self.start_for_entry(coordinator, keys, None, spawn) + } + + pub(crate) fn start_for_entry( + &self, + coordinator: &dyn ResourceLeaseCoordinator, + keys: &[ResourceLeaseKey], + entry_key: Option, + spawn: impl FnOnce() -> SpawnOutcome, + ) -> Result { + let mut launches = self + .launches + .lock() + .map_err(|_| ResourceLeaseError::Unknown)?; + if launches.len() >= 256 { + return Err(ResourceLeaseError::Busy); + } + let id = self + .next_id + .try_update( + std::sync::atomic::Ordering::Relaxed, + std::sync::atomic::Ordering::Relaxed, + |n| n.checked_add(1), + ) + .map_err(|_| ResourceLeaseError::Unknown)? + + 1; + let lease = if keys.is_empty() { + None + } else { + Some(coordinator.acquire_use(keys)?) + }; + let (tree, confirmed) = match spawn() { + SpawnOutcome::Started(tree) => (tree, true), + SpawnOutcome::Uncertain(tree) => (tree, false), + SpawnOutcome::NotStarted => return Err(ResourceLeaseError::Unknown), + }; + launches.insert( + id, + Launch { + tree, + entry_key, + _lease: lease, + }, + ); + if confirmed { + Ok(id) + } else { + Err(ResourceLeaseError::Unknown) + } + } + + #[cfg(test)] + pub(crate) fn refresh(&self, id: u64) -> Result { + let mut launches = self + .launches + .lock() + .map_err(|_| ResourceLeaseError::Unknown)?; + let launch = launches.get_mut(&id).ok_or(ResourceLeaseError::Unknown)?; + let state = launch.tree.state(); + if state == TreeState::Exited { + launches.remove(&id); + } + Ok(state) + } + + pub(crate) fn stop(&self, id: u64) -> Result { + let mut launches = self + .launches + .lock() + .map_err(|_| ResourceLeaseError::Unknown)?; + let launch = launches.get_mut(&id).ok_or(ResourceLeaseError::Unknown)?; + launch + .tree + .terminate() + .map_err(|_| ResourceLeaseError::Unknown)?; + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); + loop { + match launch.tree.state() { + TreeState::Exited => { + launches.remove(&id); + return Ok(TreeState::Exited); + } + TreeState::Unknown => return Err(ResourceLeaseError::Unknown), + TreeState::Running if std::time::Instant::now() >= deadline => { + return Err(ResourceLeaseError::Unknown); + } + TreeState::Running => std::thread::sleep(std::time::Duration::from_millis(25)), + } + } + } + + /// Inspects launches off the UI thread and releases leases only for confirmed exits. + pub(crate) fn refresh_all(&self) -> Result<(), ResourceLeaseError> { + let mut launches = self + .launches + .lock() + .map_err(|_| ResourceLeaseError::Unknown)?; + launches.retain(|_, launch| launch.tree.state() != TreeState::Exited); + Ok(()) + } + + /// Returns opaque identities for active or indeterminate launches. + pub(crate) fn active_ids(&self) -> Result, ResourceLeaseError> { + let launches = self + .launches + .lock() + .map_err(|_| ResourceLeaseError::Unknown)?; + Ok(launches.keys().copied().collect()) + } + + pub(crate) fn ids_for_entry(&self, entry_key: &str) -> Result, ResourceLeaseError> { + let launches = self + .launches + .lock() + .map_err(|_| ResourceLeaseError::Unknown)?; + Ok(launches + .iter() + .filter_map(|(id, launch)| { + (launch.entry_key.as_deref() == Some(entry_key)).then_some(*id) + }) + .collect()) + } +} + +impl Drop for LaunchSupervisor { + fn drop(&mut self) { + // The owner disappearing is not evidence that its launches exited. Preserve leases for + // the life of the coordinator rather than reporting a potentially active resource idle. + let launches = self + .launches + .get_mut() + .unwrap_or_else(std::sync::PoisonError::into_inner); + for (_, launch) in std::mem::take(launches) { + std::mem::forget(launch); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::plugin_host::grants::PluginIdentity; + use crate::plugin_host::resource_leases::ResourceLeases; + use std::sync::atomic::{AtomicU8, Ordering}; + + struct Fixture(Arc); + impl LaunchTree for Fixture { + fn state(&mut self) -> TreeState { + match self.0.load(Ordering::SeqCst) { + 0 => TreeState::Running, + 1 => TreeState::Exited, + _ => TreeState::Unknown, + } + } + fn terminate(&mut self) -> Result<(), ()> { + self.0.store(1, Ordering::SeqCst); + Ok(()) + } + } + fn key() -> ResourceLeaseKey { + ResourceLeaseKey::derive( + &PluginIdentity { + plugin_id: "example".into(), + publisher_fingerprint: "publisher".into(), + profile_id: "profile".into(), + }, + 1, + "save", + 1, + b"handle", + ) + .unwrap() + } + #[test] + fn lease_is_acquired_before_spawn_and_held_until_confirmed_exit() { + let leases = ResourceLeases::default(); + let supervisor = LaunchSupervisor::default(); + let state = Arc::new(AtomicU8::new(0)); + let id = supervisor + .start(&leases, &[key()], || { + assert!(matches!( + leases.acquire_exclusive(&[key()]), + Err(ResourceLeaseError::Busy) + )); + SpawnOutcome::Started(Box::new(Fixture(state.clone()))) + }) + .unwrap(); + state.store(2, Ordering::SeqCst); + assert_eq!(supervisor.refresh(id).unwrap(), TreeState::Unknown); + assert!(matches!( + leases.acquire_exclusive(&[key()]), + Err(ResourceLeaseError::Busy) + )); + state.store(1, Ordering::SeqCst); + assert_eq!(supervisor.refresh(id).unwrap(), TreeState::Exited); + assert!(leases.acquire_exclusive(&[key()]).is_ok()); + } + #[test] + fn exclusive_lease_blocks_spawn_and_stop_fences_before_release() { + let leases = ResourceLeases::default(); + let supervisor = LaunchSupervisor::default(); + let exclusive = leases.acquire_exclusive(&[key()]).unwrap(); + assert!(matches!( + supervisor.start(&leases, &[key()], || panic!("spawn must not run")), + Err(ResourceLeaseError::Busy) + )); + drop(exclusive); + let id = supervisor + .start(&leases, &[key()], || { + SpawnOutcome::Started(Box::new(Fixture(Arc::new(AtomicU8::new(0))))) + }) + .unwrap(); + assert_eq!(supervisor.stop(id).unwrap(), TreeState::Exited); + assert!(leases.acquire_exclusive(&[key()]).is_ok()); + } + + #[test] + fn failed_spawn_releases_the_reservation() { + let leases = ResourceLeases::default(); + let supervisor = LaunchSupervisor::default(); + assert!(matches!( + supervisor.start(&leases, &[key()], || SpawnOutcome::NotStarted), + Err(ResourceLeaseError::Unknown) + )); + assert!(leases.acquire_exclusive(&[key()]).is_ok()); + } + + #[test] + fn uncertain_spawn_reports_failure_but_keeps_reservation() { + let leases = ResourceLeases::default(); + let supervisor = LaunchSupervisor::default(); + assert!(matches!( + supervisor.start(&leases, &[key()], || { + SpawnOutcome::Uncertain(Box::new(Fixture(Arc::new(AtomicU8::new(2))))) + }), + Err(ResourceLeaseError::Unknown) + )); + assert!(matches!( + leases.acquire_exclusive(&[key()]), + Err(ResourceLeaseError::Busy) + )); + } + + #[test] + fn dropping_supervisor_does_not_claim_live_tree_has_exited() { + let leases = ResourceLeases::default(); + { + let supervisor = LaunchSupervisor::default(); + supervisor + .start(&leases, &[key()], || { + SpawnOutcome::Started(Box::new(Fixture(Arc::new(AtomicU8::new(0))))) + }) + .unwrap(); + } + assert!(matches!( + leases.acquire_exclusive(&[key()]), + Err(ResourceLeaseError::Busy) + )); + } +} diff --git a/crates/app/src/plugin_host/launch_supervisor/linux_helper.rs b/crates/app/src/plugin_host/launch_supervisor/linux_helper.rs new file mode 100644 index 000000000..eb23cc831 --- /dev/null +++ b/crates/app/src/plugin_host/launch_supervisor/linux_helper.rs @@ -0,0 +1,592 @@ +//! Linux launch helper: a dedicated subreaper owns the complete descendant tree. +//! +//! The helper exits successfully only after `wait` reports that no children remain. If it loses +//! contact with the app, it continues supervising rather than terminating an already running game. + +use super::{LaunchTree, SpawnOutcome, TreeState}; +use gamenode_core::drm_free::{CustomLaunchCommand, InstallationHost, LaunchEnvironmentDelta}; +use serde::{Deserialize, Serialize}; +use std::collections::{BTreeMap, BTreeSet}; +use std::io::{BufRead, BufReader, Read, Write}; +use std::os::unix::net::UnixStream; +use std::process::{Child, Command, Stdio}; +use std::sync::mpsc; +use std::time::Duration; + +pub(crate) const HELPER_ARG: &str = "--gamenode-internal-launch-supervisor"; +const MAX_REQUEST: usize = 128 * 1024; + +#[derive(Serialize, Deserialize)] +struct Request { + executable: String, + file_identity: String, + arguments: Vec, + working_directory: String, + set: BTreeMap, + unset: BTreeSet, +} + +struct HelperTree { + child: Child, + input: Option, + exit: Option, +} + +impl LaunchTree for HelperTree { + fn state(&mut self) -> TreeState { + let result = match self.exit { + Some(status) => Some(status), + None => match self.child.try_wait() { + Ok(result) => { + self.exit = result; + result + } + Err(_) => return TreeState::Unknown, + }, + }; + match result { + None => TreeState::Running, + Some(status) if status.success() => TreeState::Exited, + Some(_) => TreeState::Unknown, + } + } + fn terminate(&mut self) -> Result<(), ()> { + if self.state() == TreeState::Exited { + return Ok(()); + } + let input = self.input.as_mut().ok_or(())?; + let result = input + .write_all(b"STOP\n") + .and_then(|()| input.flush()) + .map_err(|_| ()); + if result.is_err() && self.state() == TreeState::Exited { + Ok(()) + } else { + result + } + } +} + +/// The OS process handle fences the helper identity against PID reuse. +pub(super) fn spawn(command: &CustomLaunchCommand) -> SpawnOutcome { + #[cfg(test)] + if let Some(executable) = std::env::var_os("GAMENODE_TEST_HELPER_BINARY") { + return spawn_with_executable(command, std::path::Path::new(&executable)); + } + // Resolve the running image rather than its install pathname: an update may replace or + // unlink that pathname while this desktop is still running. + spawn_with_executable(command, std::path::Path::new("/proc/self/exe")) +} + +fn spawn_with_executable( + command: &CustomLaunchCommand, + executable: &std::path::Path, +) -> SpawnOutcome { + if command.executable.is_empty() + || command.working_directory.is_empty() + || !command.environment.validate() + || command.executable.contains('\0') + || command.working_directory.contains('\0') + || command.arguments.iter().any(|arg| arg.contains('\0')) + { + return SpawnOutcome::NotStarted; + } + let request = Request { + executable: command.executable.clone(), + file_identity: command.file_identity.clone(), + arguments: command.arguments.clone(), + working_directory: command.working_directory.clone(), + set: command.environment.set.clone(), + unset: command.environment.unset.clone(), + }; + let Ok(mut request) = serde_json::to_vec(&request) else { + return SpawnOutcome::NotStarted; + }; + if request.len() >= MAX_REQUEST { + return SpawnOutcome::NotStarted; + } + request.push(b'\n'); + let Ok((input, helper_input)) = UnixStream::pair() else { + return SpawnOutcome::NotStarted; + }; + if input + .set_write_timeout(Some(Duration::from_secs(5))) + .is_err() + { + return SpawnOutcome::NotStarted; + } + let helper_input: std::os::fd::OwnedFd = helper_input.into(); + let Ok(mut child) = Command::new(executable) + .arg(HELPER_ARG) + .stdin(Stdio::from(helper_input)) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .spawn() + else { + return SpawnOutcome::NotStarted; + }; + let output = child.stdout.take(); + let mut tree = HelperTree { + child, + input: Some(input), + exit: None, + }; + let Some(output) = output else { + return SpawnOutcome::Uncertain(Box::new(tree)); + }; + let Some(input) = tree.input.as_mut() else { + return SpawnOutcome::Uncertain(Box::new(tree)); + }; + let written = input + .write_all(&request) + .and_then(|()| input.flush()) + .is_ok(); + if !written { + return SpawnOutcome::Uncertain(Box::new(tree)); + } + let (tx, rx) = mpsc::sync_channel(1); + if std::thread::Builder::new() + .name("custom-launch-ready".into()) + .spawn(move || { + let mut line = String::new(); + let result = BufReader::new(output) + .take(64) + .read_line(&mut line) + .map(|_| line); + let _ = tx.send(result); + }) + .is_err() + { + return SpawnOutcome::Uncertain(Box::new(tree)); + } + match rx.recv_timeout(Duration::from_secs(5)) { + Ok(Ok(line)) if line == "READY\n" => SpawnOutcome::Started(Box::new(tree)), + // A negative acknowledgement is sent only before the target is created. + Ok(Ok(line)) if line == "NOT_STARTED\n" => { + let _ = std::thread::Builder::new() + .name("custom-launch-reap".into()) + .spawn(move || { + let _ = tree.child.wait(); + }); + SpawnOutcome::NotStarted + } + _ => SpawnOutcome::Uncertain(Box::new(tree)), + } +} + +fn safe_key(key: &std::ffi::OsStr) -> bool { + let key = key.to_string_lossy(); + matches!( + key.as_ref(), + "PATH" + | "HOME" + | "USER" + | "LOGNAME" + | "LANG" + | "DISPLAY" + | "WAYLAND_DISPLAY" + | "XAUTHORITY" + | "DBUS_SESSION_BUS_ADDRESS" + ) || key.starts_with("QT_") + || key.starts_with("LC_") + || key.starts_with("XDG_") +} + +/// Called before application initialization when the internal helper argument is present. +pub(super) fn run() -> Result<(), Box> { + let mut input = BufReader::new(std::io::stdin()); + let mut line = String::new(); + let count = input + .by_ref() + .take((MAX_REQUEST + 1) as u64) + .read_line(&mut line)?; + if count == 0 || count > MAX_REQUEST || !line.ends_with('\n') { + println!("NOT_STARTED"); + return Err("invalid launch request".into()); + } + let request: Request = match serde_json::from_str(&line) { + Ok(value) => value, + Err(_) => { + println!("NOT_STARTED"); + return Err("invalid launch request".into()); + } + }; + let environment = LaunchEnvironmentDelta { + set: request.set, + unset: request.unset, + }; + let preparation = (|| -> Result<_, Box> { + if !environment.validate() { + return Err("invalid environment".into()); + } + // PR_SET_CHILD_SUBREAPER accepts a boolean; rustix represents nonzero as a Pid. + rustix::process::set_child_subreaper(rustix::process::Pid::from_raw(1))?; + // Fencing stop requests requires pidfd support. Check it before creating the game. + let _ = rustix::process::pidfd_open( + rustix::process::getpid(), + rustix::process::PidfdFlags::empty(), + )?; + let inspected = + gamenode_platform::installations::LinuxInstallations.inspect(&request.executable)?; + if inspected.file_identity != request.file_identity { + return Err("executable identity changed".into()); + } + let working = std::fs::canonicalize(&request.working_directory)?; + if !working.is_dir() { + return Err("invalid working directory".into()); + } + let mut target = Command::new(inspected.executable); + target + .args(&request.arguments) + .current_dir(working) + .env_clear(); + for (key, value) in std::env::vars_os().filter(|(key, _)| safe_key(key)) { + target.env(key, value); + } + target.envs(&environment.set); + for key in &environment.unset { + target.env_remove(key); + } + target + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()); + Ok(target.spawn()?) + })(); + // Keep the root Child handle for the helper lifetime; `wait` below also reaps adopted + // descendants after a wrapper exits or a descendant changes its process group. + let _root = match preparation { + Ok(child) => child, + Err(error) => { + println!("NOT_STARTED"); + return Err(error); + } + }; + let _ = writeln!(std::io::stdout(), "READY"); + // Once a target exists, losing the acknowledgement must not abandon its descendants. + let _ = std::io::stdout().flush(); + let (tx, rx) = mpsc::channel(); + let _ = std::thread::Builder::new() + .name("custom-launch-control".into()) + .spawn(move || { + let mut message = String::new(); + while input.read_line(&mut message).is_ok_and(|n| n > 0) { + if message == "STOP\n" { + let _ = tx.send(()); + } + message.clear(); + } + }); + let mut stopping = false; + loop { + stopping |= rx.try_recv().is_ok(); + loop { + match rustix::process::wait(rustix::process::WaitOptions::NOHANG) { + Ok(Some(_)) => continue, + Ok(None) => break, + Err(rustix::io::Errno::CHILD) => return Ok(()), + Err(rustix::io::Errno::INTR) => continue, + Err(error) => return Err(Box::new(error)), + } + } + if stopping { + signal_direct_children(); + } + std::thread::sleep(Duration::from_millis(25)); + } +} + +/// Signals only current direct children using pidfds. Repeating this after reaping parents catches +/// newly adopted descendants, including children that changed sessions or process groups. +fn signal_direct_children() { + let pid = rustix::process::getpid().as_raw_nonzero().get(); + let Ok(children) = std::fs::read_to_string(format!("/proc/self/task/{pid}/children")) else { + return; + }; + for value in children.split_whitespace() { + let Some(child) = value + .parse::() + .ok() + .and_then(rustix::process::Pid::from_raw) + else { + continue; + }; + let Ok(fd) = rustix::process::pidfd_open(child, rustix::process::PidfdFlags::empty()) + else { + continue; + }; + // A PID can be recycled between reading children and opening its pidfd. Confirm the + // current parent after opening; the pidfd itself then fences against subsequent reuse. + let Ok(status) = std::fs::read_to_string(format!("/proc/{value}/status")) else { + continue; + }; + let parent = status.lines().find_map(|line| { + line.strip_prefix("PPid:") + .and_then(|v| v.trim().parse::().ok()) + }); + if parent == Some(pid) { + let _ = rustix::process::pidfd_send_signal(&fd, rustix::process::Signal::KILL); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::plugin_host::grants::PluginIdentity; + use crate::plugin_host::launch_supervisor::LaunchSupervisor; + use crate::plugin_host::resource_leases::{ + ResourceLeaseCoordinator, ResourceLeaseError, ResourceLeaseKey, ResourceLeases, + }; + use std::time::Instant; + + fn helper() -> Option { + std::env::var_os("GAMENODE_TEST_HELPER_BINARY").map(Into::into) + } + #[test] + fn the_helper_preserves_the_desktop_session_environment() { + for key in [ + "DISPLAY", + "WAYLAND_DISPLAY", + "XAUTHORITY", + "QT_QPA_PLATFORM", + "XDG_RUNTIME_DIR", + "DBUS_SESSION_BUS_ADDRESS", + ] { + assert!(safe_key(std::ffi::OsStr::new(key)), "{key}"); + } + assert!(!safe_key(std::ffi::OsStr::new("STEAM_SESSION"))); + assert!(!safe_key(std::ffi::OsStr::new("TAURI_PLUGIN_TOKEN"))); + } + + fn shell(script: &str) -> CustomLaunchCommand { + let registration = gamenode_platform::installations::LinuxInstallations + .inspect("/bin/sh") + .unwrap(); + CustomLaunchCommand { + executable: registration.executable, + file_identity: registration.file_identity, + arguments: vec!["-c".into(), script.into()], + working_directory: "/".into(), + environment: Default::default(), + } + } + fn started(command: &CustomLaunchCommand, executable: &std::path::Path) -> Box { + match spawn_with_executable(command, executable) { + SpawnOutcome::Started(tree) => tree, + _ => panic!("helper did not start a verified launch"), + } + } + fn wait_exit(tree: &mut dyn LaunchTree) { + let deadline = Instant::now() + Duration::from_secs(10); + loop { + match tree.state() { + TreeState::Exited => return, + TreeState::Unknown => panic!("helper state became unknown"), + TreeState::Running => {} + } + assert!(Instant::now() < deadline, "helper did not finish"); + std::thread::sleep(Duration::from_millis(25)); + } + } + #[test] + fn detached_descendant_is_reaped_after_wrapper_exit() { + let Some(helper) = helper() else { + return; + }; + let command = shell("/usr/bin/setsid /bin/sh -c 'sleep 1' &"); + let mut tree = started(&command, &helper); + assert_eq!(tree.state(), TreeState::Running); + wait_exit(tree.as_mut()); + } + #[test] + fn explicit_stop_fences_detached_descendants() { + let Some(helper) = helper() else { + return; + }; + let dir = tempfile::tempdir().unwrap(); + let pidfile = dir.path().join("pid"); + let mut command = shell( + "/usr/bin/setsid /bin/sh -c 'echo $$ > \"$1\"; exec sleep 30' fixture \"$1\" & wait", + ); + command + .arguments + .extend(["fixture".into(), pidfile.to_string_lossy().into_owned()]); + let mut tree = started(&command, &helper); + assert_eq!(tree.state(), TreeState::Running); + let deadline = Instant::now() + Duration::from_secs(5); + while !pidfile.exists() { + assert!(Instant::now() < deadline, "detached child did not start"); + std::thread::sleep(Duration::from_millis(10)); + } + let pid = std::fs::read_to_string(pidfile) + .unwrap() + .trim() + .parse::() + .unwrap(); + let pidfd = rustix::process::pidfd_open( + rustix::process::Pid::from_raw(pid).unwrap(), + rustix::process::PidfdFlags::empty(), + ) + .unwrap(); + tree.terminate().unwrap(); + wait_exit(tree.as_mut()); + assert_eq!( + rustix::process::pidfd_send_signal(&pidfd, rustix::process::Signal::CONT), + Err(rustix::io::Errno::SRCH) + ); + } + #[test] + fn changed_executable_identity_is_rejected_before_spawn() { + let Some(helper) = helper() else { + return; + }; + let mut command = shell("exit 0"); + command.file_identity.push_str("-changed"); + assert!(matches!( + spawn_with_executable(&command, &helper), + SpawnOutcome::NotStarted + )); + } + + #[test] + fn command_keeps_reviewed_working_directory_environment_and_arguments() { + let Some(helper) = helper() else { + return; + }; + let dir = tempfile::tempdir().unwrap(); + let working = dir.path().join("game folder %i"); + std::fs::create_dir(&working).unwrap(); + let output = dir.path().join("result"); + let mut command = shell("printf '%s:%s:%s' \"$PWD\" \"$GAMENODE_FIXTURE\" \"$1\" > \"$2\""); + command.working_directory = working.to_string_lossy().into_owned(); + command + .environment + .set + .insert("GAMENODE_FIXTURE".into(), "reviewed value".into()); + command.arguments.extend([ + "fixture".into(), + "argument with spaces".into(), + output.to_string_lossy().into_owned(), + ]); + let mut tree = started(&command, &helper); + wait_exit(tree.as_mut()); + assert_eq!( + std::fs::read_to_string(output).unwrap(), + format!("{}:reviewed value:argument with spaces", working.display()) + ); + } + + #[test] + fn proton_style_wrapper_keeps_reviewed_plan_and_tracks_its_child() { + use std::os::unix::fs::PermissionsExt; + let Some(helper) = helper() else { + return; + }; + let dir = tempfile::tempdir().unwrap(); + let working = dir.path().join("prefix with spaces"); + std::fs::create_dir(&working).unwrap(); + let wrapper = dir.path().join("proton wrapper"); + std::fs::write(&wrapper, "#!/bin/sh\nprintf '%s\\n' \"$PWD\" \"$@\" \"$PLAN_MARKER\" > \"$CAPTURE\"\n/usr/bin/setsid /bin/sh -c 'sleep 1' &\n").unwrap(); + std::fs::set_permissions(&wrapper, std::fs::Permissions::from_mode(0o755)).unwrap(); + let registration = gamenode_platform::installations::LinuxInstallations + .inspect(wrapper.to_str().unwrap()) + .unwrap(); + let output = dir.path().join("wrapper.out"); + let mut environment = LaunchEnvironmentDelta::default(); + environment + .set + .insert("CAPTURE".into(), output.to_string_lossy().into_owned()); + environment + .set + .insert("PLAN_MARKER".into(), "reviewed".into()); + let command = CustomLaunchCommand { + executable: registration.executable, + file_identity: registration.file_identity, + arguments: vec![ + "run".into(), + "--prefix".into(), + "/prefix with spaces".into(), + "--".into(), + "Z:/Games/Example/game.exe".into(), + "argument with spaces".into(), + ], + working_directory: working.to_string_lossy().into_owned(), + environment, + }; + let mut tree = started(&command, &helper); + let deadline = Instant::now() + Duration::from_secs(5); + while !output.exists() { + assert!(Instant::now() < deadline); + std::thread::sleep(Duration::from_millis(10)); + } + assert_eq!( + std::fs::read_to_string(output).unwrap(), + format!( + "{}\nrun\n--prefix\n/prefix with spaces\n--\nZ:/Games/Example/game.exe\nargument with spaces\nreviewed\n", + working.display() + ) + ); + assert_eq!(tree.state(), TreeState::Running); + wait_exit(tree.as_mut()); + } + + #[test] + fn monitor_keeps_lease_until_detached_descendant_exits() { + let Some(helper) = helper() else { + return; + }; + let key = ResourceLeaseKey::derive( + &PluginIdentity { + plugin_id: "fixture".into(), + publisher_fingerprint: "fixture".into(), + profile_id: "fixture".into(), + }, + 1, + "save", + 1, + b"backing", + ) + .unwrap(); + let leases = ResourceLeases::default(); + let supervisor = LaunchSupervisor::start_monitor().unwrap(); + let command = shell("/usr/bin/setsid /bin/sh -c 'sleep 1' &"); + supervisor + .start(&leases, &[key], || spawn_with_executable(&command, &helper)) + .unwrap(); + assert!(matches!( + leases.acquire_exclusive(&[key]), + Err(ResourceLeaseError::Busy) + )); + let deadline = Instant::now() + Duration::from_secs(10); + while leases.acquire_exclusive(&[key]).is_err() { + assert!( + Instant::now() < deadline, + "monitor did not release the finished tree" + ); + std::thread::sleep(Duration::from_millis(100)); + } + } + + #[test] + fn unexpected_helper_exit_keeps_tree_state_unknown() { + let (input, peer) = UnixStream::pair().unwrap(); + let peer: std::os::fd::OwnedFd = peer.into(); + let child = Command::new("/bin/sh") + .args(["-c", "exit 9"]) + .stdin(Stdio::from(peer)) + .spawn() + .unwrap(); + let mut tree = HelperTree { + child, + input: Some(input), + exit: None, + }; + let deadline = Instant::now() + Duration::from_secs(5); + while tree.state() == TreeState::Running { + assert!(Instant::now() < deadline); + std::thread::sleep(Duration::from_millis(10)); + } + assert_eq!(tree.state(), TreeState::Unknown); + } +} diff --git a/crates/app/src/plugin_host/launch_supervisor/windows.rs b/crates/app/src/plugin_host/launch_supervisor/windows.rs new file mode 100644 index 000000000..a27e09eab --- /dev/null +++ b/crates/app/src/plugin_host/launch_supervisor/windows.rs @@ -0,0 +1,321 @@ +//! Windows custom launches, created suspended and assigned to a Job Object before execution. + +use super::{LaunchTree, SpawnOutcome, TreeState}; +use gamenode_core::drm_free::CustomLaunchCommand; +use std::collections::BTreeMap; +use std::os::windows::ffi::OsStrExt; +use windows_sys::Win32::Foundation::{CloseHandle, HANDLE}; +use windows_sys::Win32::System::JobObjects::{ + AssignProcessToJobObject, CreateJobObjectW, JOBOBJECT_BASIC_ACCOUNTING_INFORMATION, + JobObjectBasicAccountingInformation, QueryInformationJobObject, TerminateJobObject, +}; +use windows_sys::Win32::System::Threading::{ + CREATE_SUSPENDED, CREATE_UNICODE_ENVIRONMENT, CreateProcessW, PROCESS_INFORMATION, + ResumeThread, STARTUPINFOW, TerminateProcess, +}; + +struct WindowsTree { + job: isize, + process: isize, + assigned: bool, +} + +impl LaunchTree for WindowsTree { + fn state(&mut self) -> TreeState { + if !self.assigned { + // An unassigned suspended process can only be released after termination is confirmed. + use windows_sys::Win32::Foundation::{WAIT_OBJECT_0, WAIT_TIMEOUT}; + use windows_sys::Win32::System::Threading::WaitForSingleObject; + return match unsafe { WaitForSingleObject(self.process as HANDLE, 0) } { + WAIT_OBJECT_0 => TreeState::Exited, + WAIT_TIMEOUT => TreeState::Running, + _ => TreeState::Unknown, + }; + } + let mut info = JOBOBJECT_BASIC_ACCOUNTING_INFORMATION::default(); + let ok = unsafe { + QueryInformationJobObject( + self.job as HANDLE, + JobObjectBasicAccountingInformation, + &mut info as *mut _ as *mut _, + std::mem::size_of_val(&info) as u32, + std::ptr::null_mut(), + ) + }; + if ok == 0 { + TreeState::Unknown + } else if info.ActiveProcesses == 0 { + TreeState::Exited + } else { + TreeState::Running + } + } + fn terminate(&mut self) -> Result<(), ()> { + let ok = unsafe { + if self.assigned { + TerminateJobObject(self.job as HANDLE, 1) + } else { + TerminateProcess(self.process as HANDLE, 1) + } + }; + if ok == 0 { Err(()) } else { Ok(()) } + } +} +impl Drop for WindowsTree { + fn drop(&mut self) { + unsafe { + CloseHandle(self.process as HANDLE); + CloseHandle(self.job as HANDLE); + } + } +} + +fn wide(text: &std::ffi::OsStr) -> Option> { + let mut result: Vec = text.encode_wide().collect(); + if result.contains(&0) { + return None; + } + result.push(0); + Some(result) +} + +/// Follows the Windows CRT argument rules, including trailing backslashes before a quote. +fn quote_argument(arg: &str) -> String { + let mut out = String::from("\""); + let mut slashes = 0; + for c in arg.chars() { + match c { + '\\' => slashes += 1, + '"' => { + out.extend(std::iter::repeat_n('\\', slashes * 2 + 1)); + out.push('"'); + slashes = 0; + } + _ => { + out.extend(std::iter::repeat_n('\\', slashes)); + slashes = 0; + out.push(c); + } + } + } + out.extend(std::iter::repeat_n('\\', slashes * 2)); + out.push('"'); + out +} + +fn environment(command: &CustomLaunchCommand) -> Option> { + let mut values: BTreeMap = BTreeMap::new(); + for (key, value) in std::env::vars_os() { + let upper = key.to_string_lossy().to_ascii_uppercase(); + if matches!( + upper.as_str(), + "PATH" + | "PATHEXT" + | "SYSTEMROOT" + | "WINDIR" + | "TEMP" + | "TMP" + | "USERPROFILE" + | "HOMEDRIVE" + | "HOMEPATH" + | "APPDATA" + | "LOCALAPPDATA" + | "PROGRAMDATA" + | "COMSPEC" + | "NUMBER_OF_PROCESSORS" + | "PROCESSOR_ARCHITECTURE" + | "PROCESSOR_IDENTIFIER" + | "PROCESSOR_LEVEL" + | "PROCESSOR_REVISION" + ) { + values.insert(upper, (key, value)); + } + } + for key in &command.environment.unset { + values.remove(&key.to_ascii_uppercase()); + } + for (key, value) in &command.environment.set { + values.insert(key.to_ascii_uppercase(), (key.into(), value.into())); + } + let mut block = Vec::new(); + for (_, (key, value)) in values { + let mut pair = key; + pair.push("="); + pair.push(value); + block.extend(wide(&pair)?); + } + block.push(0); + if block.len() == 1 { + block.push(0); + } + Some(block) +} + +/// The caller rechecks the approved file identity and directory before invoking this function. +pub(super) fn spawn(command: &CustomLaunchCommand) -> SpawnOutcome { + if command.executable.is_empty() + || command.working_directory.is_empty() + || !command.environment.validate() + || command.arguments.iter().any(|s| s.contains('\0')) + { + return SpawnOutcome::NotStarted; + } + let Some(executable) = wide(std::ffi::OsStr::new(&command.executable)) else { + return SpawnOutcome::NotStarted; + }; + let Some(directory) = wide(std::ffi::OsStr::new(&command.working_directory)) else { + return SpawnOutcome::NotStarted; + }; + let Some(mut environment) = environment(command) else { + return SpawnOutcome::NotStarted; + }; + let commandline = std::iter::once(command.executable.as_str()) + .chain(command.arguments.iter().map(String::as_str)) + .map(quote_argument) + .collect::>() + .join(" "); + let Some(mut commandline) = wide(std::ffi::OsStr::new(&commandline)) else { + return SpawnOutcome::NotStarted; + }; + let job = unsafe { CreateJobObjectW(std::ptr::null(), std::ptr::null()) }; + if job.is_null() { + return SpawnOutcome::NotStarted; + } + let mut startup = STARTUPINFOW::default(); + startup.cb = std::mem::size_of_val(&startup) as u32; + let mut process = PROCESS_INFORMATION::default(); + let created = unsafe { + CreateProcessW( + executable.as_ptr(), + commandline.as_mut_ptr(), + std::ptr::null(), + std::ptr::null(), + 0, + CREATE_SUSPENDED | CREATE_UNICODE_ENVIRONMENT, + environment.as_mut_ptr() as *const _, + directory.as_ptr(), + &startup, + &mut process, + ) + }; + if created == 0 { + unsafe { + CloseHandle(job); + } + return SpawnOutcome::NotStarted; + } + let assigned = unsafe { AssignProcessToJobObject(job, process.hProcess) } != 0; + let tree = WindowsTree { + job: job as isize, + process: process.hProcess as isize, + assigned, + }; + if !assigned { + // The new process is still suspended. Do not release the lease unless its death can be + // confirmed; the retained process handle also avoids PID-reuse confusion. + unsafe { + TerminateProcess(process.hProcess, 1); + CloseHandle(process.hThread); + } + return SpawnOutcome::Uncertain(Box::new(tree)); + } + let resumed = unsafe { ResumeThread(process.hThread) }; + unsafe { + CloseHandle(process.hThread); + } + if resumed == u32::MAX { + SpawnOutcome::Uncertain(Box::new(tree)) + } else { + SpawnOutcome::Started(Box::new(tree)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::time::{Duration, Instant}; + #[test] + fn windows_arguments_quote_backslashes_and_quotes() { + assert_eq!(quote_argument(""), "\"\""); + assert_eq!(quote_argument("a b"), "\"a b\""); + assert_eq!(quote_argument("a\\\"b\\"), "\"a\\\\\\\"b\\\\\""); + } + + /// Executed by the test harness as a separate process inside the supervised job. + #[test] + fn windows_tree_fixture_process() { + match std::env::var("GAMENODE_WINDOWS_TREE_FIXTURE").as_deref() { + Ok("root") => { + let child = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "plugin_host::launch_supervisor::windows::tests::windows_tree_fixture_process", "--nocapture"]) + .env("GAMENODE_WINDOWS_TREE_FIXTURE", "child") + .spawn().unwrap(); + std::fs::write( + std::env::var_os("GAMENODE_WINDOWS_PIDFILE").unwrap(), + child.id().to_string(), + ) + .unwrap(); + } + Ok("child") => std::thread::sleep(Duration::from_secs(30)), + _ => {} + } + } + + #[test] + fn job_tracks_child_after_wrapper_exit_and_fences_explicit_stop() { + use windows_sys::Win32::Foundation::WAIT_OBJECT_0; + use windows_sys::Win32::System::Threading::{ + OpenProcess, PROCESS_SYNCHRONIZE, WaitForSingleObject, + }; + let dir = tempfile::tempdir().unwrap(); + let pidfile = dir.path().join("child.pid"); + let executable = std::env::current_exe().unwrap(); + let mut environment = gamenode_core::drm_free::LaunchEnvironmentDelta::default(); + environment + .set + .insert("GAMENODE_WINDOWS_TREE_FIXTURE".into(), "root".into()); + environment.set.insert( + "GAMENODE_WINDOWS_PIDFILE".into(), + pidfile.to_string_lossy().into_owned(), + ); + let command = CustomLaunchCommand { + executable: executable.to_string_lossy().into_owned(), + file_identity: String::new(), + arguments: vec![ + "--exact".into(), + "plugin_host::launch_supervisor::windows::tests::windows_tree_fixture_process" + .into(), + "--nocapture".into(), + ], + working_directory: dir.path().to_string_lossy().into_owned(), + environment, + }; + let mut tree = match spawn(&command) { + SpawnOutcome::Started(tree) => tree, + _ => panic!("job did not start"), + }; + let deadline = Instant::now() + Duration::from_secs(10); + while !pidfile.exists() { + assert!(Instant::now() < deadline); + std::thread::sleep(Duration::from_millis(10)); + } + let pid = std::fs::read_to_string(pidfile) + .unwrap() + .parse::() + .unwrap(); + let child = unsafe { OpenProcess(PROCESS_SYNCHRONIZE, 0, pid) }; + assert!(!child.is_null()); + // The wrapper has returned, but the descendant remains in the same job. + std::thread::sleep(Duration::from_millis(100)); + assert_eq!(tree.state(), TreeState::Running); + tree.terminate().unwrap(); + while tree.state() != TreeState::Exited { + assert!(Instant::now() < deadline); + std::thread::sleep(Duration::from_millis(10)); + } + assert_eq!(unsafe { WaitForSingleObject(child, 0) }, WAIT_OBJECT_0); + unsafe { + CloseHandle(child); + } + } +} diff --git a/crates/app/src/plugin_host/library.rs b/crates/app/src/plugin_host/library.rs new file mode 100644 index 000000000..d1e394576 --- /dev/null +++ b/crates/app/src/plugin_host/library.rs @@ -0,0 +1,1129 @@ +//! Host-owned projection of the game library for plugin reads (`Library.List/Get/Watch`). +//! +//! The engine feeds every library change as plain [`LibrarySource`] rows. A row becomes visible +//! to plugins only once its opaque installation id is durable (assigned by the library store), +//! so an id a plugin has seen never changes for its entry. The projection carries descriptive +//! fields only: never the store id, install folder, scan fields or anything account-private. +//! +//! Revisions are global and monotonic. Each change batch advances the revision once; its events +//! carry that revision. A bounded history lets watchers resume; older positions must resync. + +use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque}; +use std::sync::{Arc, Mutex, MutexGuard}; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use gamenode_core::library::{ArtworkWrite, DisplayWrite}; +use gamenode_platform::plugin_artwork::Prepared; +use gamenode_plugin_protocol::proto::LibraryEntry; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use tokio::sync::broadcast; +use tonic::Status; + +/// The most entries one page may return. +pub const MAX_PAGE_SIZE: usize = 200; +/// The page size used when a request leaves it unset. +pub const DEFAULT_PAGE_SIZE: usize = 50; +/// How many recent events a watcher can resume from. +pub const HISTORY_EVENTS: usize = 256; +/// How long a list cursor stays valid. +pub const CURSOR_TTL: Duration = Duration::from_secs(5 * 60); +/// Longest accepted search text, in bytes. +pub const MAX_SEARCH_BYTES: usize = 256; +/// Longest accepted cursor, in bytes. +const MAX_CURSOR_BYTES: usize = 2048; +/// After a failed id request, syncs wait this long before asking again. +const ID_RETRY: Duration = Duration::from_secs(30); + +/// Whether the entry is installed on this PC, or only owned or shared with the account. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum InstallState { + Installed, + Owned, + Shared, +} + +impl InstallState { + pub fn as_str(self) -> &'static str { + match self { + Self::Installed => "installed", + Self::Owned => "owned", + Self::Shared => "shared", + } + } +} + +/// One visible library entry as the engine sees it, before it has an installation id. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct LibrarySource { + pub entry_key: String, + pub provider_id: String, + /// The current GameNode match, if exactly one game is matched. + pub game_id: Option, + pub name: String, + pub install_state: InstallState, + /// The provider plugin's presentation override, if one is set. + pub display_name: Option, + /// Revision of that override for this entry; 0 until it is first written. + pub metadata_revision: u64, + /// Revision of the provider plugin's cover override for this entry; 0 until it is first + /// written. + pub artwork_revision: u64, + /// Where the entry is installed, or empty when unknown. Host-only: it is never part of the + /// projection a plugin reads; it lets file approvals find the games that share a folder. + pub install_dir: String, + /// Host-only revision and availability of the detected launch target. + pub detected_target: Option<(u64, bool, bool)>, +} + +/// One entry's install folder, for file approvals. Host-only. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct EntryFolder { + pub entry_key: String, + pub game_id: Option, + pub name: String, + pub folder: String, +} + +/// One entry as plugins see it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Projected { + pub installation_id: String, + pub provider_id: String, + pub game_id: Option, + pub name: String, + pub install_state: InstallState, + pub display_name: Option, + pub metadata_revision: u64, + pub artwork_revision: u64, + /// The revision of the entry's last change. + pub revision: u64, +} + +impl Projected { + pub fn to_proto(&self) -> LibraryEntry { + LibraryEntry { + game_id: self.game_id.map(|id| id.to_string()).unwrap_or_default(), + installation_id: self.installation_id.clone(), + provider_id: self.provider_id.clone(), + name: self.name.clone(), + version: String::new(), + install_state: self.install_state.as_str().to_owned(), + revision: self.revision, + display_name: self.display_name.clone().unwrap_or_default(), + metadata_revision: self.metadata_revision, + artwork_revision: self.artwork_revision, + runtime_availability: Vec::new(), + } + } + + fn same_content(&self, other: &Self) -> bool { + self.provider_id == other.provider_id + && self.game_id == other.game_id + && self.name == other.name + && self.install_state == other.install_state + && self.display_name == other.display_name + && self.metadata_revision == other.metadata_revision + && self.artwork_revision == other.artwork_revision + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ChangeKind { + Upserted, + Removed, +} + +impl ChangeKind { + pub fn as_str(self) -> &'static str { + match self { + Self::Upserted => "upserted", + Self::Removed => "removed", + } + } +} + +/// A change event. A removal carries the entry as it was last seen. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Change { + pub revision: u64, + pub kind: ChangeKind, + pub entry: Projected, +} + +/// Who may see which entries: the caller's own provider, or every provider with +/// `library.read.all`. An optional provider filter narrows either. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Scope { + pub own_provider: String, + pub read_all: bool, + pub provider_filter: Option, +} + +impl Scope { + pub fn admits(&self, entry: &Projected) -> bool { + (self.read_all || entry.provider_id == self.own_provider) + && self + .provider_filter + .as_ref() + .is_none_or(|provider| *provider == entry.provider_id) + } +} + +/// Why a watcher cannot resume from the position it asked for. +#[derive(Debug, PartialEq, Eq)] +pub enum ResumeError { + /// The position is older than the retained history; list again and watch from there. + Resync, + /// The position is newer than anything this host issued. + Future, +} + +#[derive(Default)] +struct FeedState { + revision: u64, + /// The engine's latest rows by entry key. + sources: BTreeMap, + source_revision: u64, + source_revisions: HashMap, + /// Durable installation ids by entry key. + ids: HashMap, + /// The entry key of each installation id. + keys: HashMap, + /// Keys whose ids are being requested. + requested: BTreeSet, + /// No new id request before this instant, after a failure. + retry_after: Option, + /// The projection by installation id; this order is the list order. + entries: BTreeMap, + history: VecDeque, + /// Events at or below this revision are no longer retained. + floor: u64, +} + +/// The shared projection. Cheap to read; writes come from the engine. +pub struct LibraryFeed { + state: Mutex, + host: Mutex>>, + live: broadcast::Sender, + cursor_key: [u8; 32], +} + +impl Default for LibraryFeed { + fn default() -> Self { + let mut cursor_key = [0; 32]; + // A per-process key: cursors from an earlier run are rejected as stale. + if getrandom::fill(&mut cursor_key).is_err() { + tracing::error!("could not create the library cursor key"); + } + Self { + state: Mutex::default(), + host: Mutex::default(), + live: broadcast::channel(HISTORY_EVENTS).0, + cursor_key, + } + } +} + +impl LibraryFeed { + pub fn new() -> Arc { + Arc::new(Self::default()) + } + + /// Connects the engine's write side. Without it, mutating services are unavailable. + pub fn set_host(&self, host: Arc) { + *self.host.lock().unwrap_or_else(|p| p.into_inner()) = Some(host); + } + + pub fn host(&self) -> Option> { + self.host.lock().unwrap_or_else(|p| p.into_inner()).clone() + } + + fn lock(&self) -> MutexGuard<'_, FeedState> { + self.state.lock().unwrap_or_else(|p| p.into_inner()) + } + + /// Replaces the engine rows. Returns the keys that still need an installation id and are not + /// already being requested; the caller requests them and reports back with + /// [`assign_ids`](Self::assign_ids) or [`ids_failed`](Self::ids_failed). + pub fn sync(&self, sources: Vec) -> Vec { + let mut state = self.lock(); + let sources: BTreeMap = sources + .into_iter() + .map(|source| (source.entry_key.clone(), source)) + .collect(); + let changed = sources != state.sources; + if changed { + state.source_revision += 1; + let revision = state.source_revision; + let mut previous = std::mem::take(&mut state.source_revisions); + state.source_revisions = sources + .iter() + .map(|(key, source)| { + let revision = previous + .remove(key) + .filter(|_| state.sources.get(key) == Some(source)) + .unwrap_or(revision); + (key.clone(), revision) + }) + .collect(); + state.sources = sources; + } + let waiting = state + .retry_after + .is_some_and(|at| std::time::Instant::now() < at); + let missing: Vec = state + .sources + .keys() + .filter(|_| !waiting) + .filter(|key| !state.ids.contains_key(*key) && !state.requested.contains(*key)) + .cloned() + .collect(); + state.requested.extend(missing.iter().cloned()); + if changed { + self.rebuild(&mut state); + } + missing + } + + /// Records the durable ids answered for `requested`. An id already known for a key is kept; + /// a requested key without an answer is asked for again by a later sync. + pub fn assign_ids(&self, requested: &[String], ids: Vec<(String, String)>) { + let mut state = self.lock(); + for key in requested { + state.requested.remove(key); + } + for (key, id) in ids { + if !state.ids.contains_key(&key) { + state.keys.insert(id.clone(), key.clone()); + state.ids.insert(key, id); + } + } + self.rebuild(&mut state); + } + + /// Releases a failed request so the next sync asks again. Those entries stay hidden. + pub fn ids_failed(&self, keys: &[String]) { + let mut state = self.lock(); + for key in keys { + state.requested.remove(key); + } + state.retry_after = Some(std::time::Instant::now() + ID_RETRY); + } + + fn rebuild(&self, state: &mut FeedState) { + let next = state.revision + 1; + let mut fresh: BTreeMap = BTreeMap::new(); + for source in state.sources.values() { + let Some(id) = state.ids.get(&source.entry_key) else { + continue; + }; + fresh.insert( + id.clone(), + Projected { + installation_id: id.clone(), + provider_id: source.provider_id.clone(), + game_id: source.game_id, + name: source.name.clone(), + install_state: source.install_state, + display_name: source.display_name.clone(), + metadata_revision: source.metadata_revision, + artwork_revision: source.artwork_revision, + revision: next, + }, + ); + } + let mut changes = Vec::new(); + for (id, entry) in &mut fresh { + match state.entries.get(id) { + Some(old) if old.same_content(entry) => entry.revision = old.revision, + _ => changes.push(Change { + revision: next, + kind: ChangeKind::Upserted, + entry: entry.clone(), + }), + } + } + for (id, old) in &state.entries { + if !fresh.contains_key(id) { + let mut entry = old.clone(); + entry.revision = next; + changes.push(Change { + revision: next, + kind: ChangeKind::Removed, + entry, + }); + } + } + if changes.is_empty() { + return; + } + state.revision = next; + state.entries = fresh; + for change in changes { + if state.history.len() == HISTORY_EVENTS + && let Some(dropped) = state.history.pop_front() + { + state.floor = state.floor.max(dropped.revision); + } + state.history.push_back(change.clone()); + // No receivers is fine; lagging receivers learn it from the channel. + let _ = self.live.send(change); + } + } + + pub fn revision(&self) -> u64 { + self.lock().revision + } + + /// One page of the entries the scope admits, in installation-id order after `after`. + /// Returns the current revision, the page and whether more entries follow. + pub fn page( + &self, + scope: &Scope, + search: Option<&str>, + after: Option<&str>, + limit: usize, + ) -> (u64, Vec, bool) { + let state = self.lock(); + let search = search.map(str::to_lowercase); + let range = match after { + Some(after) => state + .entries + .range::((std::ops::Bound::Excluded(after), std::ops::Bound::Unbounded)), + None => state.entries.range::(..), + }; + let mut page = Vec::new(); + let mut more = false; + for entry in range.map(|(_, entry)| entry).filter(|entry| { + scope.admits(entry) + && search + .as_ref() + .is_none_or(|text| entry.name.to_lowercase().contains(text)) + }) { + if page.len() == limit { + more = true; + break; + } + page.push(entry.clone()); + } + (state.revision, page, more) + } + + /// The entry with this installation id, if the scope admits it. + pub fn get(&self, scope: &Scope, installation_id: &str) -> (u64, Option) { + let state = self.lock(); + let entry = state + .entries + .get(installation_id) + .filter(|entry| scope.admits(entry)) + .cloned(); + (state.revision, entry) + } + + /// The install folder of every entry that has one, in entry-key order. Host-only. + pub fn folders(&self) -> Vec { + self.lock() + .sources + .values() + .filter(|source| !source.install_dir.trim().is_empty()) + .map(|source| EntryFolder { + entry_key: source.entry_key.clone(), + game_id: source.game_id, + name: source.name.clone(), + folder: source.install_dir.clone(), + }) + .collect() + } + + /// The install folder of the entry with this key, if it has one. Host-only. + pub fn folder_of(&self, entry_key: &str) -> Option { + self.lock() + .sources + .get(entry_key) + .map(|source| source.install_dir.clone()) + .filter(|folder| !folder.trim().is_empty()) + } + + /// The current revision of the entry with this entry key, once it has an installation id. + pub fn revision_of(&self, entry_key: &str) -> Option { + let state = self.lock(); + let id = state.ids.get(entry_key)?; + state.entries.get(id).map(|entry| entry.revision) + } + + /// Host-side installation identity for an engine entry. This never exposes the entry key or + /// installation id to the plugin except through a Core-issued target context. + pub fn projected_entry(&self, entry_key: &str) -> Option<(LibrarySource, Projected)> { + let state = self.lock(); + let source = state.sources.get(entry_key)?.clone(); + let installation_id = state.ids.get(entry_key)?; + let projected = state.entries.get(installation_id)?.clone(); + Some((source, projected)) + } + + /// Readiness can use any visible entry matched to a GameNode game. It neither opens + /// the game nor needs an installed executable, so catalog-only entries are eligible. + pub(crate) fn readiness_targets(&self) -> Vec<(String, String, String, u64)> { + let state = self.lock(); + state + .sources + .values() + .filter(|source| source.game_id.is_some()) + .filter_map(|source| { + let id = state.ids.get(&source.entry_key)?; + let revision = *state.source_revisions.get(&source.entry_key)?; + let title = source.display_name.as_ref().unwrap_or(&source.name); + Some(( + id.clone(), + title.clone(), + source.provider_id.clone(), + revision, + )) + }) + .collect() + } + + pub(crate) fn readiness_game(&self, installation_id: &str, revision: u64) -> Option { + let state = self.lock(); + let key = state.keys.get(installation_id)?; + if state.source_revisions.get(key) != Some(&revision) { + return None; + } + state.sources.get(key)?.game_id + } + + /// The entry key and projection of `installation_id`, if the scope admits it. Host-side only: + /// the entry key never reaches a plugin. + pub fn target(&self, scope: &Scope, installation_id: &str) -> Option<(String, Projected)> { + let state = self.lock(); + let entry = state + .entries + .get(installation_id) + .filter(|entry| scope.admits(entry))?; + let key = state.keys.get(installation_id)?; + Some((key.clone(), entry.clone())) + } + + /// The admitted entries matched to `game_id`. + pub fn by_game(&self, scope: &Scope, game_id: u64) -> (u64, Vec) { + let state = self.lock(); + let entries = state + .entries + .values() + .filter(|entry| entry.game_id == Some(game_id) && scope.admits(entry)) + .cloned() + .collect(); + (state.revision, entries) + } + + /// Subscribes after `after_revision`: zero starts at the current revision with no backlog; + /// otherwise the retained events after that revision are returned first. The receiver is + /// taken under the same lock, so no event falls between backlog and live delivery. + pub fn subscribe( + &self, + after_revision: u64, + ) -> Result<(u64, Vec, broadcast::Receiver), ResumeError> { + let state = self.lock(); + let receiver = self.live.subscribe(); + if after_revision == 0 { + return Ok((state.revision, Vec::new(), receiver)); + } + if after_revision > state.revision { + return Err(ResumeError::Future); + } + if after_revision < state.floor { + return Err(ResumeError::Resync); + } + let backlog = state + .history + .iter() + .filter(|change| change.revision > after_revision) + .cloned() + .collect(); + Ok((state.revision, backlog, receiver)) + } + + /// Signs a cursor for the page after `after`. + pub fn issue_cursor(&self, binding: &CursorBinding, revision: u64, after: &str) -> String { + let claims = CursorClaims { + v: 1, + binding: binding.digest(), + revision, + after: after.to_owned(), + issued: unix_seconds(), + }; + let payload = serde_json::to_vec(&claims).unwrap_or_default(); + let mac = hmac_sha256(&self.cursor_key, &payload); + format!("{}.{}", super::hex(&payload), super::hex(&mac)) + } + + /// Checks a cursor against the query and returns the position it continues after and the + /// revision it was issued for. The caller rejects the page when the library has moved past + /// that revision. A foreign, mismatched or expired cursor is a [`CursorError`]. + pub fn open_cursor( + &self, + cursor: &str, + binding: &CursorBinding, + ) -> Result<(String, u64), CursorError> { + if cursor.len() > MAX_CURSOR_BYTES { + return Err(CursorError::Malformed); + } + let (payload, mac) = cursor.split_once('.').ok_or(CursorError::Malformed)?; + let payload = unhex(payload).ok_or(CursorError::Malformed)?; + let mac = unhex(mac).ok_or(CursorError::Malformed)?; + if !super::constant_time_eq(&mac, &hmac_sha256(&self.cursor_key, &payload)) { + return Err(CursorError::Malformed); + } + let claims: CursorClaims = + serde_json::from_slice(&payload).map_err(|_| CursorError::Malformed)?; + let now = unix_seconds(); + if claims.v != 1 + || claims.binding != binding.digest() + || claims.issued > now + || now - claims.issued > CURSOR_TTL.as_secs() + { + return Err(CursorError::Stale); + } + Ok((claims.after, claims.revision)) + } +} + +/// Rechecks the caller's authorization immediately before a side effect. Run it inside the +/// critical section that commits, so a revocation cannot slip in between check and commit. +pub type CommitGuard = Box Result<(), Status> + Send + 'static>; + +/// How a plugin favorite change ended. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum FavoriteWrite { + Applied, + /// The game already had this favorite state. + AlreadyApplied, + /// None of the caller's own entries is currently matched to the game. + NoMatchedEntry, +} + +/// A catalog game a plugin search found. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct CatalogGame { + pub id: u64, + pub name: String, + pub release_year: Option, +} + +/// How an assignment ended. `revision` is the entry's revision after the call. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum MatchWrite { + Applied { + revision: u64, + }, + /// The entry already has an explicit choice of this game. + AlreadyApplied { + revision: u64, + }, + /// The entry changed since the revision the caller expected; nothing was written. + Conflict { + current: u64, + }, + /// The host does not know this game; it must be found with a search first. + UnknownGame, + /// The user chose this entry's match; a plugin cannot replace it. + UserChoice, +} + +/// A cover read back for an entry. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct StoredArtwork { + pub bytes: Vec, + pub media_type: &'static str, + /// The entry's artwork revision: 0 while the cover is the game's own, not a plugin's. + pub revision: u64, +} + +/// One approved contribution to Core executable discovery. Physical paths stay host-only. +#[derive(Clone)] +pub struct PluginScanRoot { + pub root: gamenode_platform::plugin_storage::PluginLibraryRoot, + pub valid: Arc Result<(), Status> + Send + Sync>, +} + +/// The engine's side of plugin library services: everything that reads or changes state the +/// library machine owns. Implementations take the engine's own locks; callers never hold one. +#[derive(Clone)] +pub struct BackupHostContext { + pub engine: Arc, + pub target: gamenode_core::drm_free::BackupTarget, + pub destination: String, +} + +/// A worker-prepared custom target. Executable file identity is captured before confirmation and +/// checked again by the adapter immediately before spawn. +#[derive(Clone, Debug)] +pub enum CustomLaunchDispatch { + Executable(gamenode_core::drm_free::CustomLaunchCommand), + /// The entry's detected executable with only reviewed parameter/mod-layer contributions. + Detected { + command: gamenode_core::drm_free::CustomLaunchCommand, + }, + Runtime { + command: gamenode_core::drm_free::CustomLaunchCommand, + runtime_id: String, + runtime_version: String, + runtime_revision: u64, + content_id: String, + binding_revision: Option, + /// Opaque keys created by the host for reviewed shared resources, never by a plugin. + lease_keys: Vec, + }, + Uri { + uri: url::Url, + arguments: Vec, + working_directory: String, + environment: gamenode_core::drm_free::LaunchEnvironmentDelta, + }, +} + +/// Runtime resources and content files already resolved from current, approved file references. +/// The engine may compose argument vectors from this data, but receives no plugin file token or +/// filesystem authority beyond these validated launch inputs. +#[derive(Clone, Debug)] +pub struct ResolvedRuntimeLaunch { + pub runtime_id: String, + pub version: String, + pub platform: String, + pub executable: String, + pub content_id: String, + pub content_path: Option, + pub runtime_revision: u64, + pub binding_revision: Option, + pub arguments: Vec, + pub resources: Vec, + pub(crate) lease_keys: Vec, +} + +/// Host-captured authorization for a user-selected plugin launch plan. +#[derive(Clone, Debug)] +pub struct UserLaunchAuthority { + pub(crate) plugin_id: String, + pub(crate) publisher_fingerprint: String, + pub(crate) profile_id: String, + pub(crate) profile_epoch: u64, + /// User-selected plans bind a specific persisted revision. Session-originated plans are + /// additionally fenced by their provider commit lock and recheck current persisted grants. + pub(crate) grant_revision: Option, + pub(crate) requires_files: bool, +} + +#[async_trait::async_trait] +pub trait LibraryHost: Send + Sync { + async fn runtime_resources( + &self, + _owner_key: String, + ) -> Result, Status> { + Err(Status::unavailable("runtime resources are unavailable")) + } + async fn runtime_resource( + &self, + _owner_key: String, + _runtime_id: String, + ) -> Result, Status> { + Err(Status::unavailable("runtime resources are unavailable")) + } + async fn save_runtime_resource( + &self, + _owner_key: String, + _runtime: gamenode_core::library::RuntimeResource, + ) -> Result { + Err(Status::unavailable("runtime resources are unavailable")) + } + async fn remove_runtime_resource( + &self, + _owner_key: String, + _runtime_id: String, + _expected_revision: u64, + ) -> Result { + Err(Status::unavailable("runtime resources are unavailable")) + } + async fn runtime_content_bindings( + &self, + _owner_key: String, + _game_id: u64, + _installation_id: String, + ) -> Result, Status> { + Err(Status::unavailable( + "runtime content bindings are unavailable", + )) + } + async fn save_runtime_content_binding( + &self, + _owner_key: String, + _binding: gamenode_core::library::RuntimeContentBinding, + ) -> Result { + Err(Status::unavailable( + "runtime content bindings are unavailable", + )) + } + async fn remove_runtime_content_binding( + &self, + _owner_key: String, + _binding: gamenode_core::library::RuntimeContentBinding, + ) -> Result { + Err(Status::unavailable( + "runtime content bindings are unavailable", + )) + } + async fn runtime_catalog_revision(&self, _owner_key: String) -> Result { + Err(Status::unavailable("runtime catalog is unavailable")) + } + + /// Every owner's runtimes for an authorized common-category read. + async fn shared_runtime_resources( + &self, + ) -> Result, Status> { + Err(Status::unavailable("runtime catalog is unavailable")) + } + + /// Combined catalog revision across every owner. + async fn shared_runtime_catalog_revision(&self) -> Result { + Err(Status::unavailable("runtime catalog is unavailable")) + } + + /// Safe availability rows for the named installations. `owner_key` limits the projection to + /// the caller's private bindings; `None` includes every owner after authorization. + async fn runtime_availability( + &self, + _owner_key: Option, + _installation_ids: Vec, + ) -> Result, Status> { + Err(Status::unavailable("runtime availability is unavailable")) + } + + /// Host-owned installed programs the runtime picker may suggest. Only official providers + /// contribute; the implementation reads the library store and never a plugin payload. + async fn installed_programs( + &self, + ) -> Result, Status> { + Err(Status::unavailable( + "the installed-program inventory is unavailable", + )) + } + + /// Durable recipes stay under the authenticated plugin/profile namespace. + async fn custom_launch_recipe( + &self, + _owner_key: String, + _recipe_id: String, + ) -> Result, Status> { + Err(Status::unavailable("custom launch recipes are unavailable")) + } + async fn save_custom_launch_recipe( + &self, + _owner_key: String, + _recipe: gamenode_core::library::CustomLaunchRecipe, + ) -> Result { + Err(Status::unavailable("custom launch recipes are unavailable")) + } + async fn remove_custom_launch_recipe( + &self, + _owner_key: String, + _recipe_id: String, + _expected_revision: u64, + ) -> Result { + Err(Status::unavailable("custom launch recipes are unavailable")) + } + async fn launch_recipe_selection( + &self, + _entry_key: String, + ) -> Result, Status> { + Err(Status::unavailable( + "launch recipe selections are unavailable", + )) + } + async fn approve_launch_recipe_plan( + &self, + _entry_key: String, + _recipe_id: String, + _recipe_revision: u64, + _target_revision: u64, + _fingerprint: String, + ) -> Result { + Err(Status::unavailable( + "launch recipe selections are unavailable", + )) + } + /// Resolves the entry's approved detected executable for a parameter-only or mod-layer + /// overlay. URI targets and unavailable/replaced executables fail explicitly. + async fn detected_launch( + &self, + _entry_key: String, + _expected_revision: u64, + ) -> Result { + Err(Status::unimplemented( + "detected launch customization is unavailable on this platform", + )) + } + async fn prepare_custom_launch( + &self, + _recipe: gamenode_core::library::CustomLaunchRecipe, + _executable_path: Option, + _working_directory_path: Option, + _runtime: Option, + ) -> Result { + Err(Status::unimplemented( + "custom launch is unavailable on this platform", + )) + } + async fn launch_custom(&self, _dispatch: CustomLaunchDispatch) -> Result<(), Status> { + Err(Status::unimplemented( + "custom launch is unavailable on this platform", + )) + } + + /// Launches a plan associated with the library entry selected by the host. + async fn launch_custom_for_entry( + &self, + dispatch: CustomLaunchDispatch, + _entry_key: String, + ) -> Result<(), Status> { + self.launch_custom(dispatch).await + } + + async fn launch_custom_for_entry_authorized( + &self, + dispatch: CustomLaunchDispatch, + entry_key: String, + _authority: UserLaunchAuthority, + ) -> Result<(), Status> { + self.launch_custom_for_entry(dispatch, entry_key).await + } + + fn ports_supported(&self) -> bool { + false + } + async fn ports_catalog( + &self, + _detail: Option, + ) -> Result, Status> { + Err(Status::unavailable("ports catalog unavailable")) + } + async fn request_port( + &self, + _port_id: String, + _review: gamenode_core::ports::view::PortPluginRequest, + _check: super::jobs::Fence, + ) -> Result<(), Status> { + Err(Status::unavailable("port installation unavailable")) + } + + fn tools_supported(&self) -> bool { + false + } + async fn tools_list( + &self, + _entry_key: String, + ) -> Result, Status> { + Err(Status::unavailable( + "tools are unavailable on this platform", + )) + } + async fn request_tool( + &self, + _entry_key: String, + _tool_id: String, + _review: gamenode_core::tools::ToolPluginRequest, + _check: super::jobs::Fence, + ) -> Result<(), Status> { + Err(Status::unavailable( + "tools are unavailable on this platform", + )) + } + + /// Resolves the real installation and the user's backup destination on workers. + async fn backup_context(&self, _entry_key: String) -> Result { + Err(Status::unavailable("scoped backups are unavailable")) + } + fn plugin_roots_supported(&self) -> bool { + false + } + fn set_plugin_roots(&self, _owner: String, _roots: Vec) -> Result<(), Status> { + Err(Status::unimplemented( + "Core library-root discovery is unavailable", + )) + } + + /// The favorite state of every GameNode game matched by an entry of `provider_id`, by game + /// id. Games with no entry of that provider are not disclosed. + fn favorites(&self, provider_id: &str) -> Vec<(u64, bool)>; + + /// Marks or unmarks `game_id` through the same local-first path as the user's own star. + /// Requires an entry of `provider_id` currently matched to the game; the favorite stays on + /// the game, never on the entry. + fn set_favorite( + &self, + provider_id: &str, + game_id: u64, + favorite: bool, + guard: &dyn Fn() -> Result<(), Status>, + ) -> Result; + + /// Searches GameNode's catalog by title with the user's verified session and returns at most + /// `limit` games, in the server's order. The games become assignable by + /// [`assign_match`](Self::assign_match). `UNAVAILABLE` when there is no verified, online + /// session or the catalog could not answer. + async fn search_catalog(&self, query: String, limit: usize) + -> Result, Status>; + + /// Assigns `entry_key` to `game_id` through the library's own match policy. Checked and + /// committed under the engine's lock: the entry's revision must be `expected_revision`, and a + /// choice the user made is never replaced. + fn assign_match( + &self, + entry_key: &str, + game_id: u64, + expected_revision: u64, + guard: &dyn Fn() -> Result<(), Status>, + ) -> Result; + + /// The cover `entry_key` shows: its plugin override, else the matched game's own. Reads at + /// most `max_bytes` on a worker thread. `NOT_FOUND` when the entry has no cover on this + /// device; `RESOURCE_EXHAUSTED` when the image is larger than `max_bytes`. Nothing is + /// downloaded. + async fn read_artwork( + &self, + entry_key: String, + max_bytes: u64, + ) -> Result; + + /// Sets the cover override of `entry_key` to the prepared image, or clears it with `None`, + /// if `expected_revision` is current. The file is written before the row and the replaced + /// file removed after it; the call returns once the library applied the change. + async fn set_artwork( + &self, + entry_key: String, + expected_revision: u64, + image: Option, + guard: CommitGuard, + ) -> Result; + + /// Hands the entry's Play (`install` false) or Install link to the operating system through + /// the library's own path, so the user's own Play button and a plugin's request behave the + /// same: the same launch status, the same refusals, and playtime detection as before. The + /// call returns once the link was handled. `UNIMPLEMENTED` when the provider has no such + /// action; `FAILED_PRECONDITION` when the game is already running or being opened, or when + /// the entry lacks data or the store application is missing; `UNAVAILABLE` when the link + /// could not be opened. + async fn open_entry(&self, entry_key: String, install: bool) -> Result<(), Status> { + let _ = (entry_key, install); + Err(Status::unimplemented("starting games is not available")) + } + + /// A stable number for what a launch of `entry_key` would start now: it changes when the + /// detected target changes (another launch URI, another approved executable, its arguments or + /// working directory) and not otherwise. A remembered confirmation and a pre-issued intent + /// are bound to it, so a changed target asks the user again. `NOT_FOUND` for an unknown + /// entry; `FAILED_PRECONDITION` when the entry has no launchable target. + async fn launch_fingerprint(&self, entry_key: String) -> Result { + let _ = entry_key; + Ok(0) + } + + /// The revision of the detected target as shown by the user's launch selector. + async fn launch_target_revision(&self, entry_key: String) -> Result { + let _ = entry_key; + Err(Status::failed_precondition( + "detected launch target changed", + )) + } + + /// Stores the display-name override of `entry_key` if `expected_revision` is current, + /// returning only after the write reached the database and the library applied it. + async fn set_display_name( + &self, + entry_key: String, + expected_revision: u64, + display_name: Option, + guard: CommitGuard, + ) -> Result; +} + +/// Everything a cursor is bound to besides the library revision. +#[derive(Debug, PartialEq, Eq)] +pub struct CursorBinding { + /// Which list the cursor belongs to, so one list's cursor cannot page another. + pub route: &'static str, + pub session_id: String, + pub profile_epoch: u64, + pub grant_revision: u64, + pub scope: Scope, + pub search: Option, +} + +impl CursorBinding { + fn digest(&self) -> String { + let mut hash = Sha256::new(); + for part in [ + self.route, + self.session_id.as_str(), + &self.profile_epoch.to_string(), + &self.grant_revision.to_string(), + &self.scope.own_provider, + if self.scope.read_all { "all" } else { "own" }, + self.scope.provider_filter.as_deref().unwrap_or("\u{0}"), + self.search.as_deref().unwrap_or("\u{0}"), + ] { + hash.update((part.len() as u64).to_be_bytes()); + hash.update(part.as_bytes()); + } + super::hex(&hash.finalize()) + } +} + +#[derive(Debug, PartialEq, Eq)] +pub enum CursorError { + /// Not a cursor this host issued. + Malformed, + /// Issued for another query, scope or session, expired, or the library changed since. + Stale, +} + +#[derive(Serialize, Deserialize)] +struct CursorClaims { + v: u8, + binding: String, + revision: u64, + after: String, + issued: u64, +} + +fn unix_seconds() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|elapsed| elapsed.as_secs()) + .unwrap_or_default() +} + +fn unhex(text: &str) -> Option> { + if !text.len().is_multiple_of(2) { + return None; + } + (0..text.len()) + .step_by(2) + .map(|i| u8::from_str_radix(text.get(i..i + 2)?, 16).ok()) + .collect() +} + +/// HMAC-SHA256 (RFC 2104) with a 32-byte key. +fn hmac_sha256(key: &[u8; 32], message: &[u8]) -> [u8; 32] { + let mut block = [0u8; 64]; + block[..32].copy_from_slice(key); + let mut inner = Sha256::new(); + inner.update(block.map(|b| b ^ 0x36)); + inner.update(message); + let mut outer = Sha256::new(); + outer.update(block.map(|b| b ^ 0x5c)); + outer.update(inner.finalize()); + outer.finalize().into() +} + +#[cfg(test)] +mod tests; diff --git a/crates/app/src/plugin_host/library/tests.rs b/crates/app/src/plugin_host/library/tests.rs new file mode 100644 index 000000000..6b342ef3e --- /dev/null +++ b/crates/app/src/plugin_host/library/tests.rs @@ -0,0 +1,268 @@ +use super::*; + +fn source(key: &str, game_id: Option, name: &str) -> LibrarySource { + LibrarySource { + entry_key: key.to_owned(), + provider_id: key.split(':').next().unwrap().to_owned(), + game_id, + name: name.to_owned(), + install_state: InstallState::Installed, + display_name: None, + metadata_revision: 0, + artwork_revision: 0, + install_dir: String::new(), + detected_target: None, + } +} + +fn own(provider: &str) -> Scope { + Scope { + own_provider: provider.to_owned(), + read_all: false, + provider_filter: None, + } +} + +fn all() -> Scope { + Scope { + own_provider: "steam".to_owned(), + read_all: true, + provider_filter: None, + } +} + +/// Syncs `sources` and answers every id request with `id-`. +fn feed_with(sources: Vec) -> Arc { + let feed = LibraryFeed::new(); + resync(&feed, sources); + feed +} + +fn resync(feed: &LibraryFeed, sources: Vec) { + let missing = feed.sync(sources); + let ids = missing + .iter() + .map(|key| (key.clone(), format!("id-{key}"))) + .collect(); + feed.assign_ids(&missing, ids); +} + +fn binding(scope: Scope) -> CursorBinding { + CursorBinding { + route: "library", + session_id: "s1".into(), + profile_epoch: 1, + grant_revision: 1, + scope, + search: None, + } +} + +#[test] +fn entries_appear_only_once_their_installation_id_is_durable() { + let feed = LibraryFeed::new(); + let missing = feed.sync(vec![source("steam:620", Some(7), "Portal 2")]); + assert_eq!(missing, ["steam:620"]); + assert!(feed.page(&all(), None, None, 10).1.is_empty()); + // A second sync while the request is outstanding does not ask again. + assert!( + feed.sync(vec![source("steam:620", Some(7), "Portal 2")]) + .is_empty() + ); + feed.assign_ids(&missing, vec![("steam:620".into(), "abc".into())]); + let (revision, page, more) = feed.page(&all(), None, None, 10); + assert_eq!(revision, 1); + assert!(!more); + assert_eq!(page[0].installation_id, "abc"); + assert_eq!(page[0].game_id, Some(7)); +} + +#[test] +fn a_failed_id_request_keeps_the_entry_hidden_and_backs_off() { + let feed = LibraryFeed::new(); + let missing = feed.sync(vec![source("steam:620", None, "Portal 2")]); + feed.ids_failed(&missing); + assert!(feed.page(&all(), None, None, 10).1.is_empty()); + assert!( + feed.sync(vec![source("steam:620", None, "Portal 2 GOTY")]) + .is_empty(), + "no retry storm right after a failure" + ); +} + +#[test] +fn unmatched_entries_have_no_game_and_multiple_installations_share_one() { + let feed = feed_with(vec![ + source("steam:570", None, "Dota 2"), + source("steam:620", Some(7), "Portal 2"), + source("gog:1", Some(7), "Portal 2"), + ]); + let (_, page, _) = feed.page(&all(), None, None, 10); + let protos: Vec<_> = page.iter().map(Projected::to_proto).collect(); + let dota = protos.iter().find(|e| e.name == "Dota 2").unwrap(); + assert_eq!(dota.game_id, ""); + assert_eq!(dota.installation_id, "id-steam:570"); + let portal: Vec<_> = protos.iter().filter(|e| e.game_id == "7").collect(); + assert_eq!(portal.len(), 2); + assert_ne!(portal[0].installation_id, portal[1].installation_id); + assert_eq!(feed.by_game(&all(), 7).1.len(), 2); + assert_eq!(feed.by_game(&own("gog"), 7).1.len(), 1); +} + +#[test] +fn a_rescan_or_match_change_keeps_the_installation_id_and_moves_the_game() { + let feed = feed_with(vec![source("steam:620", None, "Portal 2")]); + let before = feed.get(&all(), "id-steam:620").1.unwrap(); + resync(&feed, vec![source("steam:620", Some(7), "Portal 2")]); + let (revision, after) = feed.get(&all(), "id-steam:620"); + let after = after.unwrap(); + assert_eq!(after.installation_id, before.installation_id); + assert_eq!(after.game_id, Some(7)); + assert_eq!(after.revision, revision); + assert!(after.revision > before.revision); + // An identical rescan changes nothing. + resync(&feed, vec![source("steam:620", Some(7), "Portal 2")]); + assert_eq!(feed.revision(), revision); +} + +#[test] +fn own_provider_reads_never_disclose_another_providers_entries() { + let feed = feed_with(vec![ + source("steam:620", Some(7), "Portal 2"), + source("gog:1", Some(8), "Witcher"), + ]); + let (_, page, _) = feed.page(&own("gog"), None, None, 10); + assert_eq!(page.len(), 1); + assert_eq!(page[0].provider_id, "gog"); + // Filtering to a foreign provider without the whole-library grant yields nothing. + let foreign = Scope { + provider_filter: Some("steam".into()), + ..own("gog") + }; + assert!(feed.page(&foreign, None, None, 10).1.is_empty()); + assert!(feed.get(&own("gog"), "id-steam:620").1.is_none()); + assert!(feed.by_game(&own("gog"), 7).1.is_empty()); + // With it, the filter selects that provider. + let granted = Scope { + read_all: true, + ..foreign + }; + assert_eq!(feed.page(&granted, None, None, 10).1.len(), 1); +} + +#[test] +fn pages_are_ordered_bounded_and_searchable() { + let feed = feed_with( + (0..5) + .map(|i| source(&format!("steam:{i}"), None, &format!("Game {i}"))) + .collect(), + ); + let (_, first, more) = feed.page(&all(), None, None, 2); + assert!(more); + let (_, second, _) = feed.page(&all(), None, Some(&first[1].installation_id), 2); + assert!(first[1].installation_id < second[0].installation_id); + let (_, found, _) = feed.page(&all(), Some("game 3"), None, 10); + assert_eq!(found.len(), 1); + assert_eq!(found[0].name, "Game 3"); +} + +#[test] +fn cursors_are_bound_to_their_query_and_expire_with_the_library_revision() { + let feed = feed_with(vec![source("steam:1", None, "A")]); + let bound = binding(all()); + let cursor = feed.issue_cursor(&bound, feed.revision(), "id-steam:1"); + assert_eq!( + feed.open_cursor(&cursor, &bound), + Ok(("id-steam:1".to_owned(), 1)) + ); + // Another scope, search, session, profile or grant revision rejects it. + for other in [ + binding(own("steam")), + CursorBinding { + search: Some("a".into()), + ..binding(all()) + }, + CursorBinding { + session_id: "s2".into(), + ..binding(all()) + }, + CursorBinding { + profile_epoch: 2, + ..binding(all()) + }, + CursorBinding { + grant_revision: 2, + ..binding(all()) + }, + ] { + assert_eq!(feed.open_cursor(&cursor, &other), Err(CursorError::Stale)); + } + // A tampered cursor or one from another process is not a cursor at all. + let mut tampered = cursor.clone(); + tampered.replace_range(0..2, "00"); + assert_eq!( + feed.open_cursor(&tampered, &bound), + Err(CursorError::Malformed) + ); + assert_eq!( + LibraryFeed::new().open_cursor(&cursor, &bound), + Err(CursorError::Malformed) + ); + assert_eq!( + feed.open_cursor("not a cursor", &bound), + Err(CursorError::Malformed) + ); + // The cursor reports the revision it was issued for; the service rejects it once the + // library has moved on. + resync(&feed, vec![source("steam:1", None, "B")]); + assert_eq!(feed.open_cursor(&cursor, &bound).unwrap().1, 1); + assert_eq!(feed.revision(), 2); +} + +#[test] +fn watchers_resume_from_retained_history_or_must_resync() { + let feed = feed_with(vec![source("steam:1", None, "A")]); + // Zero starts at the current revision with no backlog. + let (current, backlog, _rx) = feed.subscribe(0).unwrap(); + assert_eq!((current, backlog.len()), (1, 0)); + resync(&feed, vec![source("steam:1", Some(3), "A")]); + resync(&feed, vec![]); + let (_, backlog, _rx) = feed.subscribe(1).unwrap(); + assert_eq!( + backlog + .iter() + .map(|c| (c.revision, c.kind)) + .collect::>(), + [(2, ChangeKind::Upserted), (3, ChangeKind::Removed)] + ); + assert_eq!(backlog[1].entry.installation_id, "id-steam:1"); + assert_eq!(feed.subscribe(9).unwrap_err(), ResumeError::Future); + // Push the first events out of the bounded history. + for i in 0..HISTORY_EVENTS as u64 + 4 { + resync(&feed, vec![source("steam:1", Some(i), "A")]); + } + assert_eq!(feed.subscribe(1).unwrap_err(), ResumeError::Resync); + assert!(feed.subscribe(feed.revision() - 1).is_ok()); +} + +#[tokio::test] +async fn live_events_follow_the_backlog_without_gaps() { + let feed = feed_with(vec![source("steam:1", None, "A")]); + let (_, _, mut rx) = feed.subscribe(1).unwrap(); + resync(&feed, vec![source("steam:1", None, "B")]); + let change = rx.recv().await.unwrap(); + assert_eq!(change.revision, 2); + assert_eq!(change.entry.name, "B"); +} + +#[test] +fn hmac_matches_the_rfc_4231_vector_shape() { + // RFC 4231 test case 2 uses a short key; a 32-byte key padded with zeros is equivalent to + // the 4-byte key "Jefe" padded to the block, so the published digest applies. + let mut key = [0u8; 32]; + key[..4].copy_from_slice(b"Jefe"); + assert_eq!( + super::super::hex(&hmac_sha256(&key, b"what do ya want for nothing?")), + "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843" + ); +} diff --git a/crates/app/src/plugin_host/login/tests.rs b/crates/app/src/plugin_host/login/tests.rs index 1537ee005..47f4423ad 100644 --- a/crates/app/src/plugin_host/login/tests.rs +++ b/crates/app/src/plugin_host/login/tests.rs @@ -829,10 +829,15 @@ async fn public_sdk_reaches_broker_only_with_extraction_grants_and_session_exit_ policy() }; api.register(Registration { + declared_developer: "Fixture developer".into(), + package_digest: Vec::new(), provider_id: "fixture".into(), plugin_id: "fixture.login".into(), + kind: crate::plugin_host::provider::RegistrationKind::Provider, + origin: crate::plugin_host::provider::RegistrationOrigin::Official, capabilities: capabilities.iter().map(|c| (*c).to_owned()).collect(), shared_catalog: false, + playtime: Default::default(), services: Arc::new(Services(broker.clone(), login_policy)), }) .unwrap(); diff --git a/crates/app/src/plugin_host/managed_packages.rs b/crates/app/src/plugin_host/managed_packages.rs new file mode 100644 index 000000000..221529d9a --- /dev/null +++ b/crates/app/src/plugin_host/managed_packages.rs @@ -0,0 +1,718 @@ +//! Compatibility-gated package validation, installation, and activation. +//! +//! These lifecycle helpers accept only packages already staged by the bounded extractor. They +//! verify signatures before reading the manifest and never execute package contents. + +use super::{ + compatibility::{ + CompatibilityState, CompatibilityVerdict, TargetCompatibilityAssessment, + assess_manifest_targets, + }, + package::Manifest, +}; +use gamenode_platform::{ + plugin_environment::{EmulationPolicy, PluginEnvironment}, + plugin_packages::{IntegrityManifest, verify_package_directory}, + plugin_registry::{InstalledPluginVersion, PluginPackageRegistry}, +}; +use sha2::Digest; +use std::{fs, path::Path}; +use thiserror::Error; + +const MAX_MANIFEST_BYTES: u64 = 4 * 1024 * 1024; + +#[derive(Debug, Error)] +pub enum PackageLifecycleError { + #[error("package validation failed: {0}")] + InvalidPackage(String), + #[error("no target is compatible with the current execution environment")] + NoCompatibleTarget(Vec), + #[error("multiple package targets match the current execution environment")] + AmbiguousTarget, + #[error("installed plugin version was not found")] + VersionNotFound, + #[error("installed package identity or version does not match its registry record")] + RegistryIdentityMismatch, + #[error("plugin package registry operation failed: {0}")] + Registry(String), + #[error("execution environment detection failed: {0}")] + Environment(String), + #[error("package validation worker failed")] + WorkerFailed, +} + +#[derive(Clone, Debug)] +pub struct PackageCandidateReport { + pub manifest: Manifest, + pub environment: PluginEnvironment, + pub targets: Vec, + pub extension_schemas: Vec, +} + +/// UI diagnostics for signed packages. Only the effective execution facts used +/// for review are returned, rather than the raw host or os-release metadata. +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PackageCompatibilityReview { + pub state: CompatibilityState, + pub ambiguous: bool, + pub os: Option, + pub release: Option, + pub product: Option, + pub build: Option, + pub architecture: Option, + pub abi: Option, + pub libc: Option, + pub emulation: gamenode_platform::plugin_environment::EmulationStatus, + pub targets: Vec, +} + +impl PackageCandidateReport { + pub fn compatibility_review(&self) -> PackageCompatibilityReview { + let selected = self.selected_target(); + let ambiguous = matches!(&selected, Err(PackageLifecycleError::AmbiguousTarget)); + let state = if selected.is_ok() { + CompatibilityState::Compatible + } else if ambiguous { + CompatibilityState::Incompatible + } else if self + .targets + .iter() + .any(|target| target.verdict.state == CompatibilityState::Indeterminate) + { + CompatibilityState::Indeterminate + } else { + CompatibilityState::Incompatible + }; + let userspace = self.environment.userspace.as_ref(); + PackageCompatibilityReview { + state, + ambiguous, + os: userspace.map(|os| os.id.clone().unwrap_or_else(|| os.family.clone())), + release: userspace.and_then(|os| os.version_id.clone()), + product: userspace.and_then(|os| os.kind), + build: userspace.and_then(|os| os.build), + architecture: self.environment.process_architecture.clone(), + abi: self.environment.process_abi.clone(), + libc: self.environment.libc.clone(), + emulation: self.environment.emulation.clone(), + targets: self.targets.clone(), + } + } + + /// Return the unique compatible target. Incompatible or indeterminate candidates never + /// select a substitute target implicitly. + pub fn selected_target(&self) -> Result<&TargetCompatibilityAssessment, PackageLifecycleError> { + let mut compatible = self + .targets + .iter() + .filter(|target| target.verdict.state == CompatibilityState::Compatible); + let Some(selected) = compatible.next() else { + return Err(PackageLifecycleError::NoCompatibleTarget( + self.targets + .iter() + .map(|target| target.verdict.clone()) + .collect(), + )); + }; + if compatible.next().is_some() { + return Err(PackageLifecycleError::AmbiguousTarget); + } + Ok(selected) + } +} + +/// Ordering boundary for host writes that change the active package, pinned publisher, or +/// runtime registration of a plugin. Acquire it inside the worker that owns the write. +pub(super) fn lock_publisher_identity() -> std::sync::MutexGuard<'static, ()> { + static PUBLISHER_IDENTITY: std::sync::Mutex<()> = std::sync::Mutex::new(()); + PUBLISHER_IDENTITY + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) +} + +#[derive(Clone)] +pub struct ManagedPackageLifecycle { + registry: PluginPackageRegistry, +} + +impl ManagedPackageLifecycle { + pub fn new(registry: PluginPackageRegistry) -> Self { + Self { registry } + } + + /// Verify and assess a staged candidate for import or update selection. All file reads and + /// JSON processing run on blocking workers; environment detection has its own worker too. + pub async fn inspect_candidate( + &self, + package_root: impl AsRef, + publisher_key: [u8; 32], + emulation_policy: EmulationPolicy, + ) -> Result { + inspect_staged_package(package_root, publisher_key, emulation_policy).await + } + + /// Install a compatible candidate. An incompatible update is rejected before the registry + /// is changed, leaving the active version and all plugin data untouched. + pub async fn install_candidate( + &self, + package_root: impl AsRef, + publisher_key: [u8; 32], + emulation_policy: EmulationPolicy, + activate: bool, + ) -> Result { + let package_root = package_root.as_ref().to_owned(); + let report = self + .inspect_candidate(&package_root, publisher_key, emulation_policy) + .await?; + let entrypoint = report.selected_target()?.target.entrypoint.clone(); + let plugin_id = report.manifest.id; + let version = report.manifest.version; + let registry = self.registry.clone(); + tokio::task::spawn_blocking(move || { + let _publisher = activate.then(lock_publisher_identity); + registry + .install_signed_with_entrypoint( + &plugin_id, + &version, + &package_root, + &publisher_key, + &entrypoint, + activate, + ) + .map_err(|error| PackageLifecycleError::Registry(error.to_string())) + }) + .await + .map_err(|_| PackageLifecycleError::WorkerFailed)? + } + + /// Revalidate a stored version against current environment facts before switching the active + /// pointer. This does not execute the package and does not fall back to another version. + pub async fn activate_version( + &self, + plugin_id: String, + version: String, + publisher_key: [u8; 32], + emulation_policy: EmulationPolicy, + ) -> Result { + let registry = self.registry.clone(); + let lookup_id = plugin_id.clone(); + let lookup_version = version.clone(); + let installed = tokio::task::spawn_blocking(move || { + registry + .versions(&lookup_id) + .map_err(|error| PackageLifecycleError::Registry(error.to_string()))? + .into_iter() + .find(|installed| installed.version == lookup_version) + .ok_or(PackageLifecycleError::VersionNotFound) + }) + .await + .map_err(|_| PackageLifecycleError::WorkerFailed)??; + let report = self + .inspect_candidate(&installed.package_path, publisher_key, emulation_policy) + .await?; + if report.manifest.id != plugin_id || report.manifest.version != version { + return Err(PackageLifecycleError::RegistryIdentityMismatch); + } + report.selected_target()?; + let registry = self.registry.clone(); + tokio::task::spawn_blocking(move || { + let _publisher = lock_publisher_identity(); + registry + .set_active(&plugin_id, &version) + .map_err(|error| PackageLifecycleError::Registry(error.to_string()))?; + Ok::<_, PackageLifecycleError>(installed) + }) + .await + .map_err(|_| PackageLifecycleError::WorkerFailed)? + } + + /// Removes every installed version after the caller has stopped processes and revoked + /// sessions. Filesystem work stays on a blocking worker. + pub async fn remove_plugin(&self, plugin_id: String) -> Result<(), PackageLifecycleError> { + let registry = self.registry.clone(); + tokio::task::spawn_blocking(move || { + let _publisher = lock_publisher_identity(); + registry + .remove_plugin(&plugin_id) + .map_err(|error| PackageLifecycleError::Registry(error.to_string())) + }) + .await + .map_err(|_| PackageLifecycleError::WorkerFailed)? + } +} + +/// Verify and assess one staged package directory without needing a registry. Bundle inspection +/// and standalone import share this entry point so neither can drift from the other. All file +/// reads and JSON processing run on blocking workers; environment detection has its own worker. +pub(super) async fn inspect_staged_package( + package_root: impl AsRef, + publisher_key: [u8; 32], + emulation_policy: EmulationPolicy, +) -> Result { + let environment = gamenode_platform::plugin_environment::detect() + .await + .map_err(PackageLifecycleError::Environment)?; + inspect_staged_package_in(package_root, publisher_key, emulation_policy, environment).await +} + +/// The same verification with an execution environment the caller already detected. A bundle +/// install evaluates every component on one worker and must not re-detect the environment for +/// each one; the result is otherwise identical to [`inspect_staged_package`]. +pub(super) async fn inspect_staged_package_in( + package_root: impl AsRef, + publisher_key: [u8; 32], + emulation_policy: EmulationPolicy, + environment: PluginEnvironment, +) -> Result { + let package_root = package_root.as_ref().to_owned(); + tokio::task::spawn_blocking(move || { + inspect_staged_package_blocking( + &package_root, + publisher_key, + emulation_policy, + &environment, + ) + }) + .await + .map_err(|_| PackageLifecycleError::WorkerFailed)? +} + +/// The blocking body shared by every staged inspection path. Callers own the environment and +/// must already be on a worker thread. +pub(super) fn inspect_staged_package_blocking( + package_root: &Path, + publisher_key: [u8; 32], + emulation_policy: EmulationPolicy, + environment: &PluginEnvironment, +) -> Result { + let integrity = verify_package_directory(package_root, &publisher_key) + .map_err(|error| PackageLifecycleError::InvalidPackage(error.to_string()))?; + let manifest_bytes = read_signed_manifest(package_root, &integrity)?; + let manifest = Manifest::parse_json(&manifest_bytes) + .map_err(|error| PackageLifecycleError::InvalidPackage(error.to_string()))? + .manifest() + .clone(); + let extension_schemas = validate_manifest_payload(package_root, &integrity, &manifest)?; + let targets = assess_manifest_targets(&manifest_bytes, environment, emulation_policy) + .map_err(|error| PackageLifecycleError::InvalidPackage(error.to_string()))?; + Ok(PackageCandidateReport { + manifest, + environment: environment.clone(), + targets, + extension_schemas, + }) +} + +fn read_signed_manifest( + package_root: &Path, + integrity: &IntegrityManifest, +) -> Result, PackageLifecycleError> { + let manifest_path = package_root.join("plugin.json"); + let metadata = fs::symlink_metadata(&manifest_path) + .map_err(|error| PackageLifecycleError::InvalidPackage(error.to_string()))?; + if !metadata.is_file() + || metadata.file_type().is_symlink() + || metadata.len() > MAX_MANIFEST_BYTES + { + return Err(PackageLifecycleError::InvalidPackage( + "plugin.json is not a bounded regular file".into(), + )); + } + let bytes = fs::read(&manifest_path) + .map_err(|error| PackageLifecycleError::InvalidPackage(error.to_string()))?; + let expected = + integrity.files.0.get("plugin.json").ok_or_else(|| { + PackageLifecycleError::InvalidPackage("plugin.json is unsigned".into()) + })?; + if format!("{:x}", sha2::Sha256::digest(&bytes)) != *expected { + return Err(PackageLifecycleError::InvalidPackage( + "plugin.json changed during compatibility validation".into(), + )); + } + Ok(bytes) +} + +fn validate_manifest_payload( + package_root: &Path, + integrity: &IntegrityManifest, + manifest: &Manifest, +) -> Result, PackageLifecycleError> +{ + let mut referenced = manifest.license.files.clone(); + referenced.extend(manifest.license.notices.iter().cloned()); + referenced.extend(manifest.resources.values().cloned()); + referenced.extend(manifest.schemas.iter().map(|schema| schema.asset.clone())); + referenced.extend( + manifest + .targets + .iter() + .map(|target| target.entrypoint.clone()), + ); + for path in referenced { + if !integrity.files.0.contains_key(&path) { + return Err(PackageLifecycleError::InvalidPackage(format!( + "manifest reference is missing from signed payload: {path}" + ))); + } + } + let mut descriptors = Vec::new(); + if !manifest.schemas.is_empty() { + let mut assets = std::collections::BTreeMap::new(); + for schema in &manifest.schemas { + assets.insert( + schema.asset.clone(), + read_signed_payload(package_root, integrity, &schema.asset, 64 * 1024)?, + ); + } + manifest + .validate_schema_assets(&assets) + .map_err(|error| PackageLifecycleError::InvalidPackage(error.to_string()))?; + for schema in &manifest.schemas { + let bytes = assets.get(&schema.asset).ok_or_else(|| { + PackageLifecycleError::InvalidPackage("schema asset disappeared".into()) + })?; + descriptors.push(packaged_schema_descriptor(schema, bytes)?); + } + } + gamenode_plugin_protocol::extensions::validate_schema_catalog(&descriptors).map_err(|_| { + PackageLifecycleError::InvalidPackage("invalid extension schema catalog".into()) + })?; + Ok(descriptors) +} + +fn packaged_schema_descriptor( + packaged: &super::package::PackagedSchema, + bytes: &[u8], +) -> Result { + use gamenode_plugin_protocol::proto::{ + ExtensionFieldClassification as Classification, ExtensionSchemaDescriptor, + ExtensionSchemaField, + }; + let schema: serde_json::Value = serde_json::from_slice(bytes) + .map_err(|error| PackageLifecycleError::InvalidPackage(error.to_string()))?; + semver::Version::parse(&packaged.version) + .map_err(|error| PackageLifecycleError::InvalidPackage(error.to_string()))?; + // Full SemVer is encoded in the id so prereleases remain distinguishable; wire version 1 + // identifies this manifest-to-protocol descriptor mapping. + let encoded_version = packaged + .version + .to_ascii_lowercase() + .chars() + .map(|character| { + if character.is_ascii_alphanumeric() || character == '-' { + character + } else { + '-' + } + }) + .collect::(); + let schema_id = format!("{}.v{encoded_version}", packaged.namespace); + if schema_id.len() > 256 { + return Err(PackageLifecycleError::InvalidPackage( + "schema identity is too long".into(), + )); + } + let mut fields = Vec::new(); + collect_schema_fields(&schema, "", &mut fields)?; + let fields = fields + .into_iter() + .map(|(path, classification)| ExtensionSchemaField { + path, + classification: match classification { + 1 => Classification::Public as i32, + 2 => Classification::Sensitive as i32, + _ => Classification::Private as i32, + }, + }) + .collect(); + let descriptor = ExtensionSchemaDescriptor { + namespace: packaged.namespace.clone(), + schema_id, + schema_version: 1, + schema_digest: sha2::Sha256::digest(bytes).to_vec(), + schema_json: bytes.to_vec(), + fields, + optional: true, + }; + gamenode_plugin_protocol::extensions::validate_schema_descriptor(&descriptor).map_err( + |_| { + PackageLifecycleError::InvalidPackage( + "packaged schema is outside the runtime schema subset".into(), + ) + }, + )?; + Ok(descriptor) +} + +fn collect_schema_fields( + schema: &serde_json::Value, + prefix: &str, + output: &mut Vec<(String, u8)>, +) -> Result { + let object = schema.as_object().ok_or_else(|| { + PackageLifecycleError::InvalidPackage("schema node must be an object".into()) + })?; + let own = match object + .get("x-gamenode-classification") + .and_then(serde_json::Value::as_str) + { + Some("public") => 1, + Some("sensitive") => 2, + Some("private") => 3, + _ if prefix.is_empty() => 1, + _ => { + return Err(PackageLifecycleError::InvalidPackage( + "schema field lacks a valid classification".into(), + )); + } + }; + let mut maximum = own; + if let Some(properties) = object + .get("properties") + .and_then(serde_json::Value::as_object) + { + for (name, child) in properties { + let path = if prefix.is_empty() { + name.clone() + } else { + format!("{prefix}.{name}") + }; + let class = collect_schema_fields(child, &path, output)?; + maximum = maximum.max(class); + output.push((path, class)); + } + } + if prefix.is_empty() { + return Ok(maximum); + } + Ok(own.max(maximum)) +} + +fn read_signed_payload( + package_root: &Path, + integrity: &IntegrityManifest, + relative_path: &str, + max_bytes: u64, +) -> Result, PackageLifecycleError> { + let root = fs::canonicalize(package_root) + .map_err(|error| PackageLifecycleError::InvalidPackage(error.to_string()))?; + let path = package_root.join(relative_path); + let metadata = fs::symlink_metadata(&path) + .map_err(|error| PackageLifecycleError::InvalidPackage(error.to_string()))?; + if !metadata.is_file() || metadata.file_type().is_symlink() || metadata.len() > max_bytes { + return Err(PackageLifecycleError::InvalidPackage(format!( + "signed payload is not a bounded regular file: {relative_path}" + ))); + } + let canonical = fs::canonicalize(&path) + .map_err(|error| PackageLifecycleError::InvalidPackage(error.to_string()))?; + if !canonical.starts_with(root) { + return Err(PackageLifecycleError::InvalidPackage(format!( + "signed payload escapes package root: {relative_path}" + ))); + } + let bytes = fs::read(canonical) + .map_err(|error| PackageLifecycleError::InvalidPackage(error.to_string()))?; + let expected = integrity + .files + .0 + .get(relative_path) + .ok_or_else(|| PackageLifecycleError::InvalidPackage("payload is unsigned".into()))?; + if format!("{:x}", sha2::Sha256::digest(&bytes)) != *expected { + return Err(PackageLifecycleError::InvalidPackage(format!( + "signed payload changed during validation: {relative_path}" + ))); + } + Ok(bytes) +} + +#[cfg(all(test, target_os = "linux"))] +pub(super) mod tests { + use super::*; + use base64::Engine; + use ring::signature::KeyPair; + use std::collections::BTreeMap; + use tempfile::tempdir; + + #[test] + fn signed_manifest_schema_maps_to_host_owned_optional_descriptor() { + let bytes = br#"{"$schema":"https://json-schema.org/draft/2020-12/schema","type":"object","properties":{"display":{"type":"object","properties":{"label":{"type":"string","maxLength":80,"x-gamenode-classification":"public"},"notes":{"type":"string","maxLength":80,"x-gamenode-classification":"sensitive"}},"required":["label","notes"],"additionalProperties":false,"x-gamenode-classification":"public"}},"required":["display"],"additionalProperties":false}"#; + let descriptor = packaged_schema_descriptor( + &super::super::package::PackagedSchema { + namespace: "org.example.catalog".into(), + version: "1.2.3".into(), + classification: super::super::package::DataClassification::Sensitive, + asset: "schemas/catalog.json".into(), + }, + bytes, + ) + .unwrap(); + assert_eq!(descriptor.schema_id, "org.example.catalog.v1-2-3"); + assert_eq!(descriptor.schema_version, 1); + assert!(descriptor.optional); + assert!(descriptor.fields.iter().any(|field| { + field.path == "display.label" + && field.classification + == gamenode_plugin_protocol::proto::ExtensionFieldClassification::Public as i32 + })); + assert!(descriptor.fields.iter().any(|field| { + field.path == "display" + && field.classification + == gamenode_plugin_protocol::proto::ExtensionFieldClassification::Sensitive + as i32 + })); + } + + pub(in crate::plugin_host) fn write_signed_package( + root: &Path, + version: &str, + os: &str, + key: &ring::signature::Ed25519KeyPair, + ) { + write_signed_package_with_playtime(root, version, os, key, None); + } + + fn write_signed_package_with_playtime( + root: &Path, + version: &str, + os: &str, + key: &ring::signature::Ed25519KeyPair, + playtime: Option, + ) { + fs::create_dir_all(root.join("bin")).unwrap(); + fs::create_dir_all(root.join("licenses")).unwrap(); + fs::write(root.join("bin/plugin"), b"fixture executable").unwrap(); + fs::write(root.join("licenses/LICENSE"), b"fixture license").unwrap(); + let abi = if os == "windows" { "msvc" } else { "gnu" }; + let mut manifest_value = serde_json::json!({ + "schema": 1, + "id": "org.example.lifecycle", + "kind": "provider", + "provider_id": "lifecycle-fixture", + "name": "Lifecycle Fixture", + "version": version, + "api": {"min": "1.6.0", "max": "1.6.0"}, + "targets": [{"os": os, "arch": "x86_64", "abi": abi, "entrypoint": "bin/plugin"}], + "publisher": { + "key_id": "fixture-key", + "public_key": base64::engine::general_purpose::STANDARD.encode(key.public_key().as_ref()) + }, + "license": {"expression": "MIT", "files": ["licenses/LICENSE"]} + }); + if let Some(playtime) = playtime { + manifest_value["playtime"] = playtime; + } + let manifest = serde_json::to_vec(&manifest_value).unwrap(); + fs::write(root.join("plugin.json"), &manifest).unwrap(); + let files = [ + ("plugin.json", manifest.as_slice()), + ("bin/plugin", b"fixture executable".as_slice()), + ("licenses/LICENSE", b"fixture license".as_slice()), + ] + .into_iter() + .map(|(path, bytes)| { + ( + path.to_owned(), + format!("{:x}", sha2::Sha256::digest(bytes)), + ) + }) + .collect::>(); + let integrity = + serde_json::to_vec(&serde_json::json!({"schema": 1, "files": files})).unwrap(); + let mut signed = gamenode_platform::plugin_packages::SIGNATURE_DOMAIN_PREFIX.to_vec(); + signed.extend_from_slice(&integrity); + fs::write(root.join("integrity.json"), integrity).unwrap(); + fs::write(root.join("signature.ed25519"), key.sign(&signed).as_ref()).unwrap(); + } + + #[test] + fn playtime_disclosure_is_part_of_the_verified_package_manifest() { + let base = tempdir().unwrap(); + let package = base.path().join("signed-playtime"); + let key = ring::signature::Ed25519KeyPair::from_seed_unchecked(&[42; 32]).unwrap(); + let public_key: [u8; 32] = key.public_key().as_ref().try_into().unwrap(); + write_signed_package_with_playtime( + &package, + "1.0.0", + "linux", + &key, + Some(serde_json::json!({ + "identifies_gameplay": true, + "identifies_pauses": true, + "without_pause_detection": "disabled" + })), + ); + + let integrity = verify_package_directory(&package, &public_key).unwrap(); + let manifest_bytes = read_signed_manifest(&package, &integrity).unwrap(); + let manifest = Manifest::parse_json(&manifest_bytes).unwrap(); + assert!(manifest.manifest().playtime.identifies_gameplay); + assert!(manifest.manifest().playtime.identifies_pauses); + + let manifest_path = package.join("plugin.json"); + let mut edited: serde_json::Value = + serde_json::from_slice(&fs::read(&manifest_path).unwrap()).unwrap(); + edited["playtime"]["identifies_pauses"] = serde_json::Value::Bool(false); + fs::write(&manifest_path, serde_json::to_vec(&edited).unwrap()).unwrap(); + assert!(verify_package_directory(&package, &public_key).is_err()); + } + + #[tokio::test] + async fn incompatible_update_and_activation_leave_previous_version_active() { + let base = tempdir().unwrap(); + let registry = PluginPackageRegistry::at(base.path().join("registry")).unwrap(); + let lifecycle = ManagedPackageLifecycle::new(registry.clone()); + let key = ring::signature::Ed25519KeyPair::from_seed_unchecked(&[42; 32]).unwrap(); + let public_key: [u8; 32] = key.public_key().as_ref().try_into().unwrap(); + let v1 = base.path().join("v1"); + write_signed_package(&v1, "1.0.0", "linux", &key); + let installed = lifecycle + .install_candidate(&v1, public_key, EmulationPolicy::RequireNative, true) + .await + .unwrap(); + assert_eq!(installed.version, "1.0.0"); + + let v2 = base.path().join("v2"); + write_signed_package(&v2, "2.0.0", "windows", &key); + assert!(matches!( + lifecycle + .install_candidate(&v2, public_key, EmulationPolicy::RequireNative, true,) + .await, + Err(PackageLifecycleError::NoCompatibleTarget(_)) + )); + assert_eq!( + registry + .active("org.example.lifecycle") + .unwrap() + .unwrap() + .version, + "1.0.0" + ); + assert_eq!(registry.versions("org.example.lifecycle").unwrap().len(), 1); + + let v2 = base.path().join("v2"); + registry + .install_signed("org.example.lifecycle", "2.0.0", &v2, &public_key, false) + .unwrap(); + assert!(matches!( + lifecycle + .activate_version( + "org.example.lifecycle".into(), + "2.0.0".into(), + public_key, + EmulationPolicy::RequireNative, + ) + .await, + Err(PackageLifecycleError::NoCompatibleTarget(_)) + )); + assert_eq!( + registry + .active("org.example.lifecycle") + .unwrap() + .unwrap() + .version, + "1.0.0" + ); + } +} diff --git a/crates/app/src/plugin_host/migration.rs b/crates/app/src/plugin_host/migration.rs new file mode 100644 index 000000000..aad8f955a --- /dev/null +++ b/crates/app/src/plugin_host/migration.rs @@ -0,0 +1,1012 @@ +//! Reviewed migration of compatible data after a publisher key re-trust. +//! +//! A changed publisher fingerprint is a distinct security identity even after the user re-trusts +//! the new key. The owner namespace of the private store, the durable shared pool and the secret +//! slots all derive from that fingerprint, so old data stays isolated and inert. This module is the +//! host's administration of the one exception: an explicit, reviewed copy of *compatible* data +//! from the old identity to the new one. +//! +//! Nothing here is served over `ResourceHost`; there is no plugin RPC that can preview, apply, +//! cancel or roll back a migration, and a plugin never supplies an identity, owner key or path. +//! The old and new fingerprints come from the pinned package registry and the recorded trust +//! history. Secrets, activation grants, sharing policies and retention limits are never copied: +//! after a migration the new identity still needs its own current approvals. The source data is +//! never deleted, copies keep the original provenance and a reviewed rollback removes exactly the +//! copies a migration created. + +use std::collections::{BTreeMap, BTreeSet}; +use std::sync::{Arc, Mutex}; + +use gamenode_platform::plugin_shared_data::{ + MigrationOutcome, MigrationRevertOutcome, OwnerScope, RecordMetadata, +}; +use gamenode_platform::plugin_storage::{PrivateMigrationOutcome, PrivateMigrationRevert}; +use gamenode_plugin_protocol::proto::ExtensionSchemaDescriptor; +use sha2::{Digest, Sha256}; +use tonic::Status; + +use super::namespace::ExternalNamespaceResolver; +use super::publisher_trust::PublisherTrustStore; +use super::runtime::ThirdPartyPluginLifecycle; +use super::sharing_policy::SharingClass; + +/// Datasets the host itself serves. Their schema does not belong to the plugin package, so they +/// stay compatible regardless of the package's declared extension schemas. +const HOST_DATASETS: &[&str] = &[ + "storage.diagnostics.benchmark.v1", + "storage.diagnostics.smart.v1", + "computer.hardware.observations.v1", + "game.presence.v1", + "game.performance.history.v1", +]; + +const MAX_ISSUED_REVIEWS: usize = 8; +const MAX_REPORTED_SCHEMAS: usize = 16; + +/// One dataset of the old identity as the preview presents it. Values, field names, record ids and +/// paths are never included. +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PublisherMigrationDataset { + pub dataset_id: String, + pub records: u64, + pub eligible_records: u64, + pub eligible_bytes: u64, + pub conflict_records: u64, + pub incompatible_schema_records: u64, + /// Schema identifiers the new package no longer declares at a usable version, bounded. + pub incompatible_schema_ids: Vec, + pub logical_bytes: u64, +} + +/// The reviewed migration the user must confirm. The token is single-use and bound to the active +/// profile, its epoch and the exact old/new publisher identities. +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PublisherMigrationPreview { + pub token: String, + /// Stable identifier of this old/new/profile pair, used by a later reviewed rollback. + pub migration_id: String, + pub generated_at: i64, + pub plugin_id: String, + pub profile_id: String, + pub profile_epoch: u64, + pub source_publisher_fingerprint: String, + pub target_publisher_fingerprint: String, + /// Every other fingerprint the plugin was pinned to before the current key, oldest first. + pub historical_publisher_fingerprints: Vec, + + pub datasets: Vec, + pub shared_records: u64, + pub shared_eligible_records: u64, + pub shared_eligible_bytes: u64, + pub shared_conflict_records: u64, + pub shared_incompatible_schema_records: u64, + pub shared_archived_records: u64, + /// What the new identity already holds in the durable pool. + pub shared_target_records: u64, + pub shared_target_logical_bytes: u64, + + /// `false` when this host has no private data folder; the durable pool may still migrate. + pub private_store_available: bool, + pub private_records: u64, + pub private_eligible_records: u64, + pub private_eligible_bytes: u64, + pub private_conflict_records: u64, + pub private_expired_records: u64, + pub private_archived_records: u64, + pub private_protected_records: u64, + pub private_target_records: u64, + pub private_target_logical_bytes: u64, + + /// Credentials and approvals are never part of a migration. + pub secrets_excluded: bool, + pub grants_excluded: bool, + /// The new identity needs a fresh sharing review before any consumer can read its data. + pub sharing_review_required: bool, + /// Retention limits are per owner and are not copied. + pub retention_review_required: bool, + pub can_migrate: bool, +} + +/// One store's outcome in a migration or rollback report. +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PublisherMigrationStoreResult { + /// `durable_shared` or `private_persistence`. + pub store: String, + /// `completed`, `failed` or `unavailable`. + pub status: String, + pub copied_records: u64, + pub copied_bytes: u64, + pub conflict_records: u64, + pub skipped_over_quota_records: u64, + pub expired_records: u64, + pub archived_records: u64, + #[serde(skip_serializing_if = "Option::is_none")] + pub error: Option, +} + +/// The measured result of one confirmed migration. A partial failure is reported per store and +/// leaves the other store's result intact; the token cannot be reused after a failure. +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PublisherMigrationReport { + pub token: String, + pub migration_id: String, + pub plugin_id: String, + pub profile_id: String, + pub source_publisher_fingerprint: String, + pub target_publisher_fingerprint: String, + pub results: Vec, + pub copied_records: u64, + pub copied_bytes: u64, + pub conflict_records: u64, + pub skipped_over_quota_records: u64, + pub incompatible_schema_records: u64, + pub secrets_excluded: bool, + pub grants_excluded: bool, + pub sharing_review_required: bool, + pub retention_review_required: bool, +} + +/// One store's outcome in a rollback report. +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PublisherMigrationRollbackStoreResult { + pub store: String, + /// `completed`, `failed` or `unavailable`. + pub status: String, + pub removed_records: u64, + pub reclaimed_bytes: u64, + pub kept_protected_records: u64, + #[serde(skip_serializing_if = "Option::is_none")] + pub error: Option, +} + +/// The measured result of removing one migration's copies. The old identity's data stays. +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PublisherMigrationRollbackReport { + pub migration_id: String, + pub plugin_id: String, + pub profile_id: String, + pub source_publisher_fingerprint: String, + pub target_publisher_fingerprint: String, + pub results: Vec, + pub removed_records: u64, + pub reclaimed_bytes: u64, + pub kept_protected_records: u64, +} + +#[derive(Clone)] +struct ReviewedMigration { + token: String, + migration_id: String, + plugin_id: String, + profile_id: String, + profile_epoch: u64, + source_fingerprint: String, + target_fingerprint: String, + source_owner_key: [u8; 32], + target_owner_key: [u8; 32], +} + +/// Single-use migration previews. Older previews are dropped first, so a settings surface cannot +/// grow unbounded state. +#[derive(Default)] +pub struct MigrationReviews { + issued: Mutex>, +} + +impl MigrationReviews { + fn issue(&self, review: ReviewedMigration) { + let mut issued = self.issued.lock().unwrap_or_else(|p| p.into_inner()); + issued.push(review); + if issued.len() > MAX_ISSUED_REVIEWS { + issued.remove(0); + } + } + + fn get(&self, token: &str) -> Option { + self.issued + .lock() + .unwrap_or_else(|p| p.into_inner()) + .iter() + .find(|review| review.token == token) + .cloned() + } + + fn take(&self, token: &str) -> Option { + let mut issued = self.issued.lock().unwrap_or_else(|p| p.into_inner()); + let index = issued.iter().position(|review| review.token == token)?; + Some(issued.remove(index)) + } +} + +/// Stable identifier for one old/new/profile migration pair. It carries no key material: the +/// fingerprints are already the user-visible SHA-256 of a public key, and the digest only binds the +/// values. +fn migration_id( + plugin_id: &str, + source_fingerprint: &str, + target_fingerprint: &str, + profile_id: &str, +) -> String { + let mut digest = Sha256::new(); + digest.update(b"gamenode.publisher-migration.v1\0"); + for part in [ + plugin_id, + source_fingerprint, + target_fingerprint, + profile_id, + ] { + digest.update((part.len() as u64).to_be_bytes()); + digest.update(part.as_bytes()); + } + digest + .finalize() + .iter() + .map(|byte| format!("{byte:02x}")) + .collect() +} + +/// Why a stored record cannot be carried to the new package. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum SchemaVerdict { + Compatible, + ForeignOrUndeclared, + OlderDeclaredVersion, +} + +/// Decides whether the new package can still use one stored record's schema. +/// +/// A schema the package declares is compatible when the declared version is at least the stored +/// one; a record at a newer schema version is not copied into code that cannot read it. An +/// undeclared schema is still compatible when the host serves that dataset itself or when the +/// schema belongs to the plugin's own reverse-domain namespace, because the package owns that +/// namespace. Anything else cannot be proven compatible and is reported instead of copied. +fn schema_verdict( + plugin_id: &str, + record: &RecordMetadata, + declared: &[ExtensionSchemaDescriptor], +) -> SchemaVerdict { + let mut matching = declared + .iter() + .filter(|descriptor| descriptor.schema_id == record.schema_id) + .peekable(); + if matching.peek().is_some() { + return if matching.any(|descriptor| descriptor.schema_version >= record.schema_version) { + SchemaVerdict::Compatible + } else { + SchemaVerdict::OlderDeclaredVersion + }; + } + let owned = record.schema_id == plugin_id + || record + .schema_id + .strip_prefix(plugin_id) + .is_some_and(|rest| rest.starts_with('.')); + if owned || HOST_DATASETS.contains(&record.schema_id.as_str()) { + SchemaVerdict::Compatible + } else { + SchemaVerdict::ForeignOrUndeclared + } +} + +fn record_compatible( + plugin_id: &str, + record: &RecordMetadata, + declared: &[ExtensionSchemaDescriptor], +) -> bool { + SharingClass::from_name(&record.class).is_some() + && schema_verdict(plugin_id, record, declared) == SchemaVerdict::Compatible +} + +fn empty_migration_outcome() -> MigrationOutcome { + MigrationOutcome { + copied: Vec::new(), + skipped: Vec::new(), + pool_revision: 0, + } +} + +/// The old/new identities and the active package's declared schemas for one plugin. +struct ActivePublisher { + source_fingerprint: String, + target_fingerprint: String, + prior_fingerprints: Vec, + declared_schemas: Vec, +} + +impl ThirdPartyPluginLifecycle { + /// Previews the data a re-trusted publisher identity could inherit from its predecessor. + pub async fn publisher_migration_preview( + &self, + plugin_id: String, + ) -> Result { + let now = unix_now()?; + self.publisher_migration_preview_at(plugin_id, now).await + } + + /// Applies one confirmed, single-use migration preview. An unconfirmed or stale call changes + /// nothing. + pub async fn publisher_migration_apply( + &self, + token: String, + expected_profile_id: String, + confirmed: bool, + ) -> Result { + let now = unix_now()?; + self.publisher_migration_apply_at(token, expected_profile_id, confirmed, now) + .await + } + + /// Discards one preview. No data was changed by the preview, so a later apply cannot proceed + /// with the cancelled token. + pub async fn publisher_migration_cancel(&self, token: String) -> Result<(), Status> { + self.migration_reviews() + .take(&token) + .map(|_| ()) + .ok_or_else(|| Status::failed_precondition("migration review expired or was used")) + } + + /// Removes the copies one migration created from the new publisher identity. The old identity + /// keeps its data. Only a pair this host recorded in the trust history can match. + pub async fn publisher_migration_rollback( + &self, + plugin_id: String, + reviewed_migration_id: String, + expected_profile_id: String, + confirmed: bool, + ) -> Result { + if !confirmed { + return Err(Status::failed_precondition( + "rolling back a data migration requires confirmation", + )); + } + let profile = self.host_api().profiles().require()?; + if profile.profile_id() != expected_profile_id { + return Err(Status::failed_precondition("plugin profile changed")); + } + let now = unix_now()?; + let publisher = self.active_publisher(&plugin_id).await?; + let Some(source_fingerprint) = publisher.prior_fingerprints.iter().rev().find(|prior| { + reviewed_migration_id + == migration_id( + &plugin_id, + prior, + &publisher.target_fingerprint, + profile.profile_id(), + ) + }) else { + return Err(Status::failed_precondition( + "no reviewed migration matches this identity and profile", + )); + }; + let source_fingerprint = source_fingerprint.clone(); + let target_resolver = + self.host_api() + .profiles() + .resolver(&plugin_id, &publisher.target_fingerprint, None)?; + let target_owner = scope(&target_resolver, profile.epoch())?; + + let mut results = Vec::new(); + let mut removed_records = 0_u64; + let mut reclaimed_bytes = 0_u64; + let mut kept_protected_records = 0_u64; + if let Some(storage) = self.private_storage() { + match storage + .revert_publisher_migration(&target_resolver, source_fingerprint.clone()) + .await + { + Ok(outcome) => { + let outcome = outcome.unwrap_or_default(); + removed_records = removed_records.saturating_add(outcome.removed_records); + reclaimed_bytes = reclaimed_bytes.saturating_add(outcome.reclaimed_bytes); + kept_protected_records = + kept_protected_records.saturating_add(outcome.kept_protected_records); + results.push(rollback_result("private_persistence", outcome)); + } + Err(error) => results.push(failed_rollback_result("private_persistence", error)), + } + } else { + results.push(unavailable_rollback_result("private_persistence")); + } + + let pool = self.host_api().shared_pool(); + match pool + .revert_migrated_owner( + target_owner, + source_fingerprint.clone(), + plugin_id.clone(), + now, + ) + .await + { + Ok(outcome) => { + let outcome = outcome.unwrap_or_else(empty_revert); + removed_records = removed_records.saturating_add(outcome.removed_records); + reclaimed_bytes = reclaimed_bytes.saturating_add(outcome.reclaimed_bytes); + kept_protected_records = + kept_protected_records.saturating_add(outcome.kept_protected_records); + results.push(PublisherMigrationRollbackStoreResult { + store: "durable_shared".to_owned(), + status: "completed".to_owned(), + removed_records: outcome.removed_records, + reclaimed_bytes: outcome.reclaimed_bytes, + kept_protected_records: outcome.kept_protected_records, + error: None, + }); + } + Err(error) => results.push(PublisherMigrationRollbackStoreResult { + store: "durable_shared".to_owned(), + status: "failed".to_owned(), + removed_records: 0, + reclaimed_bytes: 0, + kept_protected_records: 0, + error: Some(error.message().to_owned()), + }), + } + + tracing::info!( + migration_id = %reviewed_migration_id, + plugin = %plugin_id, + removed_records, + reclaimed_bytes, + "reviewed publisher migration rollback completed" + ); + Ok(PublisherMigrationRollbackReport { + migration_id: reviewed_migration_id, + plugin_id, + profile_id: profile.profile_id().to_owned(), + source_publisher_fingerprint: source_fingerprint, + target_publisher_fingerprint: publisher.target_fingerprint, + results, + removed_records, + reclaimed_bytes, + kept_protected_records, + }) + } + + /// The old/new identity pair of one plugin in the active profile, from the pinned registry and + /// the recorded trust history. A plugin RPC never supplies either value. + async fn active_publisher(&self, plugin_id: &str) -> Result { + let api = self.host_api(); + let provider_ids = api.third_party_provider_ids_for_plugin(plugin_id); + let [provider_id] = provider_ids.as_slice() else { + return Err(Status::failed_precondition( + "third-party plugin has no unique registered provider", + )); + }; + let (registered_id, target_fingerprint) = + api.third_party_identity(provider_id).ok_or_else(|| { + Status::failed_precondition("third-party plugin identity is unavailable") + })?; + if registered_id != plugin_id { + return Err(Status::failed_precondition( + "registered plugin identity changed", + )); + } + let declared_schemas = api.extension_schemas_for_provider(provider_id); + let trust_dir = self.trust_dir(); + let trust_plugin = plugin_id.to_owned(); + let prior_fingerprints = tokio::task::spawn_blocking(move || { + let trust = PublisherTrustStore::open(trust_dir).map_err(|error| error.to_string())?; + Ok::<_, String>(trust.prior_fingerprints(&trust_plugin)) + }) + .await + .map_err(|_| Status::internal("publisher trust worker failed"))? + .map_err(|error| Status::unavailable(format!("publisher trust store: {error}")))?; + let Some(source_fingerprint) = prior_fingerprints + .iter() + .rev() + .find(|prior| *prior != &target_fingerprint) + .cloned() + else { + return Err(Status::failed_precondition( + "no previous publisher key is recorded for this plugin", + )); + }; + Ok(ActivePublisher { + source_fingerprint, + target_fingerprint, + prior_fingerprints, + declared_schemas, + }) + } + + pub(crate) async fn publisher_migration_preview_at( + &self, + plugin_id: String, + now: i64, + ) -> Result { + let profile = self.host_api().profiles().require()?; + let profile_id = profile.profile_id().to_owned(); + let profile_epoch = profile.epoch(); + let publisher = self.active_publisher(&plugin_id).await?; + let source_resolver = + self.host_api() + .profiles() + .resolver(&plugin_id, &publisher.source_fingerprint, None)?; + let target_resolver = + self.host_api() + .profiles() + .resolver(&plugin_id, &publisher.target_fingerprint, None)?; + let source_owner = scope(&source_resolver, profile_epoch)?; + let target_owner = scope(&target_resolver, profile_epoch)?; + let migration_id = migration_id( + &plugin_id, + &publisher.source_fingerprint, + &publisher.target_fingerprint, + &profile_id, + ); + + let pool = self.host_api().shared_pool(); + let source = pool.migration_source(source_owner, now).await?; + let target_usage = pool.usage(target_owner, now).await?; + let target_pairs = match pool.migration_source(target_owner, now).await? { + Some(target_source) => target_source + .records + .into_iter() + .filter_map(|record| { + record + .resource_id + .map(|resource| (record.dataset_id, resource)) + }) + .collect::>(), + None => BTreeSet::new(), + }; + + let mut datasets: BTreeMap = BTreeMap::new(); + let mut shared_records = 0_u64; + let mut shared_eligible_records = 0_u64; + let mut shared_eligible_bytes = 0_u64; + let mut shared_conflict_records = 0_u64; + let mut shared_incompatible_schema_records = 0_u64; + let mut shared_archived_records = 0_u64; + if let Some(source) = source { + shared_archived_records = source.archived_records; + for record in source.records { + let entry = datasets + .entry(record.dataset_id.clone()) + .or_insert_with(|| PublisherMigrationDataset { + dataset_id: record.dataset_id.clone(), + records: 0, + eligible_records: 0, + eligible_bytes: 0, + conflict_records: 0, + incompatible_schema_records: 0, + incompatible_schema_ids: Vec::new(), + logical_bytes: 0, + }); + entry.records += 1; + entry.logical_bytes = entry.logical_bytes.saturating_add(record.size_bytes); + shared_records += 1; + if !record_compatible(&plugin_id, &record, &publisher.declared_schemas) { + entry.incompatible_schema_records += 1; + shared_incompatible_schema_records += 1; + if entry.incompatible_schema_ids.len() < MAX_REPORTED_SCHEMAS + && !entry.incompatible_schema_ids.contains(&record.schema_id) + { + entry.incompatible_schema_ids.push(record.schema_id); + } + continue; + } + let conflict = record.resource_id.as_ref().is_some_and(|resource| { + target_pairs.contains(&(record.dataset_id.clone(), resource.clone())) + }); + if conflict { + entry.conflict_records += 1; + shared_conflict_records += 1; + continue; + } + entry.eligible_records += 1; + entry.eligible_bytes = entry.eligible_bytes.saturating_add(record.size_bytes); + shared_eligible_records += 1; + shared_eligible_bytes = shared_eligible_bytes.saturating_add(record.size_bytes); + } + } + + let private = match self.private_storage() { + Some(storage) => Some( + storage + .publisher_migration_preview(&source_resolver, &target_resolver) + .await?, + ), + None => None, + }; + let private_store_available = private.is_some(); + let private = private.flatten().unwrap_or_default(); + + let can_migrate = shared_eligible_records > 0 || private.eligible_records > 0; + let token = gamenode_platform::random::nonce(); + self.migration_reviews().issue(ReviewedMigration { + token: token.clone(), + migration_id: migration_id.clone(), + plugin_id: plugin_id.clone(), + profile_id: profile_id.clone(), + profile_epoch, + source_fingerprint: publisher.source_fingerprint.clone(), + target_fingerprint: publisher.target_fingerprint.clone(), + source_owner_key: *source_resolver.storage_owner().key(), + target_owner_key: *target_resolver.storage_owner().key(), + }); + Ok(PublisherMigrationPreview { + token, + migration_id, + generated_at: now, + plugin_id, + profile_id, + profile_epoch, + source_publisher_fingerprint: publisher.source_fingerprint, + target_publisher_fingerprint: publisher.target_fingerprint, + historical_publisher_fingerprints: publisher.prior_fingerprints, + datasets: datasets.into_values().collect(), + shared_records, + shared_eligible_records, + shared_eligible_bytes, + shared_conflict_records, + shared_incompatible_schema_records, + shared_archived_records, + shared_target_records: target_usage.as_ref().map_or(0, |usage| usage.records), + shared_target_logical_bytes: target_usage + .as_ref() + .map_or(0, |usage| usage.logical_bytes), + private_store_available, + private_records: private.records, + private_eligible_records: private.eligible_records, + private_eligible_bytes: private.eligible_bytes, + private_conflict_records: private.conflict_records, + private_expired_records: private.expired_records, + private_archived_records: private.archived_records, + private_protected_records: private.protected_records, + private_target_records: private.target_records, + private_target_logical_bytes: private.target_logical_bytes, + secrets_excluded: true, + grants_excluded: true, + sharing_review_required: true, + retention_review_required: true, + can_migrate, + }) + } + + pub(crate) async fn publisher_migration_apply_at( + &self, + token: String, + expected_profile_id: String, + confirmed: bool, + now: i64, + ) -> Result { + if !confirmed { + return Err(Status::failed_precondition( + "a reviewed data migration requires confirmation", + )); + } + let review = self + .migration_reviews() + .get(&token) + .ok_or_else(|| Status::failed_precondition("migration review expired or was used"))?; + let profile = self.host_api().profiles().require()?; + if profile.profile_id() != expected_profile_id + || profile.profile_id() != review.profile_id + || profile.epoch() != review.profile_epoch + { + return Err(Status::failed_precondition( + "the account profile changed; create a new migration review", + )); + } + let publisher = self.active_publisher(&review.plugin_id).await?; + if publisher.target_fingerprint != review.target_fingerprint + || publisher.source_fingerprint != review.source_fingerprint + { + return Err(Status::failed_precondition( + "plugin identity changed since the migration review", + )); + } + if migration_id( + &review.plugin_id, + &review.source_fingerprint, + &review.target_fingerprint, + profile.profile_id(), + ) != review.migration_id + { + return Err(Status::failed_precondition( + "migration review does not match the active identity", + )); + } + let source_resolver = self.host_api().profiles().resolver( + &review.plugin_id, + &review.source_fingerprint, + None, + )?; + let target_resolver = self.host_api().profiles().resolver( + &review.plugin_id, + &review.target_fingerprint, + None, + )?; + let source_owner = scope(&source_resolver, profile.epoch())?; + let target_owner = scope(&target_resolver, profile.epoch())?; + if *source_resolver.storage_owner().key() != review.source_owner_key + || *target_resolver.storage_owner().key() != review.target_owner_key + { + return Err(Status::failed_precondition( + "plugin identity changed since the migration review", + )); + } + + let mut results = Vec::new(); + let mut copied_records = 0_u64; + let mut copied_bytes = 0_u64; + let mut conflict_records = 0_u64; + let mut skipped_over_quota_records = 0_u64; + let mut incompatible_schema_records = 0_u64; + + if let Some(storage) = self.private_storage() { + match storage + .migrate_publisher_data(&source_resolver, &target_resolver) + .await + { + Ok(outcome) => { + let outcome = private_completed(&mut results, outcome); + copied_records = copied_records.saturating_add(outcome.copied_records); + copied_bytes = copied_bytes.saturating_add(outcome.copied_bytes); + conflict_records = conflict_records.saturating_add(outcome.conflict_records); + } + Err(error) => { + results.push(failed_store_result("private_persistence", error.message())) + } + } + } else { + results.push(PublisherMigrationStoreResult { + store: "private_persistence".to_owned(), + status: "unavailable".to_owned(), + copied_records: 0, + copied_bytes: 0, + conflict_records: 0, + skipped_over_quota_records: 0, + expired_records: 0, + archived_records: 0, + error: Some("private plugin data is unavailable on this host".to_owned()), + }); + } + + // The compatible set is recomputed against the live source so a record that appeared or + // changed since the preview is not copied blindly. + let pool = self.host_api().shared_pool(); + let source = pool.migration_source(source_owner, now).await?; + match source { + None => results.push(shared_store_result(&empty_migration_outcome())), + Some(source) => { + let mut compatible_ids = Vec::new(); + for record in &source.records { + if record_compatible(&review.plugin_id, record, &publisher.declared_schemas) { + compatible_ids.push(record.record_id.clone()); + } else { + incompatible_schema_records += 1; + } + } + match pool + .migrate_owner(source_owner, target_owner, compatible_ids, now) + .await + { + Ok(outcome) => { + let outcome = outcome.unwrap_or_else(empty_migration_outcome); + let result = shared_store_result(&outcome); + copied_records = copied_records.saturating_add(result.copied_records); + copied_bytes = copied_bytes.saturating_add(result.copied_bytes); + conflict_records = conflict_records.saturating_add(result.conflict_records); + skipped_over_quota_records = skipped_over_quota_records + .saturating_add(result.skipped_over_quota_records); + results.push(result); + } + Err(error) => { + results.push(failed_store_result("durable_shared", error.message())) + } + } + } + } + + // Single use: even a partial failure consumes the reviewed snapshot and needs a new + // preview for a retry. + self.migration_reviews().take(&token); + tracing::info!( + %token, + plugin = %review.plugin_id, + source = %review.source_fingerprint, + target = %review.target_fingerprint, + copied_records, + copied_bytes, + "reviewed publisher data migration completed" + ); + Ok(PublisherMigrationReport { + token, + migration_id: review.migration_id, + plugin_id: review.plugin_id, + profile_id: review.profile_id, + source_publisher_fingerprint: review.source_fingerprint, + target_publisher_fingerprint: review.target_fingerprint, + results, + copied_records, + copied_bytes, + conflict_records, + skipped_over_quota_records, + incompatible_schema_records, + secrets_excluded: true, + grants_excluded: true, + sharing_review_required: true, + retention_review_required: true, + }) + } +} + +fn scope(resolver: &ExternalNamespaceResolver, profile_epoch: u64) -> Result { + OwnerScope::new(*resolver.storage_owner().key(), profile_epoch) + .map_err(|_| Status::failed_precondition("plugin profile is invalid")) +} + +fn private_completed( + results: &mut Vec, + outcome: PrivateMigrationOutcome, +) -> PrivateMigrationOutcome { + results.push(PublisherMigrationStoreResult { + store: "private_persistence".to_owned(), + status: "completed".to_owned(), + copied_records: outcome.copied_records, + copied_bytes: outcome.copied_bytes, + conflict_records: outcome.conflict_records, + skipped_over_quota_records: 0, + expired_records: outcome.expired_records, + archived_records: outcome.archived_records, + error: None, + }); + outcome +} + +fn shared_store_result(outcome: &MigrationOutcome) -> PublisherMigrationStoreResult { + let conflicts = outcome + .skipped + .iter() + .filter(|skip| skip.reason == "conflict") + .count() as u64; + PublisherMigrationStoreResult { + store: "durable_shared".to_owned(), + status: "completed".to_owned(), + copied_records: outcome.copied.len() as u64, + copied_bytes: outcome.copied.iter().map(|record| record.size_bytes).sum(), + conflict_records: conflicts, + skipped_over_quota_records: outcome + .skipped + .iter() + .filter(|skip| skip.reason == "over_quota") + .count() as u64, + expired_records: 0, + archived_records: 0, + error: None, + } +} + +fn failed_store_result(store: &str, error: &str) -> PublisherMigrationStoreResult { + PublisherMigrationStoreResult { + store: store.to_owned(), + status: "failed".to_owned(), + copied_records: 0, + copied_bytes: 0, + conflict_records: 0, + skipped_over_quota_records: 0, + expired_records: 0, + archived_records: 0, + error: Some(error.to_owned()), + } +} + +fn rollback_result( + store: &str, + outcome: PrivateMigrationRevert, +) -> PublisherMigrationRollbackStoreResult { + PublisherMigrationRollbackStoreResult { + store: store.to_owned(), + status: "completed".to_owned(), + removed_records: outcome.removed_records, + reclaimed_bytes: outcome.reclaimed_bytes, + kept_protected_records: outcome.kept_protected_records, + error: None, + } +} + +fn failed_rollback_result(store: &str, error: Status) -> PublisherMigrationRollbackStoreResult { + PublisherMigrationRollbackStoreResult { + store: store.to_owned(), + status: "failed".to_owned(), + removed_records: 0, + reclaimed_bytes: 0, + kept_protected_records: 0, + error: Some(error.message().to_owned()), + } +} + +fn unavailable_rollback_result(store: &str) -> PublisherMigrationRollbackStoreResult { + PublisherMigrationRollbackStoreResult { + store: store.to_owned(), + status: "unavailable".to_owned(), + removed_records: 0, + reclaimed_bytes: 0, + kept_protected_records: 0, + error: Some("private plugin data is unavailable on this host".to_owned()), + } +} + +fn empty_revert() -> MigrationRevertOutcome { + MigrationRevertOutcome { + removed_records: 0, + reclaimed_bytes: 0, + kept_protected_records: 0, + pool_revision: 0, + } +} + +fn unix_now() -> Result { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|elapsed| elapsed.as_secs().max(1) as i64) + .map_err(|_| Status::failed_precondition("the system clock is before the Unix epoch")) +} + +/// Previews the compatible data a re-trusted publisher identity could inherit. Host administration +/// only: this is a Tauri command, never a plugin RPC. +#[tauri::command] +pub async fn plugin_publisher_migration_preview( + lifecycle: tauri::State<'_, Arc>, + plugin_id: String, +) -> Result { + lifecycle + .publisher_migration_preview(plugin_id) + .await + .map_err(|error| error.message().to_owned()) +} + +/// Applies one confirmed, single-use migration preview. An unconfirmed, cancelled or stale call +/// changes nothing. +#[tauri::command] +pub async fn plugin_publisher_migration_apply( + lifecycle: tauri::State<'_, Arc>, + token: String, + expected_profile_id: String, + confirmed: bool, +) -> Result { + lifecycle + .publisher_migration_apply(token, expected_profile_id, confirmed) + .await + .map_err(|error| error.message().to_owned()) +} + +/// Discards one migration preview without changing data. +#[tauri::command] +pub async fn plugin_publisher_migration_cancel( + lifecycle: tauri::State<'_, Arc>, + token: String, +) -> Result<(), String> { + lifecycle + .publisher_migration_cancel(token) + .await + .map_err(|error| error.message().to_owned()) +} + +/// Removes one migration's copies from the new publisher identity after an explicit confirmation. +/// The old identity keeps its data. +#[tauri::command] +pub async fn plugin_publisher_migration_rollback( + lifecycle: tauri::State<'_, Arc>, + plugin_id: String, + migration_id: String, + expected_profile_id: String, + confirmed: bool, +) -> Result { + lifecycle + .publisher_migration_rollback(plugin_id, migration_id, expected_profile_id, confirmed) + .await + .map_err(|error| error.message().to_owned()) +} + +#[cfg(test)] +mod tests; diff --git a/crates/app/src/plugin_host/migration/tests.rs b/crates/app/src/plugin_host/migration/tests.rs new file mode 100644 index 000000000..b34621779 --- /dev/null +++ b/crates/app/src/plugin_host/migration/tests.rs @@ -0,0 +1,696 @@ +use std::path::PathBuf; +use std::sync::Arc; + +use gamenode_platform::plugin_shared_data::{OwnerScope, RecordProvenance}; +use gamenode_platform::plugin_storage::{DurableStore, QUOTA_BYTES, namespace_dir}; +use gamenode_plugin_protocol::capability as cap; +use gamenode_plugin_protocol::proto::{ + ExtensionFieldClassification, ExtensionSchemaDescriptor, ExtensionSchemaField, +}; +use sha2::Digest; + +use crate::plugin_host::grants::{ + GrantScope, PermissionDecision, PermissionRequest, PluginIdentity, +}; +use crate::plugin_host::publisher_trust::{PublisherTrustStore, key_fingerprint}; +use crate::plugin_host::runtime::ThirdPartyPluginLifecycle; +use crate::plugin_host::shared_pool::DurableWrite; +use crate::plugin_host::{ + PluginApi, + provider::{ExtensionServices, Registration, RegistrationKind, RegistrationOrigin}, +}; + +const PLUGIN: &str = "org.example.plugin"; +const PROVIDER: &str = "provider-one"; +const DATASET: &str = "org.example.plugin.catalog"; +const SCHEMA: &str = "org.example.plugin.catalog.v1"; + +struct Fixture { + dir: tempfile::TempDir, + root: PluginApi, + state: crate::plugin_host::profile::PluginStateLayout, + registry: gamenode_platform::plugin_registry::PluginPackageRegistry, + old_fingerprint: String, + new_fingerprint: String, +} + +impl Fixture { + async fn new() -> Self { + let dir = tempfile::tempdir().unwrap(); + let data_dir = dir.path().join("app-data"); + std::fs::create_dir_all(&data_dir).unwrap(); + let root = PluginApi { + shared_pool: Arc::new(crate::plugin_host::shared_pool::DurableSharedPool::new( + &data_dir, + )), + storage: Arc::new(crate::plugin_host::storage::PluginStorage::new( + dir.path().join("plugin-data"), + )), + ..Default::default() + }; + let state = crate::plugin_host::profile::PluginStateLayout::new(dir.path().join("state")); + std::fs::create_dir_all(dir.path().join("state")).unwrap(); + root.set_state_layout(state.clone()); + root.providers.profiles().update(Some("account-one"), true); + let registry = gamenode_platform::plugin_registry::PluginPackageRegistry::at( + dir.path().join("registry"), + ) + .unwrap(); + let old_key = [1; 32]; + let new_key = [2; 32]; + let old_fingerprint = key_fingerprint(&old_key); + let new_fingerprint = key_fingerprint(&new_key); + // The user re-trusted a changed publisher key: the trust store records the replaced key + // and the registry now holds the new identity. + { + let mut trust = PublisherTrustStore::open(state.trust_dir()).unwrap(); + trust + .confirm_first_key(PLUGIN, &old_key, &old_fingerprint) + .unwrap(); + trust + .retrust_key(PLUGIN, &new_key, &new_fingerprint) + .unwrap(); + } + let fixture = Self { + dir, + root, + state, + registry, + old_fingerprint, + new_fingerprint, + }; + fixture.register(&fixture.new_fingerprint); + fixture.declare_schemas(); + fixture + } + + fn register(&self, fingerprint: &str) { + self.root + .providers + .register(Registration { + provider_id: PROVIDER.into(), + plugin_id: PLUGIN.into(), + declared_developer: "Example Developer".into(), + package_digest: vec![7; 32], + kind: RegistrationKind::Provider, + origin: RegistrationOrigin::ThirdParty { + publisher_fingerprint: fingerprint.to_owned(), + }, + capabilities: vec![cap::CONTEXT.into()], + shared_catalog: false, + playtime: Default::default(), + services: Arc::new(ExtensionServices), + }) + .unwrap(); + } + + fn declare_schemas(&self) { + self.root + .providers + .set_extension_schemas(PROVIDER, PLUGIN, &self.new_fingerprint, vec![descriptor(1)]) + .unwrap(); + } + + fn lifecycle(&self) -> ThirdPartyPluginLifecycle { + self.lifecycle_with_private(true) + } + + fn lifecycle_without_private(&self) -> ThirdPartyPluginLifecycle { + self.lifecycle_with_private(false) + } + + fn lifecycle_with_private(&self, private: bool) -> ThirdPartyPluginLifecycle { + let processes = crate::plugin_host::process::ProviderProcesses::new_for_lifecycle( + self.root.providers.clone(), + self.dir.path().join("plugins.sock"), + vec![], + self.state.clone(), + ) + .unwrap(); + let lifecycle = ThirdPartyPluginLifecycle::new( + self.root.providers.clone(), + processes, + self.state.clone(), + self.registry.clone(), + crate::plugin_host::managed_packages::ManagedPackageLifecycle::new( + self.registry.clone(), + ), + ); + if private { + lifecycle.set_private_storage(self.root.storage.clone()); + } + lifecycle + } + + fn profile_id(&self) -> String { + self.root + .providers + .profiles() + .require() + .unwrap() + .profile_id() + .to_owned() + } + + fn owner(&self, fingerprint: &str) -> OwnerScope { + let resolver = self + .root + .providers + .profiles() + .resolver(PLUGIN, fingerprint, None) + .unwrap(); + OwnerScope::new( + *resolver.storage_owner().key(), + self.root.providers.profiles().require().unwrap().epoch(), + ) + .unwrap() + } + + fn private_dir(&self, fingerprint: &str) -> PathBuf { + namespace_dir( + &self.dir.path().join("plugin-data"), + fingerprint, + PLUGIN, + &self.profile_id(), + ) + } + + fn write_private(&self, fingerprint: &str, key: &str, value: &[u8]) { + let mut store = DurableStore::open(&self.private_dir(fingerprint)).unwrap(); + store.put(key, value, 1, None, 100, QUOTA_BYTES).unwrap(); + } + + async fn publish( + &self, + fingerprint: &str, + dataset: &str, + resource: &str, + schema_id: &str, + schema_version: u32, + ) -> String { + let record = self + .root + .shared_pool + .persist(DurableWrite { + owner: self.owner(fingerprint), + dataset_id: dataset.to_owned(), + schema_id: schema_id.to_owned(), + schema_version, + fields_json: format!(r#"{{"title":"{resource}"}}"#), + opaque_payload: Vec::new(), + resource_id: Some(resource.to_owned()), + observed_at: 100, + sequence: 1, + source_observation_id: format!("observation-{resource}"), + expires_at: None, + now: 100, + provenance: RecordProvenance { + source_plugin_id: PLUGIN.to_owned(), + source_publisher_fingerprint: fingerprint.to_owned(), + source_profile_id: self.profile_id(), + declared_developer: "Example Developer".to_owned(), + origin: "registry".to_owned(), + package_version: "1.0.0".to_owned(), + package_digest: vec![7; 32], + }, + }) + .await + .unwrap(); + record.record_id + } + + async fn seed_old_identity(&self) { + self.write_private(&self.old_fingerprint, "settings", b"old"); + self.publish(&self.old_fingerprint, DATASET, "disc-1", SCHEMA, 1) + .await; + self.publish( + &self.old_fingerprint, + "com.other.data", + "foreign-1", + "com.other.data.v1", + 1, + ) + .await; + } + + fn grant_storage_persist(&self, fingerprint: &str) { + let profile = self.root.providers.profiles().require().unwrap(); + let mut grants = self.state.open_grants(&profile).unwrap(); + grants + .replace_grants( + PluginIdentity { + plugin_id: PLUGIN.into(), + publisher_fingerprint: fingerprint.to_owned(), + profile_id: profile.profile_id().to_owned(), + }, + &[PermissionRequest { + permission_id: cap::STORAGE_PERSIST.into(), + required: true, + allowed_scopes: [GrantScope::OwnPrivateNamespace].into_iter().collect(), + }], + &[PermissionDecision { + permission_id: cap::STORAGE_PERSIST.into(), + scope: GrantScope::OwnPrivateNamespace, + granted: true, + }], + ) + .unwrap(); + } + + async fn target_records(&self) -> u64 { + self.root + .shared_pool + .usage(self.owner(&self.new_fingerprint), 100) + .await + .unwrap() + .map_or(0, |usage| usage.records) + } +} + +fn descriptor(version: u32) -> ExtensionSchemaDescriptor { + let schema_json = br#"{"type":"object","properties":{"title":{"type":"string"}}}"#.to_vec(); + ExtensionSchemaDescriptor { + namespace: "org.example.plugin".into(), + schema_id: SCHEMA.into(), + schema_version: version, + schema_digest: sha2::Sha256::digest(&schema_json).to_vec(), + schema_json, + fields: vec![ExtensionSchemaField { + path: "title".into(), + classification: ExtensionFieldClassification::Public as i32, + }], + optional: true, + } +} + +#[tokio::test] +async fn preview_reports_compatible_data_and_changes_nothing() { + let fixture = Fixture::new().await; + fixture.seed_old_identity().await; + let lifecycle = fixture.lifecycle(); + + let preview = lifecycle + .publisher_migration_preview_at(PLUGIN.to_owned(), 100) + .await + .unwrap(); + assert_eq!(preview.plugin_id, PLUGIN); + assert_eq!(preview.profile_id, fixture.profile_id()); + assert_eq!( + preview.source_publisher_fingerprint, + fixture.old_fingerprint + ); + assert_eq!( + preview.target_publisher_fingerprint, + fixture.new_fingerprint + ); + assert_eq!( + preview.historical_publisher_fingerprints, + vec![fixture.old_fingerprint.clone()] + ); + assert_eq!(preview.shared_records, 2); + assert_eq!(preview.shared_eligible_records, 1); + assert_eq!(preview.shared_conflict_records, 0); + assert_eq!(preview.shared_incompatible_schema_records, 1); + assert_eq!(preview.shared_target_records, 0); + assert_eq!(preview.private_records, 1); + assert_eq!(preview.private_eligible_records, 1); + assert!(preview.private_eligible_bytes > 0); + assert!(preview.private_store_available); + assert!(preview.can_migrate); + assert!(preview.secrets_excluded); + assert!(preview.grants_excluded); + assert!(preview.sharing_review_required); + assert!(preview.retention_review_required); + let dataset = preview + .datasets + .iter() + .find(|dataset| dataset.dataset_id == DATASET) + .unwrap(); + assert_eq!(dataset.eligible_records, 1); + let foreign = preview + .datasets + .iter() + .find(|dataset| dataset.dataset_id == "com.other.data") + .unwrap(); + assert_eq!(foreign.incompatible_schema_records, 1); + assert_eq!(foreign.incompatible_schema_ids, vec!["com.other.data.v1"]); + assert!(!preview.token.is_empty()); + + // A preview never writes: the new identity has nothing and the old identity keeps everything. + assert_eq!(fixture.target_records().await, 0); + assert!(!fixture.private_dir(&fixture.new_fingerprint).exists()); + assert_eq!( + fixture + .root + .shared_pool + .usage(fixture.owner(&fixture.old_fingerprint), 100) + .await + .unwrap() + .unwrap() + .records, + 2 + ); + let source_store = DurableStore::open(&fixture.private_dir(&fixture.old_fingerprint)).unwrap(); + assert!(source_store.get("settings", 100).unwrap().is_some()); +} + +#[tokio::test] +async fn rejection_and_cancellation_leave_every_store_untouched() { + let fixture = Fixture::new().await; + fixture.seed_old_identity().await; + let lifecycle = fixture.lifecycle(); + let preview = lifecycle + .publisher_migration_preview_at(PLUGIN.to_owned(), 100) + .await + .unwrap(); + + let rejected = lifecycle + .publisher_migration_apply_at(preview.token.clone(), fixture.profile_id(), false, 100) + .await + .unwrap_err(); + assert_eq!(rejected.code(), tonic::Code::FailedPrecondition); + assert_eq!(fixture.target_records().await, 0); + assert!(!fixture.private_dir(&fixture.new_fingerprint).exists()); + + // Cancelling drops the preview: a later confirmation has nothing to apply. + lifecycle + .publisher_migration_cancel(preview.token.clone()) + .await + .unwrap(); + let cancelled = lifecycle + .publisher_migration_apply_at(preview.token.clone(), fixture.profile_id(), true, 100) + .await + .unwrap_err(); + assert_eq!(cancelled.code(), tonic::Code::FailedPrecondition); + assert_eq!(fixture.target_records().await, 0); + assert!(!fixture.private_dir(&fixture.new_fingerprint).exists()); + + // An unconfirmed apply of another preview also changes nothing. + let preview = lifecycle + .publisher_migration_preview_at(PLUGIN.to_owned(), 100) + .await + .unwrap(); + let unknown = lifecycle + .publisher_migration_apply_at("not-a-token".into(), fixture.profile_id(), true, 100) + .await + .unwrap_err(); + assert_eq!(unknown.code(), tonic::Code::FailedPrecondition); + assert_eq!(fixture.target_records().await, 0); + // The issued preview is still applicable after the unknown token failed. + let report = lifecycle + .publisher_migration_apply_at(preview.token, fixture.profile_id(), true, 100) + .await + .unwrap(); + assert_eq!(report.copied_records, 2); +} + +#[tokio::test] +async fn apply_copies_compatible_data_preserves_provenance_and_keeps_the_source() { + let fixture = Fixture::new().await; + fixture.seed_old_identity().await; + let original_ids = fixture + .root + .shared_pool + .list_dataset_any(DATASET.to_owned(), 100) + .await + .unwrap() + .0 + .into_iter() + .map(|record| record.record_id) + .collect::>(); + let lifecycle = fixture.lifecycle(); + let preview = lifecycle + .publisher_migration_preview_at(PLUGIN.to_owned(), 100) + .await + .unwrap(); + let report = lifecycle + .publisher_migration_apply_at(preview.token.clone(), fixture.profile_id(), true, 100) + .await + .unwrap(); + + assert_eq!(report.migration_id, preview.migration_id); + assert_eq!(report.copied_records, 2, "one private entry and one record"); + assert_eq!(report.conflict_records, 0); + assert_eq!(report.incompatible_schema_records, 1); + assert!(report.copied_bytes > 0); + assert_eq!(report.results.len(), 2); + assert!( + report + .results + .iter() + .all(|result| result.status == "completed") + ); + assert!(report.secrets_excluded && report.grants_excluded); + assert!(report.sharing_review_required && report.retention_review_required); + + // The new identity has exactly the compatible durable record, with the original provenance. + assert_eq!(fixture.target_records().await, 1); + let (records, _) = fixture + .root + .shared_pool + .list_dataset_any(DATASET.to_owned(), 100) + .await + .unwrap(); + let migrated = records + .iter() + .find(|record| { + record.provenance.source.publisher_fingerprint == fixture.old_fingerprint + && !original_ids.contains(&record.record_id) + }) + .expect("the copy is a new row with the original source provenance"); + assert_eq!( + migrated.provenance.source.publisher_fingerprint, + fixture.old_fingerprint + ); + assert_eq!(migrated.provenance.package_version, "1.0.0"); + assert_eq!(records.len(), 2, "the original row and one copy"); + assert!( + records + .iter() + .all(|record| record.dataset_id != "com.other.data"), + "an incompatible schema is not copied" + ); + + // The private copy exists and the old identity keeps its own data. + let target = DurableStore::open(&fixture.private_dir(&fixture.new_fingerprint)).unwrap(); + assert_eq!(target.get("settings", 100).unwrap().unwrap().value, b"old"); + drop(target); + let source = DurableStore::open(&fixture.private_dir(&fixture.old_fingerprint)).unwrap(); + assert_eq!(source.get("settings", 100).unwrap().unwrap().value, b"old"); + drop(source); + assert_eq!( + fixture + .root + .shared_pool + .usage(fixture.owner(&fixture.old_fingerprint), 100) + .await + .unwrap() + .unwrap() + .records, + 2 + ); + + // Single use: a retry needs a new preview. + let reused = lifecycle + .publisher_migration_apply_at(preview.token, fixture.profile_id(), true, 100) + .await + .unwrap_err(); + assert_eq!(reused.code(), tonic::Code::FailedPrecondition); +} + +#[tokio::test] +async fn another_profile_and_another_identity_are_isolated_and_grants_are_not_migrated() { + let fixture = Fixture::new().await; + fixture.seed_old_identity().await; + fixture.grant_storage_persist(&fixture.old_fingerprint); + let lifecycle = fixture.lifecycle(); + let preview = lifecycle + .publisher_migration_preview_at(PLUGIN.to_owned(), 100) + .await + .unwrap(); + let first_profile = fixture.profile_id(); + let first_owner = fixture.owner(&fixture.old_fingerprint); + let first_target_dir = fixture.private_dir(&fixture.new_fingerprint); + + // The review is bound to the profile that created it. + fixture + .root + .providers + .profiles() + .update(Some("account-two"), true); + let other_profile = fixture.profile_id(); + assert_ne!(other_profile, first_profile); + let stale = lifecycle + .publisher_migration_apply_at(preview.token.clone(), first_profile.clone(), true, 100) + .await + .unwrap_err(); + assert_eq!(stale.code(), tonic::Code::FailedPrecondition); + assert!(!first_target_dir.exists()); + assert_eq!( + fixture + .root + .shared_pool + .usage(first_owner, 100) + .await + .unwrap() + .unwrap() + .records, + 2, + "another profile's old identity keeps its records" + ); + fixture + .root + .providers + .profiles() + .update(Some("account-one"), true); + assert_eq!(fixture.profile_id(), first_profile); + + // A fresh review in the original profile applies; grants are still only the old identity's. + let preview = lifecycle + .publisher_migration_preview_at(PLUGIN.to_owned(), 100) + .await + .unwrap(); + let report = lifecycle + .publisher_migration_apply_at(preview.token, first_profile, true, 100) + .await + .unwrap(); + assert_eq!(report.copied_records, 2); + let (_, old_grants) = fixture + .root + .providers + .profiles() + .granted_permissions(PLUGIN, &fixture.old_fingerprint) + .unwrap(); + assert!(old_grants.contains(cap::STORAGE_PERSIST)); + let (_, new_grants) = fixture + .root + .providers + .profiles() + .granted_permissions(PLUGIN, &fixture.new_fingerprint) + .unwrap(); + assert!( + new_grants.is_empty(), + "a data migration never migrates an activation grant" + ); +} + +#[tokio::test] +async fn rollback_removes_only_the_copies_and_keeps_the_old_identity_data() { + let fixture = Fixture::new().await; + fixture.seed_old_identity().await; + let lifecycle = fixture.lifecycle(); + let preview = lifecycle + .publisher_migration_preview_at(PLUGIN.to_owned(), 100) + .await + .unwrap(); + let report = lifecycle + .publisher_migration_apply_at(preview.token, fixture.profile_id(), true, 100) + .await + .unwrap(); + assert_eq!(fixture.target_records().await, 1); + + let unconfirmed = lifecycle + .publisher_migration_rollback( + PLUGIN.to_owned(), + report.migration_id.clone(), + fixture.profile_id(), + false, + ) + .await + .unwrap_err(); + assert_eq!(unconfirmed.code(), tonic::Code::FailedPrecondition); + assert_eq!(fixture.target_records().await, 1); + + let wrong_id = lifecycle + .publisher_migration_rollback( + PLUGIN.to_owned(), + "deadbeef".into(), + fixture.profile_id(), + true, + ) + .await + .unwrap_err(); + assert_eq!(wrong_id.code(), tonic::Code::FailedPrecondition); + + let rolled_back = lifecycle + .publisher_migration_rollback( + PLUGIN.to_owned(), + report.migration_id, + fixture.profile_id(), + true, + ) + .await + .unwrap(); + assert_eq!(rolled_back.removed_records, 2); + assert_eq!(rolled_back.kept_protected_records, 0); + assert!(rolled_back.reclaimed_bytes > 0); + assert_eq!(fixture.target_records().await, 0); + let target = DurableStore::open(&fixture.private_dir(&fixture.new_fingerprint)).unwrap(); + assert!(target.get("settings", 100).unwrap().is_none()); + drop(target); + // The old identity's original data is untouched by the migration and the rollback. + assert_eq!( + fixture + .root + .shared_pool + .usage(fixture.owner(&fixture.old_fingerprint), 100) + .await + .unwrap() + .unwrap() + .records, + 2 + ); + let source = DurableStore::open(&fixture.private_dir(&fixture.old_fingerprint)).unwrap(); + assert_eq!(source.get("settings", 100).unwrap().unwrap().value, b"old"); +} + +#[tokio::test] +async fn a_missing_private_store_is_a_reported_partial_result() { + let fixture = Fixture::new().await; + fixture.seed_old_identity().await; + let lifecycle = fixture.lifecycle_without_private(); + let preview = lifecycle + .publisher_migration_preview_at(PLUGIN.to_owned(), 100) + .await + .unwrap(); + assert!(!preview.private_store_available); + let report = lifecycle + .publisher_migration_apply_at(preview.token, fixture.profile_id(), true, 100) + .await + .unwrap(); + assert_eq!(report.results.len(), 2); + let private = report + .results + .iter() + .find(|result| result.store == "private_persistence") + .unwrap(); + assert_eq!(private.status, "unavailable"); + let durable = report + .results + .iter() + .find(|result| result.store == "durable_shared") + .unwrap(); + assert_eq!(durable.status, "completed"); + assert_eq!(durable.copied_records, 1); + assert_eq!(report.copied_records, 1, "the durable copy still applies"); + assert_eq!(fixture.target_records().await, 1); +} + +#[tokio::test] +async fn a_newer_declared_schema_version_is_reported_as_incompatible() { + let fixture = Fixture::new().await; + fixture + .publish(&fixture.old_fingerprint, DATASET, "disc-1", SCHEMA, 2) + .await; + let lifecycle = fixture.lifecycle(); + let preview = lifecycle + .publisher_migration_preview_at(PLUGIN.to_owned(), 100) + .await + .unwrap(); + assert_eq!(preview.shared_records, 1); + assert_eq!(preview.shared_eligible_records, 0); + assert_eq!(preview.shared_incompatible_schema_records, 1); + assert!(!preview.can_migrate || preview.private_eligible_records > 0); + let dataset = &preview.datasets[0]; + assert_eq!(dataset.incompatible_schema_ids, vec![SCHEMA]); +} diff --git a/crates/app/src/plugin_host/namespace.rs b/crates/app/src/plugin_host/namespace.rs new file mode 100644 index 000000000..ffc04cfc3 --- /dev/null +++ b/crates/app/src/plugin_host/namespace.rs @@ -0,0 +1,292 @@ +//! Host-owned identity and owner scopes for third-party private resources. +//! +//! A resolver is created from authenticated package/session state. Plugin request messages never +//! construct owners or supply filesystem paths. Persistent owner keys include stable identity and +//! profile values; the profile epoch fences work from a stale session without changing the +//! persistent namespace when the application restarts. + +use crate::plugin_host::grants::{GrantError, PluginIdentity}; +use sha2::{Digest, Sha256}; +use std::fmt; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum OwnerKind { + Storage, + Job, + Account, + Secret, +} + +impl OwnerKind { + #[cfg(test)] + fn provider_scoped(self) -> bool { + matches!(self, Self::Account | Self::Secret) + } +} + +/// Opaque owner capability supplied by the authenticated host context to a service adapter. +/// It contains neither a path nor caller-controlled identity fields. +#[derive(Clone, PartialEq, Eq)] +pub struct NamespaceOwner { + key: [u8; 32], + profile_epoch: u64, + kind: OwnerKind, +} + +impl NamespaceOwner { + /// Opaque deterministic owner key for host persistence adapters. + pub(crate) fn key(&self) -> &[u8; 32] { + &self.key + } +} + +impl fmt::Debug for NamespaceOwner { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("NamespaceOwner") + .field("key", &"") + .field("profile_epoch", &self.profile_epoch) + .field("kind", &self.kind) + .finish() + } +} + +/// An opaque logical secret slot. This value cannot be used as an OS credential alias. +#[derive(Clone, PartialEq, Eq)] +pub struct SecretSlot([u8; 32]); + +impl SecretSlot { + /// Opaque deterministic slot key for host credential adapters. + pub(crate) fn key(&self) -> &[u8; 32] { + &self.0 + } +} + +impl fmt::Debug for SecretSlot { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("SecretSlot()") + } +} + +/// Resolves private-resource ownership using identity authenticated by the host. +#[derive(Clone, Debug)] +pub struct ExternalNamespaceResolver { + identity: PluginIdentity, + provider_id: Option, + profile_epoch: u64, +} + +impl ExternalNamespaceResolver { + /// `identity` and `provider_id` must come from the pinned package registry and active host + /// session, never from a plugin RPC payload. + pub(crate) fn new( + identity: PluginIdentity, + provider_id: Option, + profile_epoch: u64, + ) -> Result { + identity.validate()?; + if profile_epoch == 0 + || provider_id.as_ref().is_some_and(|id| { + id.trim().is_empty() || id.len() > 256 || id.chars().any(char::is_control) + }) + { + return Err(GrantError::InvalidIdentity); + } + Ok(Self { + identity, + provider_id, + profile_epoch, + }) + } + + /// The authenticated identity this resolver was built from. + pub(crate) fn identity(&self) -> &PluginIdentity { + &self.identity + } + + /// Owner for the plugin's private key/value storage, independent of provider sub-identity. + pub fn storage_owner(&self) -> NamespaceOwner { + self.owner(OwnerKind::Storage, false) + } + + /// Stable library-store key for this plugin and active account profile. + pub(crate) fn library_recipe_owner_key(&self) -> String { + format!("namespace:{:?}", self.storage_owner().key()) + } + + /// Owner for jobs submitted by this plugin in the current profile session. + pub fn job_owner(&self) -> NamespaceOwner { + self.owner(OwnerKind::Job, false) + } + + /// Owner for provider-specific account identity and state. + pub fn account_owner(&self) -> Result { + if self.provider_id.is_none() { + return Err(GrantError::InvalidIdentity); + } + Ok(self.owner(OwnerKind::Account, true)) + } + + /// Owner for provider-specific secret material. + pub fn secret_owner(&self) -> Result { + if self.provider_id.is_none() { + return Err(GrantError::InvalidIdentity); + } + Ok(self.owner(OwnerKind::Secret, true)) + } + + /// Resolve a logical secret key to a dedicated opaque slot. No caller-provided string is + /// interpreted as a keyring alias or filesystem path. + pub fn secret_slot(&self, logical_key: &str) -> Result { + let owner = self.secret_owner()?; + if logical_key.is_empty() + || logical_key.len() > 128 + || !logical_key + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || b"._-".contains(&byte)) + { + return Err(GrantError::InvalidIdentity); + } + let mut hash = Sha256::new(); + hash.update(b"gamenode.third-party.secret-slot.v1\0"); + hash.update(owner.key); + hash.update((logical_key.len() as u64).to_be_bytes()); + hash.update(logical_key.as_bytes()); + Ok(SecretSlot(hash.finalize().into())) + } + + /// A service adapter checks the supplied owner before accessing its backing store. + #[cfg(test)] + pub(crate) fn owns(&self, owner: &NamespaceOwner, kind: OwnerKind) -> bool { + (!kind.provider_scoped() || self.provider_id.is_some()) + && owner.kind == kind + && owner.profile_epoch == self.profile_epoch + && owner.key() == self.owner(kind, kind.provider_scoped()).key() + } + + /// Returns false when a queued operation captured a previous profile epoch. + pub fn is_current_profile_epoch(&self, captured_epoch: u64) -> bool { + captured_epoch == self.profile_epoch + } + + fn owner(&self, kind: OwnerKind, provider_scoped: bool) -> NamespaceOwner { + let mut hash = Sha256::new(); + hash.update(b"gamenode.third-party.namespace-owner.v1\0"); + hash_part(&mut hash, self.identity.plugin_id.as_bytes()); + hash_part(&mut hash, self.identity.publisher_fingerprint.as_bytes()); + hash_part(&mut hash, self.identity.profile_id.as_bytes()); + hash_part( + &mut hash, + match kind { + OwnerKind::Storage => b"storage", + OwnerKind::Job => b"job", + OwnerKind::Account => b"account", + OwnerKind::Secret => b"secret", + }, + ); + if provider_scoped && let Some(provider_id) = &self.provider_id { + hash_part(&mut hash, provider_id.as_bytes()); + } + NamespaceOwner { + key: hash.finalize().into(), + profile_epoch: self.profile_epoch, + kind, + } + } +} + +fn hash_part(hash: &mut Sha256, part: &[u8]) { + hash.update((part.len() as u64).to_be_bytes()); + hash.update(part); +} + +#[cfg(test)] +mod tests { + use super::*; + + fn identity(plugin: &str, publisher: &str, profile: &str) -> PluginIdentity { + PluginIdentity { + plugin_id: plugin.into(), + publisher_fingerprint: publisher.into(), + profile_id: profile.into(), + } + } + + fn resolver( + plugin: &str, + publisher: &str, + profile: &str, + provider: &str, + epoch: u64, + ) -> ExternalNamespaceResolver { + ExternalNamespaceResolver::new( + identity(plugin, publisher, profile), + Some(provider.into()), + epoch, + ) + .unwrap() + } + + #[test] + fn private_owners_are_separated_by_plugin_publisher_and_profile() { + let base = resolver("org.example.a", "publisher-a", "default", "provider", 1); + let other_plugin = resolver("org.example.b", "publisher-a", "default", "provider", 1); + let other_publisher = resolver("org.example.a", "publisher-b", "default", "provider", 1); + let other_profile = resolver("org.example.a", "publisher-a", "child", "provider", 1); + + let owner = base.storage_owner(); + assert!(base.owns(&owner, OwnerKind::Storage)); + assert!(!other_plugin.owns(&owner, OwnerKind::Storage)); + assert!(!other_publisher.owns(&owner, OwnerKind::Storage)); + assert!(!other_profile.owns(&owner, OwnerKind::Storage)); + assert!(!base.owns(&base.job_owner(), OwnerKind::Storage)); + } + + #[test] + fn secret_slots_are_provider_scoped_and_never_official_aliases() { + let a = resolver("org.example.a", "publisher-a", "default", "provider-a", 1); + let b = resolver("org.example.a", "publisher-a", "default", "provider-b", 1); + let slot_a = a.secret_slot("session").unwrap(); + let slot_b = b.secret_slot("session").unwrap(); + + assert_ne!(slot_a, slot_b); + assert_ne!(format!("{slot_a:?}"), "steam"); + assert_ne!(slot_a.key().as_slice(), b"steam"); + assert!(a.secret_slot("../../steam").is_err()); + assert!( + ExternalNamespaceResolver::new( + identity("org.example.x", "publisher-x", "default"), + None, + 1 + ) + .unwrap() + .secret_slot("session") + .is_err() + ); + } + + #[test] + fn account_identity_is_provider_and_profile_scoped() { + let a = resolver("org.example.a", "publisher-a", "default", "provider-a", 1); + let b = resolver("org.example.a", "publisher-a", "default", "provider-b", 1); + let account = a.account_owner().unwrap(); + + assert!(a.owns(&account, OwnerKind::Account)); + assert!(!b.owns(&account, OwnerKind::Account)); + assert!( + !resolver("org.example.a", "publisher-a", "child", "provider-a", 1) + .owns(&account, OwnerKind::Account) + ); + } + + #[test] + fn profile_epoch_fences_queued_operations_without_changing_durable_owner() { + let current = resolver("org.example.a", "publisher-a", "default", "provider", 9); + let stale = resolver("org.example.a", "publisher-a", "default", "provider", 8); + let captured = current.storage_owner(); + + assert!(current.is_current_profile_epoch(9)); + assert!(!current.is_current_profile_epoch(8)); + assert!(!stale.owns(&captured, OwnerKind::Storage)); + assert_eq!(stale.storage_owner().key, captured.key); + } +} diff --git a/crates/app/src/plugin_host/network.rs b/crates/app/src/plugin_host/network.rs new file mode 100644 index 000000000..edd9c942c --- /dev/null +++ b/crates/app/src/plugin_host/network.rs @@ -0,0 +1,228 @@ +//! Origin scopes and limits for the plugins' `Network.Fetch`. +//! +//! `network.fetch` is only half of the authority: the user also approves the exact HTTPS origins +//! (scheme, host and port) a plugin may reach, and nothing is reachable until one is approved. +//! The origins come from an [`OriginScopes`] source that is asked afresh for every fetch and for +//! every redirect hop and before returning a response. The production source is the active +//! profile's permission store, read on a blocking worker. +//! +//! The fetching itself, with its address, redirect, size and deadline rules, is +//! [`gamenode_platform::plugin_network`]; this module bounds how many run at once. + +use std::collections::{BTreeSet, HashMap}; +use std::sync::{Arc, Mutex}; + +use async_trait::async_trait; +use futures_util::future::BoxFuture; +use gamenode_platform::plugin_network::{FetchClient, FetchError, Request, Response, origin_of}; +use gamenode_plugin_protocol::capability::NETWORK_FETCH; +use tokio::sync::{OwnedSemaphorePermit, Semaphore}; +use tonic::Status; +use url::Url; + +use super::{ + grants::{GrantScope, PermissionState, PluginIdentity}, + profile::{PluginProfiles, PluginStateLayout}, +}; + +/// Fetches one plugin may have in flight. +pub const PER_PLUGIN_FETCHES: usize = 4; +/// Fetches in flight for all plugins together. +pub const GLOBAL_FETCHES: usize = 16; + +/// The check a fetch makes before every origin it is about to contact. +pub type AllowOrigin = Arc BoxFuture<'static, bool> + Send + Sync>; + +/// Whatever performs a fetch. The real one is [`FetchClient`]; tests supply their own. +#[async_trait] +pub trait Fetcher: Send + Sync { + /// `allow` is asked, with the exact origin, before the first request and before every + /// redirect is followed. + async fn fetch(&self, request: Request, allow: AllowOrigin) -> Result; +} + +#[async_trait] +impl Fetcher for FetchClient { + async fn fetch(&self, request: Request, allow: AllowOrigin) -> Result { + self.fetch_with_origin_check(request, move |origin| allow(origin)) + .await + } +} + +/// The exact HTTPS origins the user has approved for a plugin, as they stand now. +#[async_trait] +pub trait OriginScopes: Send + Sync { + async fn approved( + &self, + identity: &PluginIdentity, + profile_epoch: u64, + ) -> Option; +} + +/// A permission-store revision and the exact origins approved at that revision. +pub struct ApprovedOrigins { + pub revision: u64, + pub origins: BTreeSet, +} + +pub(super) struct PersistedOriginScopes { + pub profiles: Arc, + pub layout: PluginStateLayout, +} + +#[async_trait] +impl OriginScopes for PersistedOriginScopes { + async fn approved( + &self, + identity: &PluginIdentity, + profile_epoch: u64, + ) -> Option { + let profile = self.profiles.current().filter(|profile| { + profile.epoch() == profile_epoch && profile.profile_id() == identity.profile_id + })?; + let layout = self.layout.clone(); + let identity = identity.clone(); + let approved = tokio::task::spawn_blocking(move || { + let store = layout.open_grants(&profile).ok()?; + let origins = store + .effective_grants(&identity) + .into_iter() + .filter_map(|grant| { + if grant.permission_id == NETWORK_FETCH + && grant.state == PermissionState::Granted + && let GrantScope::Declared { value } = grant.scope + && canonical_origin(&value).as_ref() == Some(&value) + { + return Some(value); + } + None + }) + .collect(); + Some(ApprovedOrigins { + revision: store.revision(&identity), + origins, + }) + }) + .await + .ok()??; + self.profiles.is_current(profile_epoch).then_some(approved) + } +} + +/// An origin as the fetch compares it: `https://host` or `https://host:port`, lowercase, with +/// the default port left out. Anything that is not exactly an origin (a path, a query, a +/// scheme other than https, credentials) is not one. +pub(super) fn canonical_origin(text: &str) -> Option { + let (scheme, authority) = text.split_once("://")?; + let authority = authority.strip_suffix('/').unwrap_or(authority); + if !scheme.eq_ignore_ascii_case("https") + || authority.is_empty() + || authority.contains(['/', '\\', '@', '?', '#']) + || text.chars().any(|c| c.is_whitespace() || c.is_control()) + { + return None; + } + let url = Url::parse(text).ok()?; + let plain = url.username().is_empty() + && url.password().is_none() + && url.query().is_none() + && url.fragment().is_none() + && matches!(url.path(), "" | "/"); + plain.then(|| origin_of(&url)).flatten() +} + +/// Origin scopes and concurrency limits shared by every plugin session. +pub struct NetworkAccess { + fetcher: Option>, + scopes: Mutex>>, + global: Arc, + per_plugin: Mutex>>, +} + +impl Default for NetworkAccess { + /// The real client; fetching is unavailable if it cannot be built. + fn default() -> Self { + match FetchClient::new() { + Ok(client) => Self::new(Arc::new(client)), + Err(error) => { + tracing::warn!(%error, "plugin network fetch is unavailable"); + Self::unavailable() + } + } + } +} + +impl NetworkAccess { + pub fn new(fetcher: Arc) -> Self { + Self { + fetcher: Some(fetcher), + ..Self::unavailable() + } + } + + fn unavailable() -> Self { + Self { + fetcher: None, + scopes: Mutex::default(), + global: Arc::new(Semaphore::new(GLOBAL_FETCHES)), + per_plugin: Mutex::default(), + } + } + + /// Connects the source of approved origins. + pub fn set_scopes(&self, scopes: Arc) { + *self.scopes.lock().unwrap_or_else(|p| p.into_inner()) = Some(scopes); + } + + pub(crate) fn fetcher(&self) -> Option> { + self.fetcher.clone() + } + + /// The origins approved for `identity` and the authenticated profile epoch now. + pub(crate) async fn approved_origins( + &self, + identity: &PluginIdentity, + profile_epoch: u64, + ) -> Option { + let scopes = self + .scopes + .lock() + .unwrap_or_else(|p| p.into_inner()) + .clone()?; + scopes.approved(identity, profile_epoch).await + } + + /// One slot of the plugin's own allowance and one of the global one, or + /// `RESOURCE_EXHAUSTED`. Fetches are not queued: a plugin that is over its allowance is told + /// so and may retry. + pub(crate) fn permits(&self, owner: [u8; 32]) -> Result { + let own = self + .per_plugin + .lock() + .unwrap_or_else(|p| p.into_inner()) + .entry(owner) + .or_insert_with(|| Arc::new(Semaphore::new(PER_PLUGIN_FETCHES))) + .clone(); + let busy = + || Status::resource_exhausted("too many fetches are already running; retry later"); + let own = own.try_acquire_owned().map_err(|_| busy())?; + let global = self + .global + .clone() + .try_acquire_owned() + .map_err(|_| busy())?; + Ok(Permits { + _own: own, + _global: global, + }) + } +} + +/// Holds a fetch's slots until dropped. +pub(crate) struct Permits { + _own: OwnedSemaphorePermit, + _global: OwnedSemaphorePermit, +} + +#[cfg(all(test, unix))] +mod tests; diff --git a/crates/app/src/plugin_host/network/tests.rs b/crates/app/src/plugin_host/network/tests.rs new file mode 100644 index 000000000..fc00ed6ad --- /dev/null +++ b/crates/app/src/plugin_host/network/tests.rs @@ -0,0 +1,62 @@ +use super::*; + +#[test] +fn only_exact_https_origins_count_and_they_are_normalized() { + for (text, expected) in [ + ("https://api.example.com", Some("https://api.example.com")), + ("https://API.Example.com/", Some("https://api.example.com")), + ( + "https://api.example.com:443", + Some("https://api.example.com"), + ), + ( + "https://api.example.com:8443/", + Some("https://api.example.com:8443"), + ), + ( + "https://bücher.example", + Some("https://xn--bcher-kva.example"), + ), + ("https://api.example.com/v1", None), + ("https://api.example.com/a/..", None), + ("https://api.example.com\\", None), + ("https://@api.example.com", None), + ("https://api.example.com/?x=1", None), + ("https://api.example.com/#f", None), + ("https://user@api.example.com", None), + ("http://api.example.com", None), + ("api.example.com", None), + ("*.example.com", None), + ("https://*.example.com", None), + ("", None), + ] { + assert_eq!(canonical_origin(text).as_deref(), expected, "{text:?}"); + } +} + +#[test] +fn a_plugin_has_a_small_allowance_and_so_have_all_plugins() { + let access = NetworkAccess::default(); + let mut held = Vec::new(); + for _ in 0..PER_PLUGIN_FETCHES { + held.push(access.permits([1; 32]).unwrap()); + } + assert_eq!( + access.permits([1; 32]).err().map(|s| s.code()), + Some(tonic::Code::ResourceExhausted) + ); + // Another plugin is unaffected, until the global allowance is used up. + for owner in 2..=(GLOBAL_FETCHES / PER_PLUGIN_FETCHES) as u8 { + for _ in 0..PER_PLUGIN_FETCHES { + held.push(access.permits([owner; 32]).unwrap()); + } + } + assert_eq!(held.len(), GLOBAL_FETCHES); + assert_eq!( + access.permits([99; 32]).err().map(|s| s.code()), + Some(tonic::Code::ResourceExhausted) + ); + // Finishing a fetch frees both slots. + held.pop(); + assert!(access.permits([99; 32]).is_ok()); +} diff --git a/crates/app/src/plugin_host/notifications.rs b/crates/app/src/plugin_host/notifications.rs new file mode 100644 index 000000000..e5c4fe1be --- /dev/null +++ b/crates/app/src/plugin_host/notifications.rs @@ -0,0 +1,273 @@ +//! Notifications a plugin asks Core to show, through `Notifications.Publish`. +//! +//! A notification is plain text attributed to the plugin that sent it: the attribution comes from +//! the authenticated session, never from the request. The host bounds the text, refuses anything +//! that could disguise it (control characters, bidirectional overrides, invisible separators), +//! limits how often a plugin may speak, and hands the result to a [`NotificationSink`], which the +//! application connects to its window. The host never interprets the text: it is not markup, a +//! link or an action, and the UI renders it as plain text. +//! +//! Notifications are events, not state: one that is delivered while no window listens is lost. + +use std::collections::{HashMap, VecDeque}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +use serde::Serialize; + +/// The Tauri event a delivered notice leaves on. The UI listens to the same name. +pub const EVENT: &str = "plugin:notification"; + +/// The longest title, in bytes. +pub const MAX_TITLE_BYTES: usize = 120; +/// The longest body, in bytes, and the most lines it may have. +pub const MAX_BODY_BYTES: usize = 512; +pub const MAX_BODY_LINES: usize = 8; +/// The most translations beside the main text. +pub const MAX_TRANSLATIONS: usize = 8; +/// The longest language tag. +pub const MAX_LOCALE_BYTES: usize = 35; +/// How many notifications one plugin may publish in [`WINDOW`]. +pub const PER_PLUGIN_PER_WINDOW: usize = 5; +/// How many notifications all plugins together may publish in [`WINDOW`]. +pub const GLOBAL_PER_WINDOW: usize = 20; +/// The length of the rate-limit window. +pub const WINDOW: Duration = Duration::from_secs(60); + +/// How much a notification matters, as the plugin names it. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "lowercase")] +pub enum Severity { + Info, + Success, + Warning, + Error, +} + +impl Severity { + pub fn parse(text: &str) -> Option { + Some(match text { + "" | "info" => Self::Info, + "success" => Self::Success, + "warning" => Self::Warning, + "error" => Self::Error, + _ => return None, + }) + } +} + +/// One version of a notification's text. +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Text { + /// A language tag, or empty when the plugin gave none. + pub locale: String, + pub title: String, + pub body: String, +} + +/// What the application is told to show. +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PluginNotice { + /// The authenticated plugin id that sent it. + pub plugin_id: String, + pub severity: Severity, + /// The plugin's main text first, then its translations. + pub texts: Vec, +} + +/// The application's side: shows a notification. Called from a service thread, so it must hand +/// the notice off and return. +pub trait NotificationSink: Send + Sync { + fn deliver(&self, notice: PluginNotice); +} + +/// Characters that would let a text pretend to be something else: bidirectional controls, +/// invisible separators and tags. Ordinary format characters that real text needs (the joiners +/// of emoji and several scripts) are allowed. +fn disguises(c: char) -> bool { + matches!(c, + '\u{061C}' | '\u{200B}' | '\u{200E}' | '\u{200F}' + | '\u{2028}' | '\u{2029}' | '\u{202A}'..='\u{202E}' + | '\u{2060}' | '\u{2066}'..='\u{2069}' | '\u{FEFF}' + | '\u{FFF9}'..='\u{FFFB}' | '\u{E0000}'..='\u{E007F}') +} + +/// Whether `text` is plain text on one line: no control characters and none that disguise text. +pub fn is_plain_line(text: &str) -> bool { + clean(text, false) +} + +fn clean(text: &str, multiline: bool) -> bool { + text.chars() + .all(|c| !disguises(c) && (!c.is_control() || (multiline && c == '\n'))) +} + +/// Why a notification was refused. The messages are safe to show the plugin. +#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)] +#[error("{0}")] +pub struct Refused(pub String); + +fn refused(message: impl Into) -> Refused { + Refused(message.into()) +} + +/// A language tag as far as the host checks one: letters, digits and hyphens. +fn valid_locale(locale: &str) -> bool { + locale.len() <= MAX_LOCALE_BYTES + && locale + .chars() + .all(|c| c.is_ascii_alphanumeric() || c == '-') + && !locale.starts_with('-') + && !locale.ends_with('-') + && !locale.contains("--") +} + +/// Checks one version of the text and returns it trimmed. +pub fn check_text(locale: &str, title: &str, body: &str) -> Result { + if !valid_locale(locale) { + return Err(refused( + "locale must be a language tag of letters, digits and hyphens, such as \"en\" or \"pt-BR\"", + )); + } + let title = title.trim(); + let body = body.trim(); + if title.is_empty() { + return Err(refused("title is required")); + } + if title.len() > MAX_TITLE_BYTES { + return Err(refused(format!( + "title is longer than {MAX_TITLE_BYTES} bytes" + ))); + } + if !clean(title, false) { + return Err(refused( + "title must be plain text on one line: no control characters, bidirectional overrides or invisible separators", + )); + } + if body.len() > MAX_BODY_BYTES { + return Err(refused(format!( + "body is longer than {MAX_BODY_BYTES} bytes" + ))); + } + if !clean(body, true) { + return Err(refused( + "body must be plain text: no control characters other than line breaks, bidirectional overrides or invisible separators", + )); + } + if body.lines().count() > MAX_BODY_LINES { + return Err(refused(format!( + "body has more than {MAX_BODY_LINES} lines" + ))); + } + Ok(Text { + locale: locale.to_owned(), + title: title.to_owned(), + body: body.to_owned(), + }) +} + +/// A sliding window of the times something was admitted. +#[derive(Default)] +struct Window(VecDeque); + +impl Window { + fn prune(&mut self, now: Instant) { + while self + .0 + .front() + .is_some_and(|at| now.duration_since(*at) >= WINDOW) + { + self.0.pop_front(); + } + } + + /// How long until there is room for one more under `limit`, or `None` if there is room now. + fn wait(&self, now: Instant, limit: usize) -> Option { + (self.0.len() >= limit).then(|| { + let oldest = self.0[self.0.len() - limit]; + WINDOW.saturating_sub(now.duration_since(oldest)) + }) + } +} + +#[derive(Default)] +struct Windows { + global: Window, + per_plugin: HashMap<[u8; 32], Window>, +} + +type Clock = Arc Instant + Send + Sync>; + +/// The notification service shared by every plugin session: the sink and the rate limits. +pub struct Notifications { + sink: Mutex>>, + windows: Mutex, + clock: Clock, +} + +impl Default for Notifications { + fn default() -> Self { + Self { + sink: Mutex::default(), + windows: Mutex::default(), + clock: Arc::new(Instant::now), + } + } +} + +impl Notifications { + /// Connects the application's side. Until it is, publishing is unavailable. + pub fn set_sink(&self, sink: Arc) { + *self.sink.lock().unwrap_or_else(|p| p.into_inner()) = Some(sink); + } + + pub(crate) fn sink(&self) -> Option> { + self.sink.lock().unwrap_or_else(|p| p.into_inner()).clone() + } + + /// Replaces the clock, for tests of the rate limit. + #[cfg(test)] + pub(crate) fn with_clock( + mut self, + clock: impl Fn() -> Instant + Send + Sync + 'static, + ) -> Self { + self.clock = Arc::new(clock); + self + } + + /// Counts one notification of `owner` against the limits, or says how long to wait. A + /// refusal counts nothing. + pub(crate) fn admit(&self, owner: [u8; 32]) -> Result<(), Duration> { + let now = (self.clock)(); + let mut windows = self.windows.lock().unwrap_or_else(|p| p.into_inner()); + windows.global.prune(now); + windows.per_plugin.retain(|_, window| { + window.prune(now); + !window.0.is_empty() + }); + let own = windows.per_plugin.get(&owner); + let wait = [ + own.and_then(|window| window.wait(now, PER_PLUGIN_PER_WINDOW)), + windows.global.wait(now, GLOBAL_PER_WINDOW), + ] + .into_iter() + .flatten() + .max(); + if let Some(wait) = wait { + return Err(wait.max(Duration::from_secs(1))); + } + windows.global.0.push_back(now); + windows + .per_plugin + .entry(owner) + .or_default() + .0 + .push_back(now); + Ok(()) + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/app/src/plugin_host/notifications/tests.rs b/crates/app/src/plugin_host/notifications/tests.rs new file mode 100644 index 000000000..6c4139e8b --- /dev/null +++ b/crates/app/src/plugin_host/notifications/tests.rs @@ -0,0 +1,199 @@ +use std::sync::atomic::{AtomicU64, Ordering}; + +use super::*; + +fn text(title: &str, body: &str) -> Result { + check_text("en", title, body) +} + +#[test] +fn plain_text_is_trimmed_and_kept_exactly() { + let accepted = check_text( + "pt-BR", + " Backup concluído ", + " Três arquivos.\nSem erros. ", + ) + .unwrap(); + assert_eq!(accepted.locale, "pt-BR"); + assert_eq!(accepted.title, "Backup concluído"); + assert_eq!(accepted.body, "Três arquivos.\nSem erros."); + // Markup, links and script are just characters: the host does not interpret them. + let hostile = text( + "", + "[click](javascript:alert(1)) x https://evil.test", + ) + .unwrap(); + assert_eq!(hostile.title, ""); + assert!(hostile.body.contains(" (Notifications, Arc) { + let base = Instant::now(); + let offset = Arc::new(AtomicU64::new(0)); + let moved = offset.clone(); + let hub = Notifications::default() + .with_clock(move || base + Duration::from_millis(moved.load(Ordering::SeqCst))); + (hub, offset) +} + +#[test] +fn a_plugin_may_publish_a_few_notifications_a_minute() { + let (hub, clock) = hub(); + for second in 0..PER_PLUGIN_PER_WINDOW as u64 { + clock.store(second * 1000, Ordering::SeqCst); + assert!(hub.admit([1; 32]).is_ok()); + } + // The next one has to wait until the oldest leaves the window. + clock.store(10_000, Ordering::SeqCst); + assert_eq!(hub.admit([1; 32]), Err(Duration::from_secs(50))); + // A refusal counts nothing: the wait does not grow by asking again. + assert_eq!(hub.admit([1; 32]), Err(Duration::from_secs(50))); + clock.store(59_999, Ordering::SeqCst); + assert_eq!( + hub.admit([1; 32]), + Err(Duration::from_secs(1)), + "never less than a second" + ); + clock.store(60_000, Ordering::SeqCst); + assert!(hub.admit([1; 32]).is_ok(), "the oldest has left the window"); + assert!(hub.admit([1; 32]).is_err(), "and its place is taken again"); +} + +#[test] +fn another_plugin_has_its_own_allowance_until_the_shared_one_is_used() { + let (hub, _) = hub(); + for _ in 0..PER_PLUGIN_PER_WINDOW { + hub.admit([1; 32]).unwrap(); + } + assert!(hub.admit([1; 32]).is_err()); + for owner in 2..=(GLOBAL_PER_WINDOW / PER_PLUGIN_PER_WINDOW) as u8 { + for _ in 0..PER_PLUGIN_PER_WINDOW { + assert!(hub.admit([owner; 32]).is_ok(), "plugin {owner}"); + } + } + // Every plugin together has spoken GLOBAL_PER_WINDOW times: a plugin that has not is held too. + let wait = hub.admit([99; 32]).unwrap_err(); + assert!(wait <= WINDOW && wait >= Duration::from_secs(1)); +} + +#[test] +fn the_window_forgets_idle_plugins() { + let (hub, clock) = hub(); + hub.admit([1; 32]).unwrap(); + clock.store(WINDOW.as_millis() as u64 + 1, Ordering::SeqCst); + hub.admit([2; 32]).unwrap(); + assert_eq!(hub.windows.lock().unwrap().per_plugin.len(), 1); +} diff --git a/crates/app/src/plugin_host/package.rs b/crates/app/src/plugin_host/package.rs new file mode 100644 index 000000000..c5902ddd6 --- /dev/null +++ b/crates/app/src/plugin_host/package.rs @@ -0,0 +1,1626 @@ +//! Manifest schema for managed third-party plugin packages. +//! +//! This is deliberately separate from the bundled provider descriptors: parsing a +//! manifest does not register, trust, install, or execute a plugin. + +use std::collections::BTreeMap; + +use semver::Version; +use serde::{ + Deserialize, + de::{self, MapAccess, SeqAccess, Visitor}, +}; + +#[derive(Clone, Debug, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct Manifest { + pub schema: u32, + pub id: String, + pub kind: PluginKind, + #[serde(default)] + pub provider_id: Option, + pub name: String, + pub version: String, + pub api: ApiRange, + #[serde(default)] + pub permissions: Vec, + /// Signed disclosure of this package's gameplay and pause identification capability. + /// Missing declarations are treated as disabled for backward compatibility. + #[serde(default)] + pub playtime: PlaytimeCapabilities, + /// OS-level capabilities requested by the package. These are disclosures only; package + /// updates never grant them automatically. + #[serde(default)] + pub native_access: Vec, + /// Content platforms this package supports, such as `gamecube` or `wii`. These are content + /// families, not OS targets; the executable tuples stay in `targets`. Missing declarations + /// are accepted for backward compatibility. + #[serde(default)] + pub supported_platforms: Vec, + pub targets: Vec, + pub publisher: Publisher, + pub license: LicenseNotice, + #[serde(default)] + pub source_url: Option, + #[serde(default)] + pub update_url: Option, + #[serde(default)] + pub configuration: ConfigurationModes, + /// Package-relative paths for validated provider/login/action descriptors. + #[serde(default)] + pub resources: BTreeMap, + #[serde(default)] + pub schemas: Vec, +} + +#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq, serde::Serialize)] +#[serde(rename_all = "snake_case")] +pub enum PlaytimeAccountingMode { + #[default] + Disabled, + ApplicationOpen, +} + +/// Signed gameplay/pause declarations. Manifests keep the documented snake_case keys; the +/// review and inventory DTOs the UI consumes use camelCase, so both spellings are accepted on +/// input and only camelCase is emitted. +#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq, serde::Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct PlaytimeCapabilities { + #[serde(default, alias = "identifies_gameplay")] + pub identifies_gameplay: bool, + #[serde(default, alias = "identifies_pauses")] + pub identifies_pauses: bool, + #[serde(default, alias = "without_pause_detection")] + pub without_pause_detection: PlaytimeAccountingMode, +} + +impl PlaytimeCapabilities { + /// Whether a signed manifest actually declares playtime support. Packages that declare + /// nothing stay installed without a playtime inventory row or accounting toggle. + pub fn declares_support(&self) -> bool { + self.identifies_gameplay + || self.identifies_pauses + || self.without_pause_detection != PlaytimeAccountingMode::Disabled + } +} + +#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "lowercase")] +pub enum PluginKind { + Provider, + Extension, +} + +#[derive(Clone, Debug, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct ApiRange { + pub min: String, + pub max: String, +} + +#[derive(Clone, Debug, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct PermissionRequest { + pub id: String, + pub required: bool, + pub scope: String, + pub reason: String, + /// Signed disclosure of what the plugin loses when this optional permission is denied. A + /// required permission cannot be denied, so the field is descriptive there. Older manifests + /// without it remain valid. + #[serde(default)] + pub impact_if_disabled: Option, +} + +#[derive(Clone, Debug, Deserialize, serde::Serialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct Target { + pub os: String, + pub arch: String, + pub abi: String, + pub entrypoint: String, + #[serde(default)] + pub requires: Option, + #[serde(default)] + pub tested_on: Vec, +} + +#[derive(Clone, Debug, Deserialize, serde::Serialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct TargetRequirements { + #[serde(default)] + pub windows: Option, + #[serde(default)] + pub linux: Option, +} + +#[derive(Clone, Copy, Debug, Deserialize, serde::Serialize, PartialEq, Eq)] +#[serde(rename_all = "lowercase")] +pub enum WindowsProduct { + Client, + Server, +} + +#[derive(Clone, Debug, Deserialize, serde::Serialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct WindowsRequirements { + #[serde(default)] + pub product: Option, + #[serde(default)] + pub min_version: Option, + #[serde(default)] + pub max_version: Option, + #[serde(default)] + pub min_build: Option, + #[serde(default)] + pub max_build: Option, +} + +#[derive(Clone, Copy, Debug, Deserialize, serde::Serialize, PartialEq, Eq)] +#[serde(rename_all = "lowercase")] +pub enum LibcFamily { + Glibc, + Musl, +} + +#[derive(Clone, Debug, Deserialize, serde::Serialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct LibcRequirements { + pub family: LibcFamily, + pub min_version: String, +} + +#[derive(Clone, Debug, Deserialize, serde::Serialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct LinuxRequirements { + #[serde(default)] + pub libc: Option, + /// Alternatives: any one listed distribution/version pair is sufficient. + #[serde(default)] + pub distributions: Option>, +} + +#[derive(Clone, Debug, Deserialize, serde::Serialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct DistributionRequirement { + pub id: String, + /// Exact distribution version strings. Entries within this list are alternatives. + pub versions: Vec, +} + +#[derive(Clone, Debug, Deserialize, serde::Serialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct TestedEnvironment { + #[serde(default)] + pub product: Option, + #[serde(default)] + pub release: Option, + #[serde(default)] + pub distribution: Option, + #[serde(default)] + pub version: Option, +} + +#[derive(Clone, Debug, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct PackagedSchema { + /// Owner-controlled reverse-domain namespace, equal to the plugin id or its child. + pub namespace: String, + /// Version of this schema contract, independent of the plugin package version. + pub version: String, + /// Maximum classification declared for any field in the schema asset. + pub classification: DataClassification, + /// Package-relative, integrity-covered JSON Schema subset asset. + pub asset: String, +} + +#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(rename_all = "lowercase")] +pub enum DataClassification { + Public, + Sensitive, + Private, +} + +#[derive(Clone, Debug, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct Publisher { + pub key_id: String, + pub public_key: String, +} + +#[derive(Clone, Debug, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct LicenseNotice { + /// SPDX expression, or `LicenseRef-*` when the bundled text defines it. + pub expression: String, + pub files: Vec, + #[serde(default)] + pub notices: Vec, +} + +#[derive(Clone, Debug, Default, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct ConfigurationModes { + #[serde(default)] + pub external: bool, + #[serde(default)] + pub declarative: bool, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ValidatedManifest(Manifest); + +impl ValidatedManifest { + pub fn manifest(&self) -> &Manifest { + &self.0 + } + + pub(crate) fn publisher_key(&self) -> [u8; 32] { + decode_key(&self.0.publisher.public_key) + .and_then(|key| key.try_into().ok()) + .expect("validated manifest contains a 32-byte publisher key") + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ManifestError(pub String); + +impl std::fmt::Display for ManifestError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } +} +impl std::error::Error for ManifestError {} + +impl Manifest { + pub fn parse_json(bytes: &[u8]) -> Result { + if bytes.len() > 4 * 1024 * 1024 { + return Err(ManifestError( + "plugin manifest exceeds the 4 MiB metadata limit".into(), + )); + } + let mut deserializer = serde_json::Deserializer::from_slice(bytes); + NoDuplicateJson::deserialize(&mut deserializer) + .map_err(|e| ManifestError(format!("invalid plugin manifest JSON: {e}")))?; + deserializer + .end() + .map_err(|e| ManifestError(format!("invalid plugin manifest JSON: {e}")))?; + let manifest: Self = serde_json::from_slice(bytes) + .map_err(|e| ManifestError(format!("invalid plugin manifest: {e}")))?; + manifest.validate()?; + Ok(ValidatedManifest(manifest)) + } + + pub fn validate(&self) -> Result<(), ManifestError> { + let invalid = |message: &str| Err(ManifestError(message.into())); + if self.schema != 1 { + return invalid("unsupported manifest schema (expected 1)"); + } + if !reverse_domain_id(&self.id) { + return invalid("plugin id must be a reverse-domain identifier"); + } + if reserved_plugin_id(&self.id) { + return invalid("plugin id uses the reserved GameNode namespace"); + } + match self.kind { + PluginKind::Provider => { + let Some(id) = self.provider_id.as_deref() else { + return invalid("provider packages require a valid provider_id"); + }; + if !provider_id(id) { + return invalid("provider packages require a valid provider_id"); + } + if reserved_provider_id(id) { + return invalid("provider_id is reserved by an official provider"); + } + } + PluginKind::Extension if self.provider_id.is_some() => { + return invalid("extension packages must not declare provider_id"); + } + _ => {} + } + if self.kind == PluginKind::Extension && self.resources.contains_key("provider") { + return invalid("extension packages must not declare a provider resource"); + } + if self.playtime.identifies_pauses && !self.playtime.identifies_gameplay { + return invalid("pause detection requires gameplay identification"); + } + if !self.playtime.identifies_gameplay + && self.playtime.without_pause_detection != PlaytimeAccountingMode::Disabled + { + return invalid("application-open accounting requires gameplay identification"); + } + if self.name.trim().is_empty() || self.name.len() > 128 { + return invalid("name must contain 1 to 128 characters"); + } + let version = Version::parse(&self.version) + .map_err(|_| ManifestError("version must be valid SemVer".into()))?; + let min = Version::parse(&self.api.min) + .map_err(|_| ManifestError("api.min must be valid SemVer".into()))?; + let max = Version::parse(&self.api.max) + .map_err(|_| ManifestError("api.max must be valid SemVer".into()))?; + if min > max { + return invalid("api.min must not exceed api.max"); + } + let _ = version; + let valid_native_access = ["files", "network", "process", "registry", "dbus"]; + let mut seen_native_access = std::collections::HashSet::new(); + if self.native_access.iter().any(|access| { + !valid_native_access.contains(&access.as_str()) || !seen_native_access.insert(access) + }) { + return invalid("native_access must contain unique supported access names"); + } + if self.targets.is_empty() { + return invalid("at least one target is required"); + } + if self.supported_platforms.len() > MAX_SUPPORTED_PLATFORMS { + return invalid("supported_platforms allows at most 16 entries"); + } + let mut seen_platforms = std::collections::HashSet::new(); + if self + .supported_platforms + .iter() + .any(|platform| !supported_platform(platform) || !seen_platforms.insert(platform)) + { + return invalid( + "supported_platforms must contain unique lowercase identifiers of 1 to 64 bytes", + ); + } + let mut seen_targets = std::collections::HashSet::new(); + for target in &self.targets { + let valid_abi = match target.os.as_str() { + "linux" => matches!(target.abi.as_str(), "gnu" | "musl"), + "windows" => matches!(target.abi.as_str(), "msvc" | "gnu"), + _ => false, + }; + if !matches!(target.os.as_str(), "linux" | "windows") + || !matches!(target.arch.as_str(), "x86_64" | "aarch64" | "x86") + || !valid_abi + { + return invalid("target must specify a supported OS, architecture, and ABI"); + } + if !package_path(&target.entrypoint) { + return invalid("target entrypoint must be a safe package-relative path"); + } + if let Some(requirements) = &target.requires { + validate_target_requirements(target, requirements)?; + } + for tested in &target.tested_on { + validate_tested_environment(target, tested)?; + } + if !seen_targets.insert((&target.os, &target.arch, &target.abi)) { + return invalid("ambiguous target selection: duplicate OS/architecture/ABI tuple"); + } + } + if self.schemas.len() > 32 { + return invalid("at most 32 packaged schemas are allowed per plugin"); + } + let mut seen_schemas = std::collections::HashSet::new(); + let mut seen_assets = std::collections::HashSet::new(); + for schema in &self.schemas { + let namespace_owned = schema.namespace == self.id + || schema.namespace.starts_with(&format!("{}.", self.id)); + if !reverse_domain_id(&schema.namespace) + || schema.namespace.starts_with("org.gamenode.") + || !namespace_owned + { + return invalid( + "schema namespace must be a reverse-domain namespace owned by this plugin", + ); + } + Version::parse(&schema.version) + .map_err(|_| ManifestError("schema version must be valid SemVer".into()))?; + if !package_path(&schema.asset) + || !schema.asset.starts_with("schemas/") + || !seen_schemas.insert((&schema.namespace, &schema.version)) + || !seen_assets.insert(&schema.asset) + { + return invalid( + "schema namespace/version and asset paths must be unique safe schema paths", + ); + } + } + let mut permissions = std::collections::HashSet::new(); + for permission in &self.permissions { + if !identifier(&permission.id) + || permission.scope.trim().is_empty() + || permission.reason.trim().is_empty() + || permission.reason.len() > 512 + { + return invalid( + "permission requests require a valid id, scope, and bounded reason", + ); + } + if let Some(impact) = &permission.impact_if_disabled + && (impact.trim().is_empty() + || impact.len() > 512 + || impact.chars().any(char::is_control)) + { + return invalid( + "permission impact_if_disabled must be a non-empty bounded single-line disclosure", + ); + } + if !permissions.insert(&permission.id) { + return invalid("duplicate permission request"); + } + } + if self.permissions.iter().any(|permission| { + permission.id == gamenode_plugin_protocol::capability::GAME_SESSIONS_REPORT + }) && !self.playtime.identifies_gameplay + { + return invalid("game.sessions.report requires declared gameplay identification"); + } + if self.publisher.key_id.trim().is_empty() + || self.publisher.key_id.len() > 128 + || decode_key(&self.publisher.public_key).is_none() + { + return invalid("publisher public_key must be base64-encoded 32-byte Ed25519 key data"); + } + if !license_expression(&self.license.expression) || self.license.files.is_empty() { + return invalid( + "license requires a valid SPDX expression or LicenseRef and at least one bundled text", + ); + } + for path in self + .license + .files + .iter() + .chain(self.license.notices.iter()) + .chain(self.resources.values()) + { + if !package_path(path) { + return invalid( + "license, notice, and resource paths must be safe package-relative paths", + ); + } + } + if let Some(source) = &self.source_url { + let parsed = url::Url::parse(source) + .map_err(|_| ManifestError("source URL is invalid".into()))?; + if !matches!(parsed.scheme(), "https" | "http") || parsed.host_str().is_none() { + return invalid("source URL must be an absolute HTTP(S) URL"); + } + } + if let Some(update) = &self.update_url { + let parsed = url::Url::parse(update) + .map_err(|_| ManifestError("update URL is invalid".into()))?; + if parsed.scheme() != "https" || parsed.host_str().is_none() { + return invalid("update URL must use HTTPS"); + } + } + Ok(()) + } + + /// Validate packaged schema bytes after archive staging. The caller supplies only + /// integrity-verified package entries; this function never retrieves remote assets. + pub fn validate_schema_assets( + &self, + assets: &BTreeMap>, + ) -> Result<(), ManifestError> { + self.validate()?; + for descriptor in &self.schemas { + let bytes = assets.get(&descriptor.asset).ok_or_else(|| { + ManifestError(format!("missing schema asset `{}`", descriptor.asset)) + })?; + if bytes.len() > 64 * 1024 { + return Err(ManifestError(format!( + "schema asset `{}` exceeds the 64 KiB limit", + descriptor.asset + ))); + } + let mut duplicate_check = serde_json::Deserializer::from_slice(bytes); + NoDuplicateJson::deserialize(&mut duplicate_check).map_err(|e| { + ManifestError(format!("invalid schema asset `{}`: {e}", descriptor.asset)) + })?; + duplicate_check.end().map_err(|e| { + ManifestError(format!("invalid schema asset `{}`: {e}", descriptor.asset)) + })?; + let value: serde_json::Value = serde_json::from_slice(bytes).map_err(|e| { + ManifestError(format!("invalid schema asset `{}`: {e}", descriptor.asset)) + })?; + let mut budget = SchemaBudget { keys: 0 }; + let maximum = validate_schema_node(&value, 0, false, &mut budget)?; + if maximum.is_some_and(|field_class| field_class > descriptor.classification) { + return Err(ManifestError(format!( + "schema `{}` understates its field classification", + descriptor.namespace + ))); + } + } + Ok(()) + } + + /// Reject namespace claims that overlap another installed package's ownership. + /// `existing_owners` is the host registry's namespace-to-plugin-id index. + pub fn validate_namespace_ownership( + &self, + existing_owners: &BTreeMap, + ) -> Result<(), ManifestError> { + self.validate()?; + for schema in &self.schemas { + for (claimed_namespace, owner) in existing_owners { + let overlaps = schema.namespace == *claimed_namespace + || schema + .namespace + .starts_with(&format!("{claimed_namespace}.")) + || claimed_namespace.starts_with(&format!("{}.", schema.namespace)); + if overlaps && owner != &self.id { + return Err(ManifestError(format!( + "schema namespace `{}` conflicts with namespace owned by `{owner}`", + schema.namespace + ))); + } + } + } + Ok(()) + } +} + +fn reverse_domain_id(s: &str) -> bool { + s.len() <= 255 + && s.split('.').count() >= 2 + && s.split('.').all(|part| { + !part.is_empty() + && part.as_bytes()[0].is_ascii_alphanumeric() + && part + .bytes() + .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-') + }) +} +fn reserved_plugin_id(s: &str) -> bool { + s == "org.gamenode" || s.starts_with("org.gamenode.") +} +fn provider_id(s: &str) -> bool { + !s.is_empty() + && s.len() <= 64 + && s.bytes() + .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-' || b == b'_') +} +fn reserved_provider_id(s: &str) -> bool { + matches!(s, "epic" | "manual" | "packagekit" | "steam") +} +fn identifier(s: &str) -> bool { + !s.is_empty() + && s.len() <= 128 + && s.bytes() + .all(|b| b.is_ascii_alphanumeric() || b == b'.' || b == b'-' || b == b'_') +} + +/// Content platform identifiers are lowercase, ASCII-only, and 1 to 64 bytes. The byte check +/// also rejects control characters, uppercase variants, and non-ASCII lookalikes. +const MAX_SUPPORTED_PLATFORMS: usize = 16; + +fn supported_platform(s: &str) -> bool { + !s.is_empty() + && s.len() <= 64 + && s.bytes().all(|b| { + b.is_ascii_lowercase() || b.is_ascii_digit() || matches!(b, b'.' | b'_' | b'-') + }) +} +fn package_path(s: &str) -> bool { + !s.is_empty() + && !s.starts_with('/') + && !s.starts_with('\\') + && !s.contains(':') + && s.split(['/', '\\']) + .all(|p| !p.is_empty() && p != "." && p != "..") +} + +fn validate_target_requirements( + target: &Target, + requirements: &TargetRequirements, +) -> Result<(), ManifestError> { + let invalid = |message: &str| Err(ManifestError(message.into())); + match target.os.as_str() { + "windows" => { + if requirements.linux.is_some() || requirements.windows.is_none() { + return invalid("Windows targets must declare only Windows requirements"); + } + let req = requirements.windows.as_ref().expect("checked above"); + if req.product.is_none() + && req.min_version.is_none() + && req.max_version.is_none() + && req.min_build.is_none() + && req.max_build.is_none() + { + return invalid("Windows requirements must specify at least one selector"); + } + let min_version = req + .min_version + .as_deref() + .map(parse_numeric_version) + .transpose()?; + let max_version = req + .max_version + .as_deref() + .map(parse_numeric_version) + .transpose()?; + if let (Some(min), Some(max)) = (&min_version, &max_version) + && compare_numeric_versions(min, max).is_gt() + { + return invalid("Windows min_version must not exceed max_version"); + } + if req + .min_build + .zip(req.max_build) + .is_some_and(|(min, max)| min > max) + { + return invalid("Windows min_build must not exceed max_build"); + } + } + "linux" => { + if requirements.windows.is_some() || requirements.linux.is_none() { + return invalid("Linux targets must declare only Linux requirements"); + } + let req = requirements.linux.as_ref().expect("checked above"); + if req.libc.is_none() && req.distributions.is_none() { + return invalid("Linux requirements must specify libc or distributions"); + } + if let Some(libc) = &req.libc { + parse_numeric_version(&libc.min_version)?; + let abi_matches = matches!( + (libc.family, target.abi.as_str()), + (LibcFamily::Glibc, "gnu") | (LibcFamily::Musl, "musl") + ); + if !abi_matches { + return invalid("Linux libc family contradicts target ABI"); + } + } + if let Some(distributions) = &req.distributions { + if distributions.is_empty() { + return invalid("Linux distribution alternatives must not be empty"); + } + let mut seen_ids = std::collections::HashSet::new(); + for distribution in distributions { + if !distribution_id(&distribution.id) || !seen_ids.insert(&distribution.id) { + return invalid("Linux distribution alternatives require unique valid IDs"); + } + if distribution.versions.is_empty() + || distribution + .versions + .iter() + .any(|v| v.trim().is_empty() || v.len() > 64) + { + return invalid( + "each Linux distribution alternative requires bounded version strings", + ); + } + let mut versions = std::collections::HashSet::new(); + if distribution.versions.iter().any(|v| !versions.insert(v)) { + return invalid("duplicate version in Linux distribution alternatives"); + } + } + } + } + _ => return invalid("unsupported target OS requirements"), + } + Ok(()) +} + +fn validate_tested_environment( + target: &Target, + tested: &TestedEnvironment, +) -> Result<(), ManifestError> { + let valid = match target.os.as_str() { + "windows" => { + tested + .product + .as_deref() + .is_some_and(|s| !s.trim().is_empty() && s.len() <= 128) + && tested + .release + .as_deref() + .is_some_and(|s| !s.trim().is_empty() && s.len() <= 128) + && tested.distribution.is_none() + && tested.version.is_none() + } + "linux" => { + tested.distribution.as_deref().is_some_and(distribution_id) + && tested + .version + .as_deref() + .is_some_and(|s| !s.trim().is_empty() && s.len() <= 64) + && tested.product.is_none() + && tested.release.is_none() + } + _ => false, + }; + if !valid { + return Err(ManifestError("tested_on entries must identify a matching Windows product/release or Linux distribution/version".into())); + } + Ok(()) +} + +fn distribution_id(s: &str) -> bool { + !s.is_empty() + && s.len() <= 64 + && s.bytes().all(|b| { + b.is_ascii_lowercase() || b.is_ascii_digit() || matches!(b, b'.' | b'_' | b'-') + }) +} + +fn parse_numeric_version(value: &str) -> Result, ManifestError> { + if value.is_empty() || value.len() > 64 { + return Err(ManifestError( + "numeric version bound is empty or too long".into(), + )); + } + let parts: Vec<_> = value.split('.').collect(); + if !(1..=4).contains(&parts.len()) { + return Err(ManifestError( + "numeric version bounds require one to four components".into(), + )); + } + parts + .iter() + .map(|part| { + if part.is_empty() + || !part.bytes().all(|b| b.is_ascii_digit()) + || (part.len() > 1 && part.starts_with('0')) + { + return Err(ManifestError( + "numeric version bounds must contain canonical decimal components".into(), + )); + } + part.parse::() + .map_err(|_| ManifestError("numeric version component exceeds range".into())) + }) + .collect() +} + +fn compare_numeric_versions(left: &[u32], right: &[u32]) -> std::cmp::Ordering { + let width = left.len().max(right.len()); + (0..width) + .map(|i| { + left.get(i) + .copied() + .unwrap_or(0) + .cmp(&right.get(i).copied().unwrap_or(0)) + }) + .find(|order| !order.is_eq()) + .unwrap_or(std::cmp::Ordering::Equal) +} + +struct SchemaBudget { + keys: usize, +} + +const JSON_SCHEMA_DIALECT: &str = "https://json-schema.org/draft/2020-12/schema"; +const MAX_SCHEMA_DEPTH: usize = 8; +const MAX_SCHEMA_KEYS: usize = 256; + +fn validate_schema_node( + value: &serde_json::Value, + depth: usize, + require_classification: bool, + budget: &mut SchemaBudget, +) -> Result, ManifestError> { + let invalid = |message: &str| Err(ManifestError(message.into())); + if depth > MAX_SCHEMA_DEPTH { + return invalid("declarative schema exceeds the depth limit of 8"); + } + let object = value + .as_object() + .ok_or_else(|| ManifestError("each declarative schema node must be an object".into()))?; + budget.keys = budget.keys.saturating_add(object.len()); + if budget.keys > MAX_SCHEMA_KEYS { + return invalid("declarative schema exceeds the 256-key limit"); + } + + const ALLOWED: &[&str] = &[ + "$schema", + "type", + "title", + "description", + "properties", + "required", + "additionalProperties", + "items", + "enum", + "minimum", + "maximum", + "minLength", + "maxLength", + "minItems", + "maxItems", + "x-gamenode-classification", + ]; + for key in object.keys() { + if key == "$ref" || key == "$dynamicRef" || key == "$recursiveRef" { + return invalid("schema references are unsupported; assets must be self-contained"); + } + if !ALLOWED.contains(&key.as_str()) { + return Err(ManifestError(format!( + "unsupported declarative schema keyword `{key}`" + ))); + } + } + + if let Some(dialect) = object.get("$schema") + && dialect.as_str() != Some(JSON_SCHEMA_DIALECT) + { + return invalid("schema $schema must identify the supported JSON Schema 2020-12 subset"); + } + for text_key in ["title", "description"] { + if let Some(text) = object.get(text_key) { + let max = if text_key == "title" { 128 } else { 1024 }; + if text.as_str().is_none_or(|s| s.len() > max) { + return invalid("schema title/description must be bounded strings"); + } + } + } + + let type_name = object + .get("type") + .and_then(serde_json::Value::as_str) + .ok_or_else(|| ManifestError("declarative schema nodes require one string type".into()))?; + if !matches!( + type_name, + "object" | "array" | "string" | "number" | "integer" | "boolean" | "null" + ) { + return invalid("declarative schema has an unsupported type"); + } + + let own_class = match object.get("x-gamenode-classification") { + Some(value) => Some(match value.as_str() { + Some("public") => DataClassification::Public, + Some("sensitive") => DataClassification::Sensitive, + Some("private") => DataClassification::Private, + _ => return invalid("field classification must be public, sensitive, or private"), + }), + None if require_classification => { + return invalid("every declared field requires x-gamenode-classification"); + } + None => None, + }; + + let mut maximum_class = own_class; + if type_name == "object" { + if object.get("additionalProperties") != Some(&serde_json::Value::Bool(false)) { + return invalid("object schemas must set additionalProperties to false"); + } + let properties = object + .get("properties") + .and_then(serde_json::Value::as_object) + .ok_or_else(|| ManifestError("object schemas require a properties object".into()))?; + if properties.len() > MAX_SCHEMA_KEYS { + return invalid("object schema has too many properties"); + } + for (key, child) in properties { + if !schema_field_name(key) { + return Err(ManifestError(format!( + "schema field name `{key}` is invalid or reserved" + ))); + } + if let Some(child_class) = validate_schema_node(child, depth + 1, true, budget)? { + maximum_class = + Some(maximum_class.map_or(child_class, |current| current.max(child_class))); + } + } + let required = object + .get("required") + .and_then(serde_json::Value::as_array) + .ok_or_else(|| { + ManifestError("object schemas require a required array (which may be empty)".into()) + })?; + let mut required_names = std::collections::HashSet::new(); + for entry in required { + let name = entry + .as_str() + .ok_or_else(|| ManifestError("required entries must be strings".into()))?; + if !properties.contains_key(name) || !required_names.insert(name) { + return invalid("required entries must name unique declared properties"); + } + } + } else if object.contains_key("properties") + || object.contains_key("required") + || object.contains_key("additionalProperties") + { + return invalid("object-only keywords require type object"); + } + + if type_name == "array" { + let items = object + .get("items") + .ok_or_else(|| ManifestError("array schemas require items".into()))?; + let max_items = object + .get("maxItems") + .and_then(serde_json::Value::as_u64) + .ok_or_else(|| ManifestError("array schemas require bounded maxItems".into()))?; + if max_items > 256 { + return invalid("array maxItems exceeds 256"); + } + if object + .get("minItems") + .and_then(serde_json::Value::as_u64) + .is_some_and(|min| min > max_items) + { + return invalid("array minItems must not exceed maxItems"); + } + if let Some(item_class) = validate_schema_node(items, depth + 1, false, budget)? { + maximum_class = + Some(maximum_class.map_or(item_class, |current| current.max(item_class))); + } + } else if object.contains_key("items") + || object.contains_key("minItems") + || object.contains_key("maxItems") + { + return invalid("array-only keywords require type array"); + } + + if type_name == "string" { + let max_length = object + .get("maxLength") + .and_then(serde_json::Value::as_u64) + .ok_or_else(|| ManifestError("string schemas require bounded maxLength".into()))?; + if max_length > 4096 { + return invalid("string maxLength exceeds 4096"); + } + if object + .get("minLength") + .and_then(serde_json::Value::as_u64) + .is_some_and(|min| min > max_length) + { + return invalid("string minLength must not exceed maxLength"); + } + } else if object.contains_key("minLength") || object.contains_key("maxLength") { + return invalid("string-only keywords require type string"); + } + + if let Some(values) = object.get("enum") { + let values = values + .as_array() + .ok_or_else(|| ManifestError("enum must be an array".into()))?; + if values.is_empty() + || values.len() > 128 + || values.iter().any(|v| v.is_array() || v.is_object()) + { + return invalid("enum must contain 1 to 128 scalar values"); + } + } + let min = object.get("minimum").and_then(serde_json::Value::as_f64); + let max = object.get("maximum").and_then(serde_json::Value::as_f64); + if object.contains_key("minimum") && min.is_none() + || object.contains_key("maximum") && max.is_none() + { + return invalid("numeric schema bounds must be finite numbers"); + } + if min.zip(max).is_some_and(|(min, max)| min > max) { + return invalid("numeric minimum must not exceed maximum"); + } + if (min.is_some() || max.is_some()) && !matches!(type_name, "number" | "integer") { + return invalid("numeric bounds require number or integer type"); + } + + Ok(maximum_class) +} + +fn schema_field_name(name: &str) -> bool { + const RESERVED: &[&str] = &[ + "id", + "plugin_id", + "owner", + "creator", + "creator_plugin_id", + "owner_plugin_id", + "provider_id", + "publisher", + "origin", + "provenance", + "resource_id", + "revision", + "permissions", + "permission_revision", + "scope", + "schema_id", + "schema_version", + "schema_digest", + "command", + "method", + "operation", + "dispatch", + "action", + "launch", + "argv", + "environment", + "executable", + "entrypoint", + "credential", + "secret", + "token", + ]; + identifier(name) && !RESERVED.contains(&name.to_ascii_lowercase().as_str()) +} + +fn decode_key(s: &str) -> Option> { + // 32 bytes have a canonical 44-character encoding: 43 data characters and + // one final `=` whose two unused bits must be zero. + let alphabet = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + if s.len() != 44 || !s.ends_with('=') || s.as_bytes()[42] == b'=' { + return None; + } + let mut out = Vec::with_capacity(33); + let bytes = s.as_bytes(); + for chunk in bytes.as_chunks::<4>().0 { + let a = alphabet.iter().position(|b| *b == chunk[0])? as u32; + let b = alphabet.iter().position(|b| *b == chunk[1])? as u32; + let c = if chunk[2] == b'=' { + 0 + } else { + alphabet.iter().position(|v| *v == chunk[2])? as u32 + }; + let d = if chunk[3] == b'=' { + 0 + } else { + alphabet.iter().position(|v| *v == chunk[3])? as u32 + }; + if chunk[3] == b'=' && (c & 0b11) != 0 { + return None; + } + if chunk[2] == b'=' && (b & 0b1111) != 0 { + return None; + } + let n = (a << 18) | (b << 12) | (c << 6) | d; + out.push((n >> 16) as u8); + if chunk[2] != b'=' { + out.push((n >> 8) as u8); + } + if chunk[3] != b'=' { + out.push(n as u8); + } + } + (out.len() == 32).then_some(out) +} +fn license_expression(s: &str) -> bool { + !s.is_empty() && s.len() <= 256 && spdx::Expression::parse(s).is_ok() +} + +/// Walk the JSON value before typed deserialization so duplicate object keys cannot +/// be silently overwritten by maps such as `resources`. +struct NoDuplicateJson; + +impl<'de> Deserialize<'de> for NoDuplicateJson { + fn deserialize(deserializer: D) -> Result + where + D: serde::Deserializer<'de>, + { + struct JsonVisitor; + impl<'de> Visitor<'de> for JsonVisitor { + type Value = NoDuplicateJson; + + fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("a JSON value without duplicate object keys") + } + fn visit_bool(self, _: bool) -> Result { + Ok(NoDuplicateJson) + } + fn visit_i64(self, _: i64) -> Result { + Ok(NoDuplicateJson) + } + fn visit_u64(self, _: u64) -> Result { + Ok(NoDuplicateJson) + } + fn visit_f64(self, _: f64) -> Result { + Ok(NoDuplicateJson) + } + fn visit_str(self, _: &str) -> Result { + Ok(NoDuplicateJson) + } + fn visit_string(self, _: String) -> Result { + Ok(NoDuplicateJson) + } + fn visit_unit(self) -> Result { + Ok(NoDuplicateJson) + } + fn visit_none(self) -> Result { + Ok(NoDuplicateJson) + } + fn visit_some(self, d: D) -> Result + where + D: serde::Deserializer<'de>, + { + NoDuplicateJson::deserialize(d) + } + fn visit_seq(self, mut seq: A) -> Result + where + A: SeqAccess<'de>, + { + while seq.next_element::()?.is_some() {} + Ok(NoDuplicateJson) + } + fn visit_map(self, mut map: A) -> Result + where + A: MapAccess<'de>, + { + let mut keys = std::collections::HashSet::new(); + while let Some(key) = map.next_key::()? { + if !keys.insert(key.clone()) { + return Err(de::Error::custom(format!( + "duplicate JSON object key `{key}`" + ))); + } + map.next_value::()?; + } + Ok(NoDuplicateJson) + } + } + deserializer.deserialize_any(JsonVisitor) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const VALID: &str = r#"{"schema":1,"id":"org.example.reader","kind":"provider","provider_id":"example-reader","name":"Example Reader","version":"1.2.3","api":{"min":"1.6.0","max":"1.7.0"},"permissions":[{"id":"library.read","required":false,"scope":"own-provider","reason":"Read imported games"}],"targets":[{"os":"linux","arch":"x86_64","abi":"gnu","entrypoint":"bin/linux-x64/plugin"}],"publisher":{"key_id":"dev-key","public_key":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="},"license":{"expression":"MIT","files":["licenses/LICENSE"]},"configuration":{"external":true,"declarative":false},"resources":{"provider":"provider.toml"}}"#; + const VALID_SCHEMA: &str = r#"{"$schema":"https://json-schema.org/draft/2020-12/schema","type":"object","properties":{"supports_cloud_sync":{"type":"boolean","x-gamenode-classification":"public"},"notes":{"type":"string","maxLength":512,"x-gamenode-classification":"sensitive"}},"required":["supports_cloud_sync"],"additionalProperties":false}"#; + + fn manifest_with_schema( + namespace: &str, + version: &str, + classification: &str, + asset: &str, + ) -> String { + let descriptor = format!( + "\"schemas\":[{{\"namespace\":\"{namespace}\",\"version\":\"{version}\",\"classification\":\"{classification}\",\"asset\":\"{asset}\"}}]" + ); + VALID.replace( + "\"resources\":{\"provider\":\"provider.toml\"}", + &format!("\"resources\":{{\"provider\":\"provider.toml\"}},{descriptor}"), + ) + } + + #[test] + fn accepts_provider_and_extension_manifest_fixtures() { + assert!(Manifest::parse_json(VALID.as_bytes()).is_ok()); + assert!(license_expression("MIT OR (Apache-2.0 AND BSD-3-Clause)")); + assert!(license_expression("LicenseRef-Internal")); + let extension = VALID.replace( + "\"kind\":\"provider\",\"provider_id\":\"example-reader\",", + "\"kind\":\"extension\",", + ); + let extension = extension.replace( + ",\"resources\":{\"provider\":\"provider.toml\"}", + ",\"resources\":{}", + ); + assert!(Manifest::parse_json(extension.as_bytes()).is_ok()); + } + + #[test] + fn rejects_reserved_official_ids_and_provider_resources_on_extensions() { + for reserved in ["org.gamenode", "org.gamenode.plugin.steam-discovery"] { + let manifest = VALID.replace("org.example.reader", reserved); + assert!( + Manifest::parse_json(manifest.as_bytes()).is_err(), + "{reserved}" + ); + } + for reserved in ["epic", "manual", "packagekit", "steam"] { + let manifest = VALID.replace("example-reader", reserved); + assert!( + Manifest::parse_json(manifest.as_bytes()).is_err(), + "{reserved}" + ); + } + let extension = VALID + .replace( + "\"kind\":\"provider\",\"provider_id\":\"example-reader\",", + "\"kind\":\"extension\",", + ) + .replace( + ",\"resources\":{\"provider\":\"provider.toml\"}", + ",\"resources\":{}", + ); + let extension_with_provider = extension.replace( + "\"resources\":{}", + "\"resources\":{\"provider\":\"provider.toml\"}", + ); + assert!(Manifest::parse_json(extension_with_provider.as_bytes()).is_err()); + } + + #[test] + fn accepts_platform_requirements_and_tested_environment_alternatives() { + let linux = VALID.replace( + "\"os\":\"linux\",\"arch\":\"x86_64\",\"abi\":\"gnu\",\"entrypoint\":\"bin/linux-x64/plugin\"", + "\"os\":\"linux\",\"arch\":\"x86_64\",\"abi\":\"gnu\",\"entrypoint\":\"bin/linux-x64/plugin\",\"requires\":{\"linux\":{\"libc\":{\"family\":\"glibc\",\"min_version\":\"2.36\"},\"distributions\":[{\"id\":\"debian\",\"versions\":[\"13\",\"13.1\"]},{\"id\":\"fedora\",\"versions\":[\"43\"]}]}},\"tested_on\":[{\"distribution\":\"debian\",\"version\":\"13\"}]", + ); + assert!(Manifest::parse_json(linux.as_bytes()).is_ok()); + + let windows = VALID.replace( + "\"os\":\"linux\",\"arch\":\"x86_64\",\"abi\":\"gnu\",\"entrypoint\":\"bin/linux-x64/plugin\"", + "\"os\":\"windows\",\"arch\":\"x86_64\",\"abi\":\"msvc\",\"entrypoint\":\"bin/windows-x64/plugin.exe\",\"requires\":{\"windows\":{\"product\":\"client\",\"min_version\":\"10.0\",\"max_version\":\"10.0.99999\",\"min_build\":22000,\"max_build\":30000}},\"tested_on\":[{\"product\":\"windows-11\",\"release\":\"23H2\"}]", + ); + assert!(Manifest::parse_json(windows.as_bytes()).is_ok()); + } + + #[test] + fn validates_signed_playtime_disclosure_and_runtime_reporting_compatibility() { + let valid = VALID + .replace( + "\"permissions\":[{\"id\":\"library.read\",\"required\":false,\"scope\":\"own-provider\",\"reason\":\"Read imported games\"}]", + "\"permissions\":[{\"id\":\"game.sessions.report\",\"required\":false,\"scope\":\"selected-game-runtime\",\"reason\":\"Identify game content\"}]", + ) + .replace( + "\"permissions\":", + "\"playtime\":{\"identifies_gameplay\":true,\"identifies_pauses\":false,\"without_pause_detection\":\"application_open\"},\"permissions\":", + ); + assert!(Manifest::parse_json(valid.as_bytes()).is_ok()); + + let report_without_gameplay = valid.replace( + "\"identifies_gameplay\":true", + "\"identifies_gameplay\":false", + ); + assert!(Manifest::parse_json(report_without_gameplay.as_bytes()).is_err()); + + let pauses_without_gameplay = VALID.replace( + "\"permissions\":", + "\"playtime\":{\"identifies_gameplay\":false,\"identifies_pauses\":true,\"without_pause_detection\":\"disabled\"},\"permissions\":", + ); + assert!(Manifest::parse_json(pauses_without_gameplay.as_bytes()).is_err()); + + let application_open_without_gameplay = VALID.replace( + "\"permissions\":", + "\"playtime\":{\"identifies_gameplay\":false,\"identifies_pauses\":false,\"without_pause_detection\":\"application_open\"},\"permissions\":", + ); + assert!(Manifest::parse_json(application_open_without_gameplay.as_bytes()).is_err()); + } + + #[test] + fn omitted_playtime_declaration_keeps_legacy_packages_disabled() { + let manifest = Manifest::parse_json(VALID.as_bytes()).unwrap(); + assert_eq!( + manifest.manifest().playtime, + PlaytimeCapabilities::default() + ); + assert_eq!( + manifest.manifest().playtime.without_pause_detection, + PlaytimeAccountingMode::Disabled + ); + } + + fn manifest_value() -> serde_json::Value { + serde_json::from_str(VALID).unwrap() + } + + fn parse_value(value: &serde_json::Value) -> Result { + Manifest::parse_json(&serde_json::to_vec(value).unwrap()) + } + + #[test] + fn accepts_signed_platform_and_permission_impact_disclosures() { + let mut value = manifest_value(); + value["supported_platforms"] = serde_json::json!(["gamecube", "wii", "nintendo.wii-u"]); + value["permissions"][0]["impact_if_disabled"] = + serde_json::json!("GameCube and Wii games are not recognised"); + let manifest = parse_value(&value).expect("valid impact and platform declarations"); + assert_eq!( + manifest.manifest().supported_platforms, + ["gamecube", "wii", "nintendo.wii-u"] + ); + assert_eq!( + manifest.manifest().permissions[0] + .impact_if_disabled + .as_deref(), + Some("GameCube and Wii games are not recognised") + ); + } + + #[test] + fn omitted_platforms_and_impact_stay_backward_compatible() { + let manifest = Manifest::parse_json(VALID.as_bytes()).unwrap(); + assert!(manifest.manifest().supported_platforms.is_empty()); + assert!( + manifest.manifest().permissions[0] + .impact_if_disabled + .is_none() + ); + } + + #[test] + fn rejects_unsafe_platforms_and_impact_disclosures() { + let mut too_many = manifest_value(); + too_many["supported_platforms"] = serde_json::json!( + (0..17) + .map(|index| format!("platform{index}")) + .collect::>() + ); + let mut duplicate = manifest_value(); + duplicate["supported_platforms"] = serde_json::json!(["gamecube", "gamecube"]); + let mut uppercase = manifest_value(); + uppercase["supported_platforms"] = serde_json::json!(["GameCube"]); + let mut control = manifest_value(); + control["supported_platforms"] = serde_json::json!(["game\u{0007}cube"]); + let mut separator = manifest_value(); + separator["supported_platforms"] = serde_json::json!(["game/cube"]); + let mut too_long = manifest_value(); + too_long["supported_platforms"] = serde_json::json!(["p".repeat(65)]); + let mut empty = manifest_value(); + empty["supported_platforms"] = serde_json::json!([""]); + let mut empty_impact = manifest_value(); + empty_impact["permissions"][0]["impact_if_disabled"] = serde_json::json!(" "); + let mut long_impact = manifest_value(); + long_impact["permissions"][0]["impact_if_disabled"] = serde_json::json!("i".repeat(513)); + let mut control_impact = manifest_value(); + control_impact["permissions"][0]["impact_if_disabled"] = + serde_json::json!("first line\nsecond line"); + let mut renamed_impact = manifest_value(); + renamed_impact["permissions"][0]["impact"] = serde_json::json!("not a declared field"); + + for (label, value) in [ + ("too many platforms", too_many), + ("duplicate platform", duplicate), + ("uppercase platform", uppercase), + ("control character", control), + ("separator character", separator), + ("overlong platform", too_long), + ("empty platform", empty), + ("blank impact", empty_impact), + ("overlong impact", long_impact), + ("multiline impact", control_impact), + ("unknown permission field", renamed_impact), + ] { + assert!( + parse_value(&value).is_err(), + "accepted {label} fixture: {value}" + ); + } + } + + #[test] + fn rejects_malformed_and_unsafe_manifest_fixtures() { + for malformed in [ + VALID.replace("\"schema\":1", "\"schema\":2"), + VALID.replace("\"provider_id\":\"example-reader\",", ""), + VALID.replace("\"kind\":\"provider\"", "\"kind\":\"extension\""), + VALID.replace("\"max\":\"1.7.0\"", "\"max\":\"1.5.0\""), + VALID.replace( + "\"entrypoint\":\"bin/linux-x64/plugin\"", + "\"entrypoint\":\"bin/linux-x64/plugin\",\"requires\":{\"windows\":{\"min_build\":22000}}", + ), + VALID.replace( + "\"entrypoint\":\"bin/linux-x64/plugin\"", + "\"entrypoint\":\"bin/linux-x64/plugin\",\"requires\":{\"macos\":{\"min_version\":\"14.0\"}}", + ), + VALID.replace( + "\"entrypoint\":\"bin/linux-x64/plugin\"", + "\"entrypoint\":\"bin/linux-x64/plugin\",\"requires\":{\"linux\":{\"libc\":{\"family\":\"glibc\",\"min_version\":\"2.x\"}}}", + ), + VALID.replace( + "\"entrypoint\":\"bin/linux-x64/plugin\"", + "\"entrypoint\":\"bin/linux-x64/plugin\",\"requires\":{\"linux\":{\"libc\":{\"family\":\"glibc\",\"min_version\":\"2.36\"}}}", + ).replace("\"abi\":\"gnu\"", "\"abi\":\"musl\""), + VALID.replace( + "\"entrypoint\":\"bin/linux-x64/plugin\"", + "\"entrypoint\":\"bin/linux-x64/plugin\",\"requires\":{\"linux\":{\"distributions\":[]}}", + ), + VALID.replace( + "\"entrypoint\":\"bin/linux-x64/plugin\"", + "\"entrypoint\":\"bin/linux-x64/plugin\",\"requires\":{\"linux\":{\"distributions\":[{\"id\":\"debian\",\"versions\":[\"13\"]},{\"id\":\"debian\",\"versions\":[\"14\"]}]}}", + ), + VALID.replace( + "\"entrypoint\":\"bin/linux-x64/plugin\"", + "\"entrypoint\":\"bin/linux-x64/plugin\",\"tested_on\":[{\"product\":\"windows-11\",\"release\":\"23H2\"}]", + ), + VALID.replace( + "\"targets\":[{\"os\":\"linux\",\"arch\":\"x86_64\",\"abi\":\"gnu\",\"entrypoint\":\"bin/linux-x64/plugin\"}]", + "\"targets\":[{\"os\":\"linux\",\"arch\":\"x86_64\",\"abi\":\"gnu\",\"entrypoint\":\"bin/linux-x64/plugin\"},{\"os\":\"linux\",\"arch\":\"x86_64\",\"abi\":\"gnu\",\"entrypoint\":\"bin/linux-x64/alternate\"}]", + ), + VALID.replace("bin/linux-x64/plugin", "../escape"), + VALID.replace("licenses/LICENSE", "../../LICENSE"), + VALID + .replace("\"MIT\"", "\"LicenseRef-Custom\"") + .replace("licenses/LICENSE", ""), + VALID.replace("\"reason\":\"Read imported games\"", "\"reason\":\"\""), + VALID.replace("\"MIT\"", "\"MIT AND\""), + VALID.replace("\"MIT\"", "\"MadeUp-License\""), + VALID.replace("\"schema\":1,", "\"schema\":1,\"schema\":1,"), + VALID.replace( + "\"provider\":\"provider.toml\"", + "\"provider\":\"first.toml\",\"provider\":\"second.toml\"", + ), + VALID.replace("AAA=", "AAB="), + VALID.replace( + "\"configuration\":{\"external\":true,\"declarative\":false},", + "\"unexpected\":true,", + ), + ] { + assert!( + Manifest::parse_json(malformed.as_bytes()).is_err(), + "accepted fixture: {malformed}" + ); + } + + let windows_base = VALID.replace( + "\"os\":\"linux\",\"arch\":\"x86_64\",\"abi\":\"gnu\",\"entrypoint\":\"bin/linux-x64/plugin\"", + "\"os\":\"windows\",\"arch\":\"x86_64\",\"abi\":\"msvc\",\"entrypoint\":\"bin/windows-x64/plugin.exe\",\"requires\":{\"windows\":{\"product\":\"client\",\"min_version\":\"10.0\",\"max_version\":\"11.0\",\"min_build\":22000,\"max_build\":30000}}", + ); + for malformed in [ + windows_base.replace("\"min_version\":\"10.0\"", "\"min_version\":\"10.x\""), + windows_base + .replace("\"min_version\":\"10.0\"", "\"min_version\":\"11.0\"") + .replace("\"max_version\":\"11.0\"", "\"max_version\":\"10.0\""), + windows_base.replace("\"min_build\":22000", "\"min_build\":31000"), + ] { + assert!( + Manifest::parse_json(malformed.as_bytes()).is_err(), + "accepted Windows range fixture: {malformed}" + ); + } + } + + #[test] + fn validates_owned_versioned_schema_assets_and_classifications() { + let manifest_text = manifest_with_schema( + "org.example.reader.compatibility", + "1.0.0", + "sensitive", + "schemas/compatibility.v1.json", + ); + let manifest = Manifest::parse_json(manifest_text.as_bytes()).unwrap(); + let assets = BTreeMap::from([( + "schemas/compatibility.v1.json".into(), + VALID_SCHEMA.as_bytes().to_vec(), + )]); + manifest + .manifest() + .validate_schema_assets(&assets) + .expect("valid packaged schema fixture"); + assert!( + manifest + .manifest() + .validate_namespace_ownership(&BTreeMap::from([( + "org.example.reader.compatibility.v2".into(), + "org.example.other".into(), + )])) + .is_err() + ); + assert!( + manifest + .manifest() + .validate_namespace_ownership(&BTreeMap::from([( + "org.example.reader.launch".into(), + "org.example.other".into(), + )])) + .is_ok() + ); + + let underclassified = Manifest::parse_json( + manifest_with_schema( + "org.example.reader.compatibility", + "1.0.0", + "public", + "schemas/compatibility.v1.json", + ) + .as_bytes(), + ) + .unwrap(); + assert!( + underclassified + .manifest() + .validate_schema_assets(&assets) + .is_err() + ); + assert!( + manifest + .manifest() + .validate_schema_assets(&BTreeMap::new()) + .is_err() + ); + } + + #[test] + fn rejects_schema_ownership_collisions_and_unsafe_assets() { + let foreign = manifest_with_schema( + "org.other.compatibility", + "1.0.0", + "sensitive", + "schemas/compat.json", + ); + assert!(Manifest::parse_json(foreign.as_bytes()).is_err()); + + let invalid_version = manifest_with_schema( + "org.example.reader.compatibility", + "v1", + "public", + "schemas/compat.json", + ); + assert!(Manifest::parse_json(invalid_version.as_bytes()).is_err()); + + let descriptor = "{\"namespace\":\"org.example.reader.compatibility\",\"version\":\"1.0.0\",\"classification\":\"public\",\"asset\":\"schemas/compat.json\"}"; + let duplicate = VALID.replace( + "\"resources\":{\"provider\":\"provider.toml\"}", + &format!("\"resources\":{{\"provider\":\"provider.toml\"}},\"schemas\":[{descriptor},{descriptor}]"), + ); + assert!(Manifest::parse_json(duplicate.as_bytes()).is_err()); + + let declared = Manifest::parse_json( + manifest_with_schema( + "org.example.reader.compatibility", + "1.0.0", + "sensitive", + "schemas/compat.json", + ) + .as_bytes(), + ) + .unwrap(); + for unsafe_asset in [ + r#"{"$schema":"https://json-schema.org/draft/2020-12/schema","$ref":"https://evil.invalid/schema.json","type":"object","properties":{},"required":[],"additionalProperties":false}"#, + r#"{"type":"object","properties":{"launch":{"type":"string","maxLength":20,"x-gamenode-classification":"public"}},"required":[],"additionalProperties":false}"#, + r#"{"type":"object","properties":{"field":{"type":"string","maxLength":20,"x-gamenode-classification":"secret"}},"required":[],"additionalProperties":false}"#, + r#"{"type":"object","properties":{"field":{"type":"string","maxLength":20}},"required":[],"additionalProperties":false}"#, + r#"{"type":"object","properties":{"field":{"type":"string","maxLength":20,"x-gamenode-classification":"public","x-gamenode-dispatch":"launch"}},"required":[],"additionalProperties":false}"#, + r#"{"type":"object","properties":{"field":{"type":"string","maxLength":5000,"x-gamenode-classification":"public"}},"required":[],"additionalProperties":false}"#, + r#"{"type":"object","properties":{"field":{"type":"string","maxLength":20,"x-gamenode-classification":"public"}},"required":[],"additionalProperties":true}"#, + r#"{"type":"object","type":"object","properties":{},"required":[],"additionalProperties":false}"#, + ] { + let assets = BTreeMap::from([( + "schemas/compat.json".into(), + unsafe_asset.as_bytes().to_vec(), + )]); + assert!( + declared.manifest().validate_schema_assets(&assets).is_err(), + "accepted schema asset: {unsafe_asset}" + ); + } + + let oversized = vec![b' '; 64 * 1024 + 1]; + assert!( + declared + .manifest() + .validate_schema_assets(&BTreeMap::from([( + "schemas/compat.json".into(), + oversized + )])) + .is_err() + ); + + let mut deep = serde_json::json!({ + "type": "string", + "maxLength": 16, + "x-gamenode-classification": "public" + }); + for _ in 0..9 { + deep = serde_json::json!({ + "type": "object", + "properties": {"child": deep}, + "required": ["child"], + "additionalProperties": false, + "x-gamenode-classification": "public" + }); + } + let deep = serde_json::to_vec(&deep).unwrap(); + assert!( + declared + .manifest() + .validate_schema_assets(&BTreeMap::from([("schemas/compat.json".into(), deep)])) + .is_err() + ); + + let mut properties = serde_json::Map::new(); + for i in 0..90 { + properties.insert( + format!("field{i}"), + serde_json::json!({ + "type": "string", + "maxLength": 16, + "x-gamenode-classification": "public" + }), + ); + } + let broad = serde_json::json!({ + "type": "object", + "properties": properties, + "required": [], + "additionalProperties": false + }); + let broad = serde_json::to_vec(&broad).unwrap(); + assert!( + declared + .manifest() + .validate_schema_assets(&BTreeMap::from([("schemas/compat.json".into(), broad)])) + .is_err() + ); + } +} diff --git a/crates/app/src/plugin_host/process.rs b/crates/app/src/plugin_host/process.rs index 270d07b71..6947f400f 100644 --- a/crates/app/src/plugin_host/process.rs +++ b/crates/app/src/plugin_host/process.rs @@ -1,7 +1,7 @@ -//! Supervision for persistent provider processes. Executable configurations are +//! Supervision for provider and scoped extension processes. Executable configurations are //! supplied only by trusted desktop composition, never by plugin RPCs. -use std::collections::HashMap; +use std::collections::{BTreeSet, HashMap}; use std::ffi::OsString; use std::path::PathBuf; use std::sync::Arc; @@ -9,20 +9,150 @@ use std::sync::atomic::{AtomicBool, Ordering}; use std::time::Duration; use gamenode_plugin_protocol::proto::ProviderOperation; +use gamenode_plugin_protocol::proto::TargetGameContext; use tokio::sync::{Mutex, Notify, oneshot, watch}; use tonic::Status; -use super::provider::{Completion, ProviderApi}; +use super::provider::{Completion, ProviderApi, SupervisedExtension}; /// Stable error returned when a provider was deliberately stopped for this run. pub(crate) const PLUGIN_STOPPED: &str = "plugin stopped"; +#[derive(Clone)] pub struct ProcessConfig { pub provider_id: String, pub executable: PathBuf, pub arguments: Vec, pub environment: Vec<(OsString, OsString)>, pub startup_timeout: Duration, + /// Signed manifest permissions which the process is allowed to request. + pub manifest_capabilities: Vec, + /// Required manifest permissions gate startup until the user has granted them. + pub required_capabilities: Vec, + /// Update declarations whose previous grants have been revoked and need a fresh review. + pub blocked_capabilities: Vec, + /// Present for managed packages; publisher key comes from host trust state. + pub integrity: Option, +} + +#[derive(Clone)] +pub struct PackageIntegrity { + pub package_root: PathBuf, + pub version: String, + pub publisher_key: [u8; 32], + pub emulation_policy: gamenode_platform::plugin_environment::EmulationPolicy, +} + +async fn verify_before_launch( + config: &ProcessConfig, + extension_trust_dir: Option, +) -> Result, Status> { + let Some(integrity) = config.integrity.clone() else { + return Ok(None); + }; + let executable = config.executable.clone(); + let config_id = config.provider_id.clone(); + let environment = gamenode_platform::plugin_environment::detect() + .await + .map_err(|_| Status::unavailable("plugin execution environment could not be detected"))?; + tokio::task::spawn_blocking(move || { + let integrity_manifest = gamenode_platform::plugin_packages::verify_package_directory( + &integrity.package_root, + &integrity.publisher_key, + ) + .map_err(|_| Status::failed_precondition("plugin package integrity check failed"))?; + let manifest_path = integrity.package_root.join("plugin.json"); + let metadata = std::fs::metadata(&manifest_path) + .map_err(|_| Status::failed_precondition("plugin manifest is unavailable"))?; + if metadata.len() > 4 * 1024 * 1024 { + return Err(Status::failed_precondition("plugin manifest is invalid")); + } + let manifest = std::fs::read(&manifest_path) + .map_err(|_| Status::failed_precondition("plugin manifest is unavailable"))?; + use sha2::Digest; + let manifest_hash = format!("{:x}", sha2::Sha256::digest(&manifest)); + if integrity_manifest.files.0.get("plugin.json") != Some(&manifest_hash) { + return Err(Status::failed_precondition( + "plugin manifest changed during compatibility validation", + )); + } + let root = std::fs::canonicalize(&integrity.package_root) + .map_err(|_| Status::failed_precondition("plugin package is unavailable"))?; + let target = std::fs::canonicalize(executable) + .map_err(|_| Status::failed_precondition("plugin executable is unavailable"))?; + if !target.starts_with(&root) || !target.is_file() { + return Err(Status::failed_precondition( + "plugin executable is outside its verified package", + )); + } + let verdict = super::compatibility::assess_package( + &root, + &target, + &manifest, + &environment, + integrity.emulation_policy, + ) + .map_err(|_| Status::failed_precondition("plugin target compatibility is invalid"))?; + if verdict.state != super::compatibility::CompatibilityState::Compatible { + return Err(Status::failed_precondition(format!( + "plugin target compatibility is {:?}: {:?}", + verdict.state, verdict.reasons + ))); + } + let playtime = if let Some(plugin_id) = config_id.strip_prefix("extension:") { + let trust = super::publisher_trust::PublisherTrustStore::open( + extension_trust_dir + .ok_or_else(|| Status::failed_precondition("extension trust is unavailable"))?, + ) + .map_err(|_| Status::failed_precondition("extension publisher trust is unavailable"))?; + if !trust + .is_pinned(plugin_id, &integrity.publisher_key) + .unwrap_or(false) + { + return Err(Status::permission_denied( + "extension publisher is no longer trusted", + )); + } + let manifest = super::package::Manifest::parse_json(&manifest).map_err(|_| { + Status::failed_precondition("verified extension manifest is invalid") + })?; + let manifest = manifest.manifest(); + if manifest.id != plugin_id + || manifest.kind != super::package::PluginKind::Extension + || manifest.version != integrity.version + { + return Err(Status::failed_precondition( + "verified extension identity changed", + )); + } + #[cfg(target_os = "linux")] + { + // The package registry copies verified bytes into a private directory. + // Only the signed, selected entrypoint needs owner execute permission. + use std::os::unix::fs::PermissionsExt; + let file = std::fs::File::open(&target).map_err(|_| { + Status::failed_precondition("extension executable is unavailable") + })?; + let metadata = file.metadata().map_err(|_| { + Status::failed_precondition("extension executable is unavailable") + })?; + if metadata.permissions().mode() & 0o7777 != 0o700 { + file.set_permissions(std::fs::Permissions::from_mode(0o700)) + .map_err(|_| { + Status::failed_precondition( + "extension executable permissions could not be set", + ) + })?; + } + } + Some(manifest.playtime) + } else { + None + }; + Ok(playtime) + }) + .await + .map_err(|_| Status::unavailable("plugin integrity worker failed"))? } struct ChildProcess { @@ -31,6 +161,169 @@ struct ChildProcess { stopped: Arc, stop: Option>, task: tokio::task::JoinHandle<()>, + is_extension: bool, +} + +/// A selection made by the host against the active library and account. +#[derive(Clone)] +pub struct ExtensionTarget { + pub(crate) context: TargetGameContext, + pub(crate) profile_epoch: u64, + pub(crate) still_selected: Arc bool + Send + Sync>, +} + +impl ExtensionTarget { + pub(crate) fn is_current(&self) -> bool { + (self.still_selected)() + } +} + +#[derive(Clone)] +pub(crate) struct ExtensionLaunch { + pub target: ExtensionTarget, + pub required_permission: &'static str, +} + +pub(crate) struct ExtensionIntent { + pub id: String, + pub store: Arc, +} + +impl Drop for ExtensionIntent { + fn drop(&mut self) { + self.store.revoke_issued(&self.id); + } +} + +async fn wait_for_invalid_target(api: &ProviderApi, target: Option<&ExtensionTarget>) { + let Some(target) = target else { + return std::future::pending().await; + }; + let profiles = api.profiles(); + let mut changes = profiles.subscribe(); + let mut interval = tokio::time::interval(Duration::from_millis(250)); + loop { + if !target.is_current() + || profiles.current().is_none_or(|profile| { + !profile.verified() || profile.epoch() != target.profile_epoch + }) + { + return; + } + tokio::select! { + _ = changes.changed() => {}, + _ = interval.tick() => {}, + } + } +} + +/// Owns the OS-level process group assigned to a supervised plugin. Dropping this guard kills +/// remaining descendants even when the plugin's main process exits first. +#[cfg(target_os = "linux")] +struct ChildTree { + process_group: rustix::process::Pid, +} + +#[cfg(target_os = "linux")] +impl ChildTree { + fn attach(pid: u32) -> Result { + rustix::process::Pid::from_raw(pid as i32) + .map(|process_group| Self { process_group }) + .ok_or_else(|| Status::unavailable("plugin process group is unavailable")) + } + + fn terminate(&self) { + let _ = + rustix::process::kill_process_group(self.process_group, rustix::process::Signal::TERM); + } + + fn kill(&self) { + let _ = + rustix::process::kill_process_group(self.process_group, rustix::process::Signal::KILL); + } +} + +#[cfg(windows)] +struct ChildTree { + job: isize, +} + +#[cfg(windows)] +impl ChildTree { + fn attach(pid: u32) -> Result { + use windows_sys::Win32::Foundation::{CloseHandle, HANDLE}; + use windows_sys::Win32::System::JobObjects::{ + AssignProcessToJobObject, CreateJobObjectW, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE, + JOBOBJECT_EXTENDED_LIMIT_INFORMATION, JobObjectExtendedLimitInformation, + SetInformationJobObject, + }; + use windows_sys::Win32::System::Threading::{ + OpenProcess, PROCESS_SET_QUOTA, PROCESS_TERMINATE, + }; + + // Fail closed rather than run a plugin process the host cannot supervise as a tree. + let process = unsafe { OpenProcess(PROCESS_SET_QUOTA | PROCESS_TERMINATE, 0, pid) }; + if process.is_null() { + return Err(Status::unavailable( + "plugin process could not be supervised", + )); + } + let job = unsafe { CreateJobObjectW(std::ptr::null(), std::ptr::null()) }; + if job.is_null() { + unsafe { CloseHandle(process) }; + return Err(Status::unavailable( + "plugin process job could not be created", + )); + } + let mut limits = JOBOBJECT_EXTENDED_LIMIT_INFORMATION::default(); + limits.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; + let configured = unsafe { + SetInformationJobObject( + job, + JobObjectExtendedLimitInformation, + &limits as *const JOBOBJECT_EXTENDED_LIMIT_INFORMATION as *const std::ffi::c_void, + std::mem::size_of::() as u32, + ) + }; + let assigned = + configured != 0 && unsafe { AssignProcessToJobObject(job, process as HANDLE) != 0 }; + unsafe { CloseHandle(process) }; + if !assigned { + unsafe { CloseHandle(job) }; + return Err(Status::unavailable( + "plugin process tree could not be supervised", + )); + } + Ok(Self { job: job as isize }) + } + + fn terminate(&self) { + // The protocol shutdown request is the graceful path on Windows; the job is killed after + // the bounded grace period when the plugin does not exit. + } + + fn kill(&self) { + use windows_sys::Win32::System::JobObjects::TerminateJobObject; + unsafe { + let _ = TerminateJobObject(self.job as windows_sys::Win32::Foundation::HANDLE, 1); + } + } +} + +#[cfg(windows)] +impl Drop for ChildTree { + fn drop(&mut self) { + use windows_sys::Win32::Foundation::{CloseHandle, HANDLE}; + self.kill(); + unsafe { CloseHandle(self.job as HANDLE) }; + } +} + +#[cfg(target_os = "linux")] +impl Drop for ChildTree { + fn drop(&mut self) { + self.kill(); + } } impl Drop for ChildProcess { @@ -40,15 +333,18 @@ impl Drop for ChildProcess { } struct Slot { - config: ProcessConfig, + config: std::sync::Mutex, child: Mutex>, } struct Inner { api: ProviderApi, endpoint: PathBuf, - slots: HashMap, + /// Process slots for every composed package. The startup composition fills the map; an + /// explicitly accepted import may add one package without replacing this shared manager. + slots: std::sync::RwLock>>, shutdown: watch::Sender, + activation: std::sync::RwLock>, /// Providers the user stopped for this run. Work is refused with a stable error until an /// explicit start clears the marker. stopped: std::sync::Mutex>, @@ -64,6 +360,25 @@ impl ProviderProcesses { api: ProviderApi, endpoint: PathBuf, configs: Vec, + ) -> Result { + Self::build(api, endpoint, configs, None, true) + } + + pub(crate) fn new_for_lifecycle( + api: ProviderApi, + endpoint: PathBuf, + configs: Vec, + activation: super::profile::PluginStateLayout, + ) -> Result { + Self::build(api, endpoint, configs, Some(activation), false) + } + + fn build( + api: ProviderApi, + endpoint: PathBuf, + configs: Vec, + activation: Option, + watch_profile: bool, ) -> Result { let mut slots = HashMap::new(); for config in configs { @@ -77,29 +392,181 @@ impl ProviderProcesses { } slots.insert( config.provider_id.clone(), - Slot { - config, + Arc::new(Slot { + config: std::sync::Mutex::new(config), child: Mutex::new(None), - }, + }), ); } let (shutdown, _) = watch::channel(false); - Ok(Self { + let manager = Self { inner: Arc::new(Inner { api, endpoint, - slots, + slots: std::sync::RwLock::new(slots), shutdown, + activation: std::sync::RwLock::new(activation), stopped: std::sync::Mutex::new(std::collections::BTreeSet::new()), }), - }) + }; + if watch_profile { + manager.spawn_profile_shutdown()?; + } + Ok(manager) + } + + /// Adds one verified package configuration to this shared process manager after construction. + /// + /// Composition state (endpoint, shutdown signal, profile fence and activation layout) is + /// reused, so a package accepted through the import review can start without rebuilding the + /// host or restarting the desktop. The provider must already be registered with the API, and + /// a duplicate slot is rejected instead of silently replacing a running package. + pub(crate) fn register_config(&self, config: ProcessConfig) -> Result<(), Status> { + if !self.inner.api.registered(&config.provider_id) || config.startup_timeout.is_zero() { + return Err(Status::invalid_argument( + "invalid provider process configuration", + )); + } + let mut slots = self + .inner + .slots + .write() + .unwrap_or_else(std::sync::PoisonError::into_inner); + if slots.contains_key(&config.provider_id) { + return Err(Status::already_exists( + "provider process is already registered", + )); + } + slots.insert( + config.provider_id.clone(), + Arc::new(Slot { + config: std::sync::Mutex::new(config), + child: Mutex::new(None), + }), + ); + Ok(()) + } + + fn slot(&self, provider_id: &str) -> Option> { + self.inner + .slots + .read() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .get(provider_id) + .cloned() + } + + fn slot_ids(&self) -> Vec { + self.inner + .slots + .read() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .keys() + .cloned() + .collect() + } + + /// Reap every third-party process when its account profile is fenced. The receiver does not + /// keep the process manager alive, so dropping the host also ends this task. + fn spawn_profile_shutdown(&self) -> Result<(), Status> { + let provider_ids = self.inner.api.third_party_provider_ids(); + if provider_ids.is_empty() { + return Ok(()); + } + let runtime = tokio::runtime::Handle::try_current().map_err(|_| { + Status::failed_precondition("plugin process host requires an async runtime") + })?; + let api = self.inner.api.clone(); + let mut changes = api.profiles().subscribe(); + let manager = Arc::downgrade(&self.inner); + runtime.spawn(async move { + let mut epoch = api.profiles().epoch(); + while changes.changed().await.is_ok() { + let current = api.profiles().epoch(); + if current == epoch { + continue; + } + epoch = current; + let Some(inner) = manager.upgrade() else { + break; + }; + let processes = ProviderProcesses { inner }; + for provider_id in &provider_ids { + processes.terminate_provider(provider_id).await; + } + } + }); + Ok(()) } pub fn has_provider(&self, id: &str) -> bool { - self.inner.slots.contains_key(id) + self.slot(id).is_some() + } + + pub(crate) fn extension_runtime_available(&self, slot_id: &str) -> bool { + !self.inner.endpoint.as_os_str().is_empty() + && !*self.inner.shutdown.borrow() + && self.has_provider(slot_id) } pub async fn ensure_started(&self, provider_id: &str) -> Result<(), Status> { + self.ensure_started_inner(provider_id, false, None, None, None) + .await + } + + /// Starts an extension only for a host-selected game and passes its one-use user intent to + /// that child. Extension launches never join a previously running process session. + pub(crate) async fn ensure_extension_started( + &self, + slot_id: &str, + launch: ExtensionLaunch, + intent: ExtensionIntent, + ) -> Result<(), Status> { + if intent.id.is_empty() || intent.id.len() > 128 { + return Err(Status::invalid_argument("invalid user intent")); + } + self.ensure_started_inner( + slot_id, + false, + Some(launch.target), + Some((intent, launch.required_permission)), + None, + ) + .await + } + + /// Negotiate an Extension session for readiness without issuing a user intent. + pub(crate) async fn ensure_extension_ready_for_update( + &self, + slot_id: &str, + target: ExtensionTarget, + candidate: ProcessConfig, + ) -> Result<(), Status> { + if candidate.provider_id != slot_id || candidate.startup_timeout.is_zero() { + return Err(Status::invalid_argument( + "invalid extension readiness configuration", + )); + } + self.ensure_started_inner(slot_id, true, Some(target), None, Some(candidate)) + .await + } + + /// One-shot readiness check used only after explicit update approval. It may start a plugin + /// whose account activation is disabled, but still requires an active profile and current + /// grants. Callers must stop it again after readiness when the user had disabled it. + pub(crate) async fn ensure_ready_for_update(&self, provider_id: &str) -> Result<(), Status> { + self.ensure_started_inner(provider_id, true, None, None, None) + .await + } + + async fn ensure_started_inner( + &self, + provider_id: &str, + allow_disabled: bool, + extension: Option, + action: Option<(ExtensionIntent, &'static str)>, + candidate: Option, + ) -> Result<(), Status> { if *self.inner.shutdown.borrow() { return Err(Status::unavailable("desktop is shutting down")); } @@ -107,22 +574,75 @@ impl ProviderProcesses { return Err(Status::unavailable(PLUGIN_STOPPED)); } let slot = self - .inner - .slots - .get(provider_id) + .slot(provider_id) .ok_or_else(|| Status::not_found("provider process is not registered"))?; + if extension.is_some() != self.inner.api.is_extension(provider_id) { + return Err(Status::failed_precondition( + "extension startup requires a selected game", + )); + } + if extension.is_some() && self.inner.endpoint.as_os_str().is_empty() { + return Err(Status::unavailable("extension runtime is unavailable")); + } + let activation_layout = self + .inner + .activation + .read() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .clone(); + let third_party_identity = self.inner.api.third_party_identity(provider_id); + let mut active_profile = None; + let mut active_profile_epoch = None; + if let Some((plugin_id, _)) = third_party_identity.as_ref() { + let profile = self.inner.api.profiles().require()?; + if let Some(target) = &extension + && (!profile.verified() + || profile.epoch() != target.profile_epoch + || profile.profile_id() != target.context.profile_id + || !target.is_current() + || activation_layout.is_none()) + { + return Err(Status::failed_precondition( + "selected extension target is unavailable", + )); + } + active_profile_epoch = Some(profile.epoch()); + if !allow_disabled && let Some(layout) = activation_layout.as_ref() { + let layout = layout.clone(); + let plugin = plugin_id.clone(); + let account = profile.clone(); + let enabled = tokio::task::spawn_blocking(move || { + layout + .open_activation(&account) + .map(|state| state.is_enabled(&plugin)) + .map_err(|error| { + Status::internal(format!("plugin activation state: {error}")) + }) + }) + .await + .map_err(|_| Status::internal("plugin activation worker failed"))??; + if !enabled { + return Err(Status::permission_denied("third-party plugin is disabled")); + } + } + active_profile = Some(profile); + } // A per-provider async lock joins concurrent startup requests without // blocking another provider or a native UI callback. let mut stored = slot.child.lock().await; if let Some(child) = stored.as_mut() { - if child.running.load(Ordering::Acquire) && self.inner.api.connected(provider_id) { + if extension.is_none() + && child.running.load(Ordering::Acquire) + && self.inner.api.connected(provider_id) + { return Ok(()); } if child.running.load(Ordering::Acquire) { if let Some(stop) = child.stop.take() { let _ = stop.send(()); } - let stopped = child.stopped.notified(); + let mut stopped = std::pin::pin!(child.stopped.notified()); + stopped.as_mut().enable(); if child.running.load(Ordering::Acquire) && tokio::time::timeout(Duration::from_secs(4), stopped) .await @@ -133,18 +653,143 @@ impl ProviderProcesses { } } stored.take(); - let launch = self.inner.api.begin_launch(provider_id)?; - let mut command = tokio::process::Command::new(&slot.config.executable); + let config = candidate.unwrap_or_else(|| { + slot.config + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .clone() + }); + if let (Some((plugin_id, publisher_fingerprint)), Some(profile), Some(layout)) = ( + third_party_identity, + active_profile, + activation_layout.as_ref(), + ) { + let grants_layout = layout.clone(); + let grants_profile = profile.clone(); + let identity = super::grants::PluginIdentity { + plugin_id, + publisher_fingerprint, + profile_id: profile.profile_id().to_owned(), + }; + let declared = config.manifest_capabilities.clone(); + let required = config.required_capabilities.clone(); + let blocked = config.blocked_capabilities.clone(); + let effective = tokio::task::spawn_blocking(move || { + let grants = grants_layout + .open_grants(&grants_profile) + .map_err(|error| { + Status::internal(format!("plugin grants unavailable: {error}")) + })?; + let effective = grants + .effective_grants(&identity) + .into_iter() + .filter(|grant| grant.state == super::grants::PermissionState::Granted) + .map(|grant| grant.permission_id) + .filter(|permission| !blocked.contains(permission)) + .collect::>(); + let missing_required = required + .iter() + .find(|permission| !effective.contains(*permission)); + if missing_required.is_some() { + return Err(Status::permission_denied( + "required plugin permissions are not granted", + )); + } + let mut allowed = vec![gamenode_plugin_protocol::capability::CONTEXT.to_owned()]; + allowed.extend( + declared + .into_iter() + .filter(|permission| effective.contains(permission)), + ); + allowed.sort(); + allowed.dedup(); + Ok(allowed) + }) + .await + .map_err(|_| Status::internal("plugin permission worker failed"))??; + if action.as_ref().is_some_and(|(_, permission)| { + !effective.iter().any(|granted| granted == *permission) + }) { + return Err(Status::permission_denied( + "extension action permission is not granted", + )); + } + if !self.inner.api.profiles().is_current(profile.epoch()) { + return Err(Status::failed_precondition( + "plugin profile changed during startup", + )); + } + self.inner.api.set_third_party_capabilities( + provider_id, + &config.manifest_capabilities, + &effective, + )?; + } + let trust_dir = activation_layout.as_ref().map(|layout| layout.trust_dir()); + let playtime = verify_before_launch(&config, trust_dir).await?; + if active_profile_epoch.is_some_and(|epoch| !self.inner.api.profiles().is_current(epoch)) { + return Err(Status::failed_precondition( + "plugin profile changed during startup", + )); + } + let (intent, required_permission) = match action { + Some((intent, permission)) => (Some(intent), Some(permission)), + None => (None, None), + }; + let intent_id = intent.as_ref().map(|intent| intent.id.clone()); + let launch = if let Some(target) = extension.as_ref() { + self.inner.api.begin_supervised_extension( + provider_id, + SupervisedExtension { + target: target.clone(), + required_permission, + expected_version: config + .integrity + .as_ref() + .map(|integrity| integrity.version.clone()), + intent, + playtime, + }, + )? + } else { + self.inner + .api + .begin_launch_for_profile(provider_id, active_profile_epoch)? + }; + let mut command = tokio::process::Command::new(&config.executable); command - .args(&slot.config.arguments) - .envs(slot.config.environment.iter().cloned()) + .args(&config.arguments) + .envs(config.environment.iter().cloned()) .env("GAMENODE_PLUGIN_ENDPOINT", &self.inner.endpoint) .env("GAMENODE_PLUGIN_OPERATION_ID", "initialization") .env("GAMENODE_PLUGIN_SESSION_CREDENTIAL", &launch.credential) + .env_remove("GAMENODE_PLUGIN_USER_INTENT_ID") + .env_remove("GAMENODE_PLUGIN_TARGET_GAME_ID") + .env_remove("GAMENODE_PLUGIN_TARGET_INSTALLATION_ID") + .env_remove("GAMENODE_PLUGIN_TARGET_PROFILE_ID") + .env_remove("GAMENODE_PLUGIN_TARGET_REVISION") .stdin(std::process::Stdio::null()) .stdout(std::process::Stdio::null()) .stderr(std::process::Stdio::null()) .kill_on_drop(true); + if let Some(target) = extension.as_ref() { + if let Some(intent) = intent_id { + command.env("GAMENODE_PLUGIN_USER_INTENT_ID", intent); + } + command + .env("GAMENODE_PLUGIN_TARGET_GAME_ID", &target.context.game_id) + .env( + "GAMENODE_PLUGIN_TARGET_INSTALLATION_ID", + &target.context.installation_id, + ) + .env( + "GAMENODE_PLUGIN_TARGET_PROFILE_ID", + &target.context.profile_id, + ) + .env("GAMENODE_PLUGIN_TARGET_REVISION", &target.context.revision); + } + #[cfg(target_os = "linux")] + command.process_group(0); #[cfg(windows)] command.creation_flags(windows_sys::Win32::System::Threading::CREATE_NO_WINDOW); let child = match command.spawn() { @@ -159,6 +804,15 @@ impl ProviderProcesses { let pid = child .id() .ok_or_else(|| Status::unavailable("provider process exited"))?; + let tree = match ChildTree::attach(pid) { + Ok(tree) => tree, + Err(error) => { + let mut child = child; + let _ = child.kill().await; + self.inner.api.disconnect(provider_id).await; + return Err(error); + } + }; let running = Arc::new(AtomicBool::new(true)); let stopped = Arc::new(Notify::new()); let (stop, stop_receiver) = oneshot::channel(); @@ -169,12 +823,15 @@ impl ProviderProcesses { api: self.inner.api.clone(), provider_id: provider_id.into(), ready: launch.ready, - startup_timeout: slot.config.startup_timeout, + closed: launch.closed, + target: extension.clone(), + startup_timeout: config.startup_timeout, startup, stop: stop_receiver, shutdown: self.inner.shutdown.subscribe(), running: running.clone(), stopped: stopped.clone(), + tree, }, )); *stored = Some(ChildProcess { @@ -183,10 +840,11 @@ impl ProviderProcesses { stopped, stop: Some(stop), task, + is_extension: extension.is_some(), }); started .await - .map_err(|_| Status::unavailable("provider startup failed"))? + .map_err(|_| Status::unavailable("plugin startup failed"))? } pub async fn execute( @@ -261,13 +919,25 @@ impl ProviderProcesses { /// Ends the current process and waits for the supervised shutdown, without changing whether /// the provider is user-stopped. pub async fn terminate_provider(&self, provider_id: &str) { - if let Some(slot) = self.inner.slots.get(provider_id) { + if !self.inner.api.is_extension(provider_id) { + let _ = self + .inner + .api + .close_configuration_before_stop(provider_id) + .await; + } + if let Some(slot) = self.slot(provider_id) { let mut child = slot.child.lock().await; if let Some(mut child) = child.take() { + if child.is_extension { + self.inner.api.request_shutdown(provider_id); + self.inner.api.disconnect(provider_id).await; + } if let Some(stop) = child.stop.take() { let _ = stop.send(()); } - let stopped = child.stopped.notified(); + let mut stopped = std::pin::pin!(child.stopped.notified()); + stopped.as_mut().enable(); if child.running.load(Ordering::Acquire) { let _ = tokio::time::timeout(Duration::from_secs(4), stopped).await; } @@ -275,10 +945,113 @@ impl ProviderProcesses { } } + /// Stop a package process before replacing its immutable verified executable configuration. + /// The per-provider child lock fences an overlapping startup until the new config is visible. + pub(crate) async fn replace_config( + &self, + provider_id: &str, + config: ProcessConfig, + ) -> Result<(), Status> { + if config.provider_id != provider_id || config.startup_timeout.is_zero() { + return Err(Status::invalid_argument( + "invalid provider process configuration", + )); + } + let slot = self + .slot(provider_id) + .ok_or_else(|| Status::not_found("provider process is not registered"))?; + let mut child = slot.child.lock().await; + if let Some(child) = child.as_mut() { + if child.is_extension { + self.inner.api.request_shutdown(provider_id); + self.inner.api.disconnect(provider_id).await; + } + if let Some(stop) = child.stop.take() { + let _ = stop.send(()); + } + let mut stopped = std::pin::pin!(child.stopped.notified()); + stopped.as_mut().enable(); + if child.running.load(Ordering::Acquire) + && tokio::time::timeout(Duration::from_secs(4), stopped) + .await + .is_err() + { + return Err(Status::unavailable("provider cleanup is still in progress")); + } + } + child.take(); + *slot + .config + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) = config; + Ok(()) + } + + /// Removes a stopped package's process slot after its package is uninstalled. + /// + /// The slot holds the immutable verified configuration. Keeping it would make a reinstall in + /// the same session fail with `provider process is already registered`, so an accepted + /// uninstall drops it after the child has been asked to stop. + pub(crate) async fn unregister_config(&self, provider_id: &str) { + let Some(slot) = self.slot(provider_id) else { + return; + }; + { + let mut child = slot.child.lock().await; + if let Some(mut child) = child.take() { + if let Some(stop) = child.stop.take() { + let _ = stop.send(()); + } + let mut stopped = std::pin::pin!(child.stopped.notified()); + stopped.as_mut().enable(); + if child.running.load(Ordering::Acquire) { + let _ = tokio::time::timeout(Duration::from_secs(4), stopped).await; + } + } + } + self.inner + .slots + .write() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .remove(provider_id); + } + + pub(crate) fn config(&self, provider_id: &str) -> Result { + let slot = self + .slot(provider_id) + .ok_or_else(|| Status::not_found("provider process is not registered"))?; + Ok(slot + .config + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .clone()) + } + + pub async fn stop_plugin(&self, plugin_id: &str) { + for provider_id in self + .inner + .api + .third_party_provider_ids_for_plugin(plugin_id) + { + self.terminate_provider(&provider_id).await; + } + } + pub async fn shutdown(&self) { + // Send correlated Close acknowledgements while provider command sessions are still + // serviceable. Broadcasting shutdown first would let supervisors tear down those sessions + // before the configuration windows could be fenced. + let provider_ids = self.slot_ids(); + for provider_id in &provider_ids { + let _ = self + .inner + .api + .close_configuration_before_stop(provider_id) + .await; + } self.inner.shutdown.send_replace(true); let _ = tokio::time::timeout(Duration::from_secs(4), async { - for id in self.inner.slots.keys() { + for id in &provider_ids { self.terminate_provider(id).await; } }) @@ -286,9 +1059,7 @@ impl ProviderProcesses { } pub async fn process_id(&self, provider_id: &str) -> Option { - self.inner - .slots - .get(provider_id)? + self.slot(provider_id)? .child .lock() .await @@ -302,12 +1073,15 @@ struct Supervision { api: ProviderApi, provider_id: String, ready: oneshot::Receiver<()>, + closed: oneshot::Receiver<()>, + target: Option, startup_timeout: Duration, startup: oneshot::Sender>, stop: oneshot::Receiver<()>, shutdown: watch::Receiver, running: Arc, stopped: Arc, + tree: ChildTree, } async fn supervise(mut child: tokio::process::Child, supervision: Supervision) { @@ -315,39 +1089,67 @@ async fn supervise(mut child: tokio::process::Child, supervision: Supervision) { api, provider_id, mut ready, + mut closed, + target, startup_timeout, startup, mut stop, mut shutdown, running, stopped, + tree, } = supervision; + let invalid_target = wait_for_invalid_target(&api, target.as_ref()); + tokio::pin!(invalid_target); let opened = tokio::select! { - ready = tokio::time::timeout(startup_timeout, &mut ready) => ready.is_ok_and(|r| r.is_ok()), + biased; + _ = &mut invalid_target => false, + _ = &mut closed, if target.is_some() => false, _ = child.wait() => false, _ = &mut stop => false, _ = shutdown.changed() => false, + ready = tokio::time::timeout(startup_timeout, &mut ready) => ready.is_ok_and(|r| r.is_ok()), }; let _ = startup.send(if opened { Ok(()) } else { Err(Status::unavailable( - "provider did not establish its command session", + "plugin did not establish its command session", )) }); if opened { - tokio::select! { - _ = child.wait() => {}, - _ = &mut stop => { - api.request_shutdown(&provider_id); - let _ = tokio::time::timeout(Duration::from_secs(3), child.wait()).await; - }, - _ = shutdown.changed() => { - api.request_shutdown(&provider_id); - let _ = tokio::time::timeout(Duration::from_secs(3), child.wait()).await; - }, + let exited = tokio::select! { + _ = child.wait() => true, + _ = &mut closed, if target.is_some() => false, + _ = &mut invalid_target => false, + _ = tokio::time::sleep(Duration::from_secs(5 * 60)), if target.is_some() => false, + _ = &mut stop => false, + _ = shutdown.changed() => false, + }; + if !exited { + api.request_shutdown(&provider_id); + } + if target.is_some() { + api.disconnect(&provider_id).await; + } + if !exited + && tokio::time::timeout(Duration::from_secs(1), child.wait()) + .await + .is_err() + { + tree.terminate(); + if tokio::time::timeout(Duration::from_secs(2), child.wait()) + .await + .is_err() + { + tree.kill(); + let _ = child.wait().await; + } } } + // A cleanly exiting plugin may have left descendants behind. The process group/job is private + // to this launch and cannot affect another plugin or the desktop process. + tree.kill(); if !matches!(child.try_wait(), Ok(Some(_))) { let _ = child.kill().await; } diff --git a/crates/app/src/plugin_host/process/tests.rs b/crates/app/src/plugin_host/process/tests.rs index 15b66061e..cd52032d2 100644 --- a/crates/app/src/plugin_host/process/tests.rs +++ b/crates/app/src/plugin_host/process/tests.rs @@ -33,7 +33,11 @@ struct ChildPlugin; #[tonic::async_trait] impl ProviderPlugin for ChildPlugin { - async fn handle(&self, _: ProviderCommand, host: HostClient) -> Result { + async fn handle( + &self, + command: ProviderCommand, + host: HostClient, + ) -> Result { if std::env::var("GAMENODE_TEST_PLUGIN_MODE").as_deref() == Ok("crash-once") && let Some(path) = std::env::var_os("GAMENODE_TEST_PLUGIN_CRASH_MARKER") && std::fs::OpenOptions::new() @@ -45,6 +49,43 @@ impl ProviderPlugin for ChildPlugin { std::process::exit(23); } assert_eq!(host.provider_context().await?.provider_id, "fixture"); + if std::env::var("GAMENODE_TEST_PLUGIN_MODE").as_deref() == Ok("provider-catalog") + && command.operation == ProviderOperation::Discover as i32 + { + let version = std::env::var("GAMENODE_TEST_PLUGIN_VERSION").unwrap_or_default(); + return Ok(OperationResult { + disposition: OperationDisposition::Completed as i32, + discovery: Some(DiscoveryResult { + provider_id: "fixture".into(), + records: vec![DiscoveryRecord { + id: format!("fixture-game-v{version}"), + name: format!("Fixture Game {version}"), + install_dir: format!("/fixtures/Fixture Game {version}"), + ..Default::default() + }], + ..Default::default() + }), + ..Default::default() + }); + } + if std::env::var("GAMENODE_TEST_PLUGIN_MODE").as_deref() == Ok("provider-catalog") + && command.operation == ProviderOperation::SyncCatalog as i32 + { + let completion = host + .catalog_chunks( + CatalogCategory::Owned, + vec![gamenode_plugin_protocol::models::CatalogRecord::new( + "fixture-game", + "Fixture Game", + )], + ) + .await?; + return Ok(OperationResult { + disposition: OperationDisposition::Completed as i32, + catalogs: vec![completion], + ..Default::default() + }); + } Ok(OperationResult { disposition: OperationDisposition::Completed as i32, ..Default::default() @@ -59,6 +100,12 @@ async fn fixture_process() { if std::env::var("GAMENODE_TEST_PLUGIN_PROCESS").as_deref() != Ok("fixture") { return; } + if let Ok(mode) = std::env::var("GAMENODE_TEST_PLUGIN_MODE") + && mode.starts_with("extension-") + { + extension_fixture_process(&mode).await; + return; + } if std::env::var("GAMENODE_TEST_PLUGIN_MODE").as_deref() == Ok("stall") { tokio::time::sleep(Duration::from_secs(30)).await; return; @@ -78,20 +125,242 @@ async fn fixture_process() { tokio::time::sleep(Duration::from_secs(30)).await; return; } + let capabilities: &[&str] = + if std::env::var("GAMENODE_TEST_PLUGIN_MODE").as_deref() == Ok("provider-catalog") { + &[ + capability::CONTEXT, + capability::CATALOG, + capability::DISCOVERY, + ] + } else { + &[capability::CONTEXT] + }; let session = Session::open( gamenode_plugin_sdk::Launch::from_env().unwrap(), "fixture.plugin", "fixture", "1.0", - &[capability::CONTEXT], + capabilities, ) .await .unwrap(); + if std::env::var("GAMENODE_TEST_PLUGIN_MODE").as_deref() == Ok("tree") { + let output = std::env::var_os("GAMENODE_TEST_PLUGIN_TREE_OUTPUT").unwrap(); + let child = std::process::Command::new("sh") + .args([ + "-c", + "trap '' TERM; while :; do printf x >> \"$1\"; sleep 0.05; done", + "plugin-child", + ]) + .arg(&output) + .spawn() + .unwrap(); + let pid_path = std::env::var_os("GAMENODE_TEST_PLUGIN_TREE_PID").unwrap(); + std::fs::write(pid_path, child.id().to_string()).unwrap(); + std::mem::forget(child); + } gamenode_plugin_sdk::run(session, Arc::new(ChildPlugin)) .await .unwrap(); } +async fn assert_extension_actions_denied( + channel: tonic::transport::Channel, + context: &ServiceContext, +) { + let target = context.target_game.as_ref().unwrap(); + let mut resource = resource_host_client::ResourceHostClient::new(channel); + let launch = resource + .games_request_launch(GameLaunchRequest { + context: Some(context.clone()), + installation_id: target.installation_id.clone(), + game_id: target.game_id.clone(), + expected_revision: target.revision.parse().unwrap(), + idempotency_key: "probe-launch".into(), + ..Default::default() + }) + .await + .unwrap_err(); + let install = resource + .games_request_install(GameInstallRequest { + context: Some(context.clone()), + installation_id: target.installation_id.clone(), + game_id: target.game_id.clone(), + idempotency_key: "probe-install".into(), + ..Default::default() + }) + .await + .unwrap_err(); + for denied in [launch, install] { + assert_eq!(denied.code(), tonic::Code::PermissionDenied); + assert_eq!( + denied.message(), + "extension session has no active target authority" + ); + } +} + +async fn extension_fixture_process(mode: &str) { + let launch = gamenode_plugin_sdk::Launch::from_env().unwrap(); + let target = launch.selected_target().unwrap(); + let version = std::env::var("GAMENODE_TEST_PLUGIN_VERSION").unwrap(); + if matches!( + mode, + "extension-stall" | "extension-probe" | "extension-gated" + ) { + assert!(std::env::var_os("GAMENODE_PLUGIN_USER_INTENT_ID").is_none()); + let channel = gamenode_plugin_sdk::connect(&launch.endpoint) + .await + .unwrap(); + let minor = gamenode_plugin_protocol::API_MINOR; + let reply = plugin_host_client::PluginHostClient::new(channel.clone()) + .open_session(OpenSessionRequest { + api_major: 1, + api_minor: minor, + min_api_major: 1, + min_api_minor: minor, + max_api_major: 1, + max_api_minor: minor, + plugin_id: "fixture.plugin".into(), + plugin_version: version, + session_credential: launch.credential, + requested_capabilities: vec![ + capability::CONTEXT.into(), + capability::GAME_LAUNCH.into(), + capability::GAMES_INSTALL.into(), + ], + session_kind: SessionKind::Extension as i32, + target_game: Some(target.clone()), + ..Default::default() + }) + .await + .unwrap() + .into_inner(); + assert!( + reply + .granted_capabilities + .contains(&capability::GAME_LAUNCH.into()) + ); + assert!( + reply + .granted_capabilities + .contains(&capability::GAMES_INSTALL.into()) + ); + let context = reply.resource_context.unwrap(); + assert!(context.provider_id.is_empty()); + assert_extension_actions_denied(channel.clone(), &context).await; + let marker = std::env::var_os("GAMENODE_TEST_PLUGIN_OPEN_MARKER").unwrap(); + std::fs::write(&marker, b"OpenSession accepted, both actions denied").unwrap(); + if mode == "extension-stall" { + tokio::time::sleep(Duration::from_secs(30)).await; + return; + } + if mode == "extension-gated" { + let ready = std::path::Path::new(&marker).with_file_name("allow-ready"); + while !ready.exists() { + tokio::time::sleep(Duration::from_millis(10)).await; + } + } + let (events, receive) = tokio::sync::mpsc::channel(1); + events + .send(ProviderEvent { + context: Some(ServiceContext { + operation_id: "initialization".into(), + profile_epoch: 0, + ..context + }), + event: Some(provider_event::Event::Ready(true)), + }) + .await + .unwrap(); + let mut commands = provider_host_client::ProviderHostClient::new(channel) + .exchange(tokio_stream::wrappers::ReceiverStream::new(receive)) + .await + .unwrap() + .into_inner(); + while commands + .message() + .await + .is_ok_and(|command| command.is_some()) + {} + drop(events); + return; + } + let mut wrong_target = target.clone(); + wrong_target.game_id.push('9'); + assert!( + Session::open_extension( + gamenode_plugin_sdk::Launch { + endpoint: launch.endpoint.clone(), + credential: launch.credential.clone(), + operation_id: launch.operation_id.clone(), + }, + "fixture.plugin", + "1.0.0", + wrong_target, + &[capability::GAME_LAUNCH], + ) + .await + .is_err() + ); + assert!( + Session::open_extension( + gamenode_plugin_sdk::Launch { + endpoint: launch.endpoint.clone(), + credential: launch.credential.clone(), + operation_id: launch.operation_id.clone(), + }, + "other.plugin", + "1.0.0", + target.clone(), + &[capability::GAME_LAUNCH], + ) + .await + .is_err() + ); + let mut session = Session::open_extension_from_launch( + launch, + "fixture.plugin", + &version, + &[capability::GAME_LAUNCH], + ) + .await + .unwrap(); + let context = session.host.resource_context().unwrap(); + assert!(context.provider_id.is_empty()); + assert_eq!(context.target_game.as_ref(), Some(&target)); + assert!(session.host.provider_context().await.is_err()); + let output = std::env::var_os("GAMENODE_TEST_PLUGIN_TREE_OUTPUT").unwrap(); + let mut child = std::process::Command::new("sh") + .args([ + "-c", + r#"trap '' TERM; while :; do printf x >> "$1"; sleep 0.05; done"#, + "plugin-child", + ]) + .arg(&output) + .spawn() + .unwrap(); + let pid_path = std::env::var_os("GAMENODE_TEST_PLUGIN_TREE_PID").unwrap(); + std::fs::write(&pid_path, child.id().to_string()).unwrap(); + // The fixture child outlives this session; reap it after the host tears down the tree. + std::thread::spawn(move || { + let _ = child.wait(); + }); + if mode == "extension-crash" { + let marker = std::env::var_os("GAMENODE_TEST_PLUGIN_CRASH_MARKER").unwrap(); + while !std::path::Path::new(&marker).exists() { + tokio::time::sleep(Duration::from_millis(15)).await; + } + std::process::exit(23); + } + while session + .commands + .message() + .await + .is_ok_and(|command| command.is_some()) + {} +} + async fn manager( executable: PathBuf, mode: &str, @@ -100,18 +369,70 @@ async fn manager( ProviderProcesses, super::super::PluginApiServer, tempfile::TempDir, +) { + manager_with_origin( + executable, + mode, + timeout, + crate::plugin_host::provider::RegistrationOrigin::Official, + ) + .await +} + +async fn manager_with_origin( + executable: PathBuf, + mode: &str, + timeout: Duration, + origin: crate::plugin_host::provider::RegistrationOrigin, +) -> ( + ProviderProcesses, + super::super::PluginApiServer, + tempfile::TempDir, +) { + manager_with_origin_and_lifecycle(executable, mode, timeout, origin, false).await +} + +async fn manager_with_origin_and_lifecycle( + executable: PathBuf, + mode: &str, + timeout: Duration, + origin: crate::plugin_host::provider::RegistrationOrigin, + managed_lifecycle: bool, +) -> ( + ProviderProcesses, + super::super::PluginApiServer, + tempfile::TempDir, ) { use std::os::unix::fs::PermissionsExt; let directory = tempfile::tempdir().unwrap(); std::fs::set_permissions(directory.path(), std::fs::Permissions::from_mode(0o700)).unwrap(); let endpoint = directory.path().join("plugins.sock"); let root = super::super::PluginApi::default(); + let extension = mode.starts_with("extension-"); + let slot_id = if extension { + super::super::provider::extension_registration_id("fixture.plugin") + } else { + "fixture".into() + }; + let mut capabilities = vec![capability::CONTEXT.into()]; + if extension { + capabilities.push(capability::GAME_LAUNCH.into()); + } root.providers .register(Registration { - provider_id: "fixture".into(), + declared_developer: "Fixture developer".into(), + package_digest: Vec::new(), + provider_id: slot_id.clone(), plugin_id: "fixture.plugin".into(), - capabilities: vec![capability::CONTEXT.into()], + kind: if extension { + crate::plugin_host::provider::RegistrationKind::Extension + } else { + crate::plugin_host::provider::RegistrationKind::Provider + }, + origin, + capabilities: capabilities.clone(), shared_catalog: false, + playtime: Default::default(), services: Arc::new(Services), }) .unwrap(); @@ -121,32 +442,152 @@ async fn manager( root.clone(), ) .unwrap(); - let manager = ProviderProcesses::new( - root.providers, - endpoint, - vec![ProcessConfig { - provider_id: "fixture".into(), - executable, - arguments: vec![ - "--exact".into(), - "plugin_host::process::tests::fixture_process".into(), - "--nocapture".into(), - ], - environment: vec![ - ("GAMENODE_TEST_PLUGIN_PROCESS".into(), "fixture".into()), - ("GAMENODE_TEST_PLUGIN_MODE".into(), mode.into()), - ( - "GAMENODE_TEST_PLUGIN_CRASH_MARKER".into(), - directory.path().join("crash-once").into_os_string(), - ), - ], - startup_timeout: timeout, - }], - ) + capabilities.push("library.read".into()); + let config = vec![ProcessConfig { + provider_id: slot_id, + executable, + arguments: vec![ + "--exact".into(), + "plugin_host::process::tests::fixture_process".into(), + "--nocapture".into(), + ], + environment: vec![ + ("GAMENODE_TEST_PLUGIN_PROCESS".into(), "fixture".into()), + ("GAMENODE_TEST_PLUGIN_MODE".into(), mode.into()), + ( + "GAMENODE_TEST_PLUGIN_CRASH_MARKER".into(), + directory.path().join("crash-once").into_os_string(), + ), + ( + "GAMENODE_TEST_PLUGIN_TREE_PID".into(), + directory.path().join("tree-child-pid").into_os_string(), + ), + ( + "GAMENODE_TEST_PLUGIN_TREE_OUTPUT".into(), + directory.path().join("tree-child-output").into_os_string(), + ), + ], + startup_timeout: timeout, + manifest_capabilities: capabilities, + required_capabilities: vec![], + blocked_capabilities: vec![], + integrity: None, + }]; + let manager = if managed_lifecycle { + ProviderProcesses::new_for_lifecycle( + root.providers, + endpoint, + config, + crate::plugin_host::profile::PluginStateLayout::new(if extension { + directory.path().join("plugin-data/state") + } else { + directory.path().join("plugin-data") + }), + ) + } else { + ProviderProcesses::new(root.providers, endpoint, config) + } .unwrap(); (manager, server, directory) } +#[tokio::test] +async fn managed_package_integrity_failure_prevents_process_start() { + let (mut processes, _server, directory) = manager( + std::env::current_exe().unwrap(), + "fixture", + Duration::from_secs(5), + ) + .await; + let inner = Arc::get_mut(&mut processes.inner).unwrap(); + let slot = Arc::get_mut(inner.slots.get_mut().unwrap().get_mut("fixture").unwrap()).unwrap(); + slot.config.get_mut().unwrap().integrity = Some(PackageIntegrity { + version: "1.0.0".into(), + package_root: directory.path().to_owned(), + publisher_key: [0; 32], + emulation_policy: gamenode_platform::plugin_environment::EmulationPolicy::RequireNative, + }); + let error = processes.ensure_started("fixture").await.unwrap_err(); + assert_eq!(error.code(), tonic::Code::FailedPrecondition); + assert!(processes.process_id("fixture").await.is_none()); + processes.shutdown().await; +} + +#[cfg(target_os = "linux")] +#[tokio::test] +async fn incompatible_signed_target_prevents_process_start() { + use base64::Engine; + use ring::signature::KeyPair; + use sha2::Digest; + use std::collections::BTreeMap; + + let package = tempfile::tempdir().unwrap(); + std::fs::create_dir_all(package.path().join("bin")).unwrap(); + std::fs::create_dir_all(package.path().join("licenses")).unwrap(); + let executable = package.path().join("bin/fixture"); + std::fs::write(&executable, b"fixture executable").unwrap(); + std::fs::write(package.path().join("licenses/LICENSE"), b"fixture license").unwrap(); + + let key = ring::signature::Ed25519KeyPair::from_seed_unchecked(&[42; 32]).unwrap(); + let public_key = key.public_key().as_ref(); + let manifest = serde_json::to_vec(&serde_json::json!({ + "schema": 1, + "id": "org.example.fixture", + "kind": "provider", + "provider_id": "fixture", + "name": "Fixture", + "version": "1.0.0", + "api": {"min": "1.6.0", "max": "1.6.0"}, + "targets": [{"os": "windows", "arch": "x86_64", "abi": "msvc", "entrypoint": "bin/fixture"}], + "publisher": { + "key_id": "fixture-key", + "public_key": base64::engine::general_purpose::STANDARD.encode(public_key) + }, + "license": {"expression": "MIT", "files": ["licenses/LICENSE"]} + })) + .unwrap(); + std::fs::write(package.path().join("plugin.json"), &manifest).unwrap(); + let payloads = [ + ("plugin.json", manifest.as_slice()), + ("bin/fixture", b"fixture executable".as_slice()), + ("licenses/LICENSE", b"fixture license".as_slice()), + ]; + let files = payloads + .into_iter() + .map(|(path, bytes)| { + ( + path.to_owned(), + format!("{:x}", sha2::Sha256::digest(bytes)), + ) + }) + .collect::>(); + let integrity = serde_json::to_vec(&serde_json::json!({"schema": 1, "files": files})).unwrap(); + let mut signed = gamenode_platform::plugin_packages::SIGNATURE_DOMAIN_PREFIX.to_vec(); + signed.extend_from_slice(&integrity); + std::fs::write(package.path().join("integrity.json"), &integrity).unwrap(); + std::fs::write( + package.path().join("signature.ed25519"), + key.sign(&signed).as_ref(), + ) + .unwrap(); + + let (mut processes, _server, _directory) = + manager(executable, "normal", Duration::from_secs(5)).await; + let inner = Arc::get_mut(&mut processes.inner).unwrap(); + let slot = Arc::get_mut(inner.slots.get_mut().unwrap().get_mut("fixture").unwrap()).unwrap(); + slot.config.get_mut().unwrap().integrity = Some(PackageIntegrity { + version: "1.0.0".into(), + package_root: package.path().to_owned(), + publisher_key: public_key.try_into().unwrap(), + emulation_policy: gamenode_platform::plugin_environment::EmulationPolicy::RequireNative, + }); + let error = processes.ensure_started("fixture").await.unwrap_err(); + assert_eq!(error.code(), tonic::Code::FailedPrecondition); + assert!(error.message().contains("OperatingSystemMismatch")); + assert!(processes.process_id("fixture").await.is_none()); + processes.shutdown().await; +} + #[tokio::test] async fn a_stopped_provider_refuses_work_until_started_with_a_fresh_session() { let (processes, _server, _directory) = manager( @@ -211,6 +652,435 @@ async fn concurrent_work_reuses_one_child_and_shutdown_reaps_it() { assert!(!processes.inner.api.connected("fixture")); } +#[tokio::test] +async fn shutdown_reaps_plugin_descendants_after_the_main_process_exits() { + let (processes, _server, directory) = manager( + std::env::current_exe().unwrap(), + "tree", + Duration::from_secs(10), + ) + .await; + processes + .execute("fixture", ProviderOperation::Initialize) + .await + .unwrap(); + let pid_path = directory.path().join("tree-child-pid"); + tokio::time::timeout(Duration::from_secs(3), async { + while !pid_path.is_file() { + tokio::task::yield_now().await; + } + }) + .await + .unwrap(); + let child_pid: u32 = std::fs::read_to_string(pid_path).unwrap().parse().unwrap(); + let output = directory.path().join("tree-child-output"); + tokio::time::timeout(Duration::from_secs(3), async { + while std::fs::metadata(&output).map_or(true, |metadata| metadata.len() == 0) { + tokio::task::yield_now().await; + } + }) + .await + .unwrap(); + assert!(std::path::Path::new(&format!("/proc/{child_pid}")).exists()); + + processes.stop_provider("fixture").await; + let stopped_at = std::fs::metadata(&output).unwrap().len(); + tokio::time::sleep(Duration::from_millis(150)).await; + assert_eq!(std::fs::metadata(&output).unwrap().len(), stopped_at); + processes.shutdown().await; +} + +#[cfg(target_os = "linux")] +#[tokio::test] +async fn profile_change_stops_third_party_process_but_not_official_processes() { + let (official, _official_server, _official_directory) = manager( + std::env::current_exe().unwrap(), + "linger", + Duration::from_secs(10), + ) + .await; + official.ensure_started("fixture").await.unwrap(); + let official_pid = official.process_id("fixture").await.unwrap(); + let (processes, _server, _directory) = manager_with_origin( + std::env::current_exe().unwrap(), + "linger", + Duration::from_secs(10), + crate::plugin_host::provider::RegistrationOrigin::ThirdParty { + publisher_fingerprint: "fixture-publisher".into(), + }, + ) + .await; + let profiles = processes.inner.api.profiles(); + profiles.update(Some("account-one"), true); + processes.ensure_started("fixture").await.unwrap(); + let old_pid = processes.process_id("fixture").await.unwrap(); + + profiles.update(None, false); + tokio::time::timeout(Duration::from_secs(5), async { + while processes.process_id("fixture").await.is_some() { + tokio::task::yield_now().await; + } + }) + .await + .expect("sign-out should stop the third-party process"); + assert!(!std::path::Path::new(&format!("/proc/{old_pid}")).exists()); + assert_eq!(official.process_id("fixture").await, Some(official_pid)); + assert!(std::path::Path::new(&format!("/proc/{official_pid}")).exists()); + processes.shutdown().await; + official.shutdown().await; +} + +#[tokio::test] +async fn managed_lifecycle_refuses_disabled_plugins_and_requires_an_active_profile() { + let (processes, _server, directory) = manager_with_origin_and_lifecycle( + std::env::current_exe().unwrap(), + "linger", + Duration::from_secs(10), + crate::plugin_host::provider::RegistrationOrigin::ThirdParty { + publisher_fingerprint: "fixture-publisher".into(), + }, + true, + ) + .await; + let state = + crate::plugin_host::profile::PluginStateLayout::new(directory.path().join("plugin-data")); + + assert_eq!( + processes + .ensure_started("fixture") + .await + .unwrap_err() + .code(), + tonic::Code::Unavailable + ); + let profiles = processes.inner.api.profiles(); + profiles.update(Some("account-one"), true); + assert_eq!( + processes + .ensure_started("fixture") + .await + .unwrap_err() + .code(), + tonic::Code::PermissionDenied + ); + let profile = profiles.current().unwrap(); + state + .open_activation(&profile) + .unwrap() + .set_enabled("fixture.plugin", true) + .unwrap(); + processes.ensure_started("fixture").await.unwrap(); + assert!(processes.process_id("fixture").await.is_some()); + processes.shutdown().await; +} + +#[tokio::test] +async fn update_readiness_can_start_a_disabled_plugin_without_persisting_enablement() { + let (processes, _server, directory) = manager_with_origin_and_lifecycle( + std::env::current_exe().unwrap(), + "linger", + Duration::from_secs(10), + crate::plugin_host::provider::RegistrationOrigin::ThirdParty { + publisher_fingerprint: "fixture-publisher".into(), + }, + true, + ) + .await; + let profiles = processes.inner.api.profiles(); + profiles.update(Some("account-one"), true); + let state = + crate::plugin_host::profile::PluginStateLayout::new(directory.path().join("plugin-data")); + let profile = profiles.current().unwrap(); + assert!( + !state + .open_activation(&profile) + .unwrap() + .is_enabled("fixture.plugin") + ); + assert_eq!( + processes + .ensure_started("fixture") + .await + .unwrap_err() + .code(), + tonic::Code::PermissionDenied + ); + + processes.ensure_ready_for_update("fixture").await.unwrap(); + assert!(processes.inner.api.connected("fixture")); + processes.stop_provider("fixture").await; + assert!( + !state + .open_activation(&profile) + .unwrap() + .is_enabled("fixture.plugin") + ); + processes.shutdown().await; +} + +#[cfg(target_os = "linux")] +#[tokio::test] +async fn activation_persists_per_account_and_remove_stops_unregisters_and_deletes_packages() { + let (processes, _server, directory) = manager_with_origin_and_lifecycle( + std::env::current_exe().unwrap(), + "linger", + Duration::from_secs(10), + crate::plugin_host::provider::RegistrationOrigin::ThirdParty { + publisher_fingerprint: "fixture-publisher".into(), + }, + true, + ) + .await; + let api = processes.inner.api.clone(); + api.profiles().update(Some("account-one"), true); + let package_source = directory.path().join("package-source"); + std::fs::create_dir(&package_source).unwrap(); + std::fs::write(package_source.join("plugin.bin"), b"fixture").unwrap(); + let registry = gamenode_platform::plugin_registry::PluginPackageRegistry::at( + directory.path().join("packages"), + ) + .unwrap(); + registry + .install_verified("fixture.plugin", "1.0.0", &package_source, true) + .unwrap(); + let lifecycle = + std::sync::Arc::new(crate::plugin_host::runtime::ThirdPartyPluginLifecycle::new( + api.clone(), + processes.clone(), + crate::plugin_host::profile::PluginStateLayout::new( + directory.path().join("plugin-data"), + ), + registry.clone(), + crate::plugin_host::managed_packages::ManagedPackageLifecycle::new(registry.clone()), + )); + lifecycle.spawn_profile_lifecycle(&tokio::runtime::Handle::current()); + + lifecycle.enable("fixture.plugin".into()).await.unwrap(); + let pid = processes.process_id("fixture").await.unwrap(); + assert!(lifecycle.enabled("fixture.plugin".into()).await.unwrap()); + + api.profiles().update(Some("account-two"), true); + tokio::time::timeout(Duration::from_secs(5), async { + while processes.process_id("fixture").await.is_some() { + tokio::task::yield_now().await; + } + }) + .await + .expect("changing accounts should stop the old process"); + assert!(!lifecycle.enabled("fixture.plugin".into()).await.unwrap()); + api.profiles().update(Some("account-one"), true); + tokio::time::timeout(Duration::from_secs(5), async { + while processes.process_id("fixture").await.is_none() { + tokio::task::yield_now().await; + } + }) + .await + .expect("the previously enabled plugin should restart for its account"); + assert!(processes.process_id("fixture").await.is_some()); + assert!(lifecycle.enabled("fixture.plugin".into()).await.unwrap()); + + lifecycle.disable("fixture.plugin".into()).await.unwrap(); + assert!(processes.process_id("fixture").await.is_none()); + assert!(!std::path::Path::new(&format!("/proc/{pid}")).exists()); + assert!(!lifecycle.enabled("fixture.plugin".into()).await.unwrap()); + + lifecycle.enable("fixture.plugin".into()).await.unwrap(); + lifecycle.remove("fixture.plugin".into()).await.unwrap(); + assert!(processes.process_id("fixture").await.is_none()); + assert!( + api.third_party_provider_ids_for_plugin("fixture.plugin") + .is_empty() + ); + assert!(registry.active("fixture.plugin").unwrap().is_none()); + processes.shutdown().await; +} + +#[cfg(target_os = "linux")] +#[tokio::test] +async fn failed_update_rolls_back_version_and_keeps_changed_permission_revoked() { + let (processes, _server, directory) = manager_with_origin_and_lifecycle( + std::env::current_exe().unwrap(), + "linger", + Duration::from_secs(10), + crate::plugin_host::provider::RegistrationOrigin::ThirdParty { + publisher_fingerprint: "fixture-publisher".into(), + }, + true, + ) + .await; + let api = processes.inner.api.clone(); + api.profiles().update(Some("account-one"), true); + let state = + crate::plugin_host::profile::PluginStateLayout::new(directory.path().join("plugin-data")); + let profile = api.profiles().current().unwrap(); + let identity = crate::plugin_host::grants::PluginIdentity { + plugin_id: "fixture.plugin".into(), + publisher_fingerprint: "fixture-publisher".into(), + profile_id: profile.profile_id().into(), + }; + let permission = "library.read"; + let scope = crate::plugin_host::grants::GrantScope::Declared { + value: "fixture provider data".into(), + }; + let request = crate::plugin_host::grants::PermissionRequest { + permission_id: permission.into(), + required: false, + allowed_scopes: std::collections::BTreeSet::from([scope.clone()]), + }; + state + .open_grants(&profile) + .unwrap() + .replace_grants( + identity.clone(), + &[request], + &[crate::plugin_host::grants::PermissionDecision { + permission_id: permission.into(), + scope, + granted: true, + }], + ) + .unwrap(); + + let package_source = directory.path().join("update-source"); + std::fs::create_dir(&package_source).unwrap(); + std::fs::write(package_source.join("plugin.bin"), b"fixture update").unwrap(); + let registry = gamenode_platform::plugin_registry::PluginPackageRegistry::at( + directory.path().join("update-registry"), + ) + .unwrap(); + registry + .install_verified("fixture.plugin", "1.0.0", &package_source, true) + .unwrap(); + let candidate = registry + .install_verified("fixture.plugin", "2.0.0", &package_source, false) + .unwrap(); + let lifecycle = crate::plugin_host::runtime::ThirdPartyPluginLifecycle::new( + api, + processes.clone(), + state.clone(), + registry.clone(), + crate::plugin_host::managed_packages::ManagedPackageLifecycle::new(registry.clone()), + ); + lifecycle.enable("fixture.plugin".into()).await.unwrap(); + assert!(processes.process_id("fixture").await.is_some()); + + let mut candidate_config = processes.config("fixture").unwrap(); + candidate_config.environment = vec![("GAMENODE_TEST_PLUGIN_MODE".into(), "stall".into())]; + candidate_config.startup_timeout = Duration::from_millis(150); + candidate_config.blocked_capabilities = vec![permission.into()]; + let error = lifecycle + .activate_update( + "fixture.plugin".into(), + "1.0.0".into(), + candidate, + candidate_config, + None, + ) + .await + .unwrap_err(); + + assert!(matches!( + error.code(), + tonic::Code::DeadlineExceeded | tonic::Code::Unavailable + )); + assert_eq!( + registry.active("fixture.plugin").unwrap().unwrap().version, + "1.0.0" + ); + let persisted = state.open_grants(&profile).unwrap(); + assert_eq!( + persisted.effective_grants(&identity)[0].state, + crate::plugin_host::grants::PermissionState::Denied + ); + assert_eq!( + processes + .config("fixture") + .unwrap() + .environment + .iter() + .find(|(key, _)| key == "GAMENODE_TEST_PLUGIN_MODE") + .map(|(_, value)| value), + Some(&std::ffi::OsString::from("linger")) + ); + assert!(processes.process_id("fixture").await.is_some()); + processes.shutdown().await; +} + +#[test] +fn interrupted_update_recovery_keeps_last_known_good_and_revoked_grants() { + let directory = tempfile::tempdir().unwrap(); + let package_source = directory.path().join("package-source"); + std::fs::create_dir(&package_source).unwrap(); + std::fs::write(package_source.join("plugin.bin"), b"complete package").unwrap(); + let registry_root = directory.path().join("packages"); + let registry = + gamenode_platform::plugin_registry::PluginPackageRegistry::at(®istry_root).unwrap(); + registry + .install_verified("fixture.plugin", "1.0.0", &package_source, true) + .unwrap(); + registry + .install_verified("fixture.plugin", "2.0.0", &package_source, false) + .unwrap(); + + let profiles = crate::plugin_host::profile::PluginProfiles::default(); + profiles.update(Some("account-one"), true); + let profile = profiles.current().unwrap(); + let state = + crate::plugin_host::profile::PluginStateLayout::new(directory.path().join("plugin-data")); + let identity = crate::plugin_host::grants::PluginIdentity { + plugin_id: "fixture.plugin".into(), + publisher_fingerprint: "fixture-publisher".into(), + profile_id: profile.profile_id().into(), + }; + let permission = "library.read"; + let scope = crate::plugin_host::grants::GrantScope::Declared { + value: "fixture provider data".into(), + }; + let request = crate::plugin_host::grants::PermissionRequest { + permission_id: permission.into(), + required: false, + allowed_scopes: std::collections::BTreeSet::from([scope.clone()]), + }; + let mut grants = state.open_grants(&profile).unwrap(); + grants + .replace_grants( + identity.clone(), + &[request], + &[crate::plugin_host::grants::PermissionDecision { + permission_id: permission.into(), + scope, + granted: true, + }], + ) + .unwrap(); + grants + .revoke_permissions( + &identity, + &std::collections::BTreeSet::from([permission.to_owned()]), + ) + .unwrap(); + let _interrupted = registry + .begin_activation("fixture.plugin", "1.0.0", "2.0.0") + .unwrap(); + assert_eq!( + registry.active("fixture.plugin").unwrap().unwrap().version, + "2.0.0" + ); + drop(registry); + + let recovered = + gamenode_platform::plugin_registry::PluginPackageRegistry::at(®istry_root).unwrap(); + assert_eq!( + recovered.active("fixture.plugin").unwrap().unwrap().version, + "1.0.0" + ); + let grants = state.open_grants(&profile).unwrap(); + assert_eq!( + grants.effective_grants(&identity)[0].state, + crate::plugin_host::grants::PermissionState::Denied + ); +} + #[tokio::test] async fn missing_executable_and_handshake_timeout_release_the_launch() { for (executable, mode) in [ @@ -308,3 +1178,663 @@ async fn invalidated_live_child_is_reaped_before_a_fresh_session_starts() { processes.shutdown().await; assert!(!std::path::Path::new(&format!("/proc/{new_pid}")).exists()); } + +struct ExtensionFixture { + processes: ProviderProcesses, + _server: super::super::PluginApiServer, + directory: tempfile::TempDir, + registry: gamenode_platform::plugin_registry::PluginPackageRegistry, + lifecycle: Arc, + state: super::super::profile::PluginStateLayout, + slot: String, + selected: Arc, +} + +impl ExtensionFixture { + async fn new(mode: &str) -> Self { + let (processes, server, directory) = manager_with_origin_and_lifecycle( + std::env::current_exe().unwrap(), + mode, + Duration::from_secs(5), + super::super::provider::RegistrationOrigin::ThirdParty { + publisher_fingerprint: Self::publisher_fingerprint(), + }, + true, + ) + .await; + let paths = gamenode_platform::paths::DataPaths::at(directory.path()); + let state = + super::super::profile::PluginStateLayout::new(paths.plugin_data_dir().join("state")); + let api = &processes.inner.api; + api.profiles().update(Some("account-one"), true); + let registry = + gamenode_platform::plugin_registry::PluginPackageRegistry::open(&paths).unwrap(); + let lifecycle = Arc::new(super::super::runtime::ThirdPartyPluginLifecycle::new( + api.clone(), + processes.clone(), + state.clone(), + registry.clone(), + super::super::managed_packages::ManagedPackageLifecycle::new(registry.clone()), + )); + let fixture = Self { + processes, + _server: server, + directory, + registry, + lifecycle, + state, + slot: super::super::provider::extension_registration_id("fixture.plugin"), + selected: Arc::new(AtomicBool::new(true)), + }; + use ring::signature::KeyPair; + std::fs::create_dir_all(fixture.state.trust_dir()).unwrap(); + super::super::publisher_trust::PublisherTrustStore::open(fixture.state.trust_dir()) + .unwrap() + .confirm_first_key( + "fixture.plugin", + Self::key().public_key().as_ref(), + &Self::publisher_fingerprint(), + ) + .unwrap(); + fixture.grant_action(); + fixture + } + + fn api(&self) -> &ProviderApi { + &self.processes.inner.api + } + + fn key() -> ring::signature::Ed25519KeyPair { + ring::signature::Ed25519KeyPair::from_seed_unchecked(&[23; 32]).unwrap() + } + + fn publisher_fingerprint() -> String { + use ring::signature::KeyPair; + super::super::publisher_trust::key_fingerprint(Self::key().public_key().as_ref()) + } + + fn grant_action(&self) { + use super::super::grants::{ + GrantScope, PermissionDecision, PermissionRequest, PluginIdentity, + }; + let profile = self.api().profiles().require().unwrap(); + let scope = GrantScope::Declared { + value: "selected game".into(), + }; + self.state + .open_grants(&profile) + .unwrap() + .replace_grants( + PluginIdentity { + plugin_id: "fixture.plugin".into(), + publisher_fingerprint: Self::publisher_fingerprint(), + profile_id: profile.profile_id().into(), + }, + &[capability::GAME_LAUNCH, capability::GAMES_INSTALL].map(|permission| { + PermissionRequest { + permission_id: permission.into(), + required: permission == capability::GAME_LAUNCH, + allowed_scopes: BTreeSet::from([scope.clone()]), + } + }), + &[capability::GAME_LAUNCH, capability::GAMES_INSTALL].map(|permission| { + PermissionDecision { + permission_id: permission.into(), + scope: scope.clone(), + granted: true, + } + }), + ) + .unwrap(); + } + + fn signed_package(&self, version: &str, mode: &str) -> tempfile::TempDir { + use base64::Engine; + use ring::signature::KeyPair; + use sha2::Digest; + use std::os::unix::fs::PermissionsExt; + let package = tempfile::tempdir().unwrap(); + let key = Self::key(); + let publisher_key: [u8; 32] = key.public_key().as_ref().try_into().unwrap(); + let manifest = serde_json::to_vec(&serde_json::json!({ + "schema": 1, + "id": "fixture.plugin", + "kind": "extension", + "name": "Fixture", + "version": version, + "api": {"min": "1.6.0", "max": "1.6.0"}, + "targets": [{"os": "linux", "arch": "x86_64", "abi": "gnu", "entrypoint": "plugin"}], + "permissions": [ + {"id": capability::GAME_LAUNCH, "required": true, "scope": "selected game", "reason": "Start the selected game"}, + {"id": capability::GAMES_INSTALL, "required": false, "scope": "selected game", "reason": "Install the selected game"} + ], + "publisher": { + "key_id": "fixture-key", + "public_key": base64::engine::general_purpose::STANDARD.encode(publisher_key) + }, + "license": {"expression": "MIT", "files": ["LICENSE"]} + })).unwrap(); + // Sign the fixture launcher itself so candidates reached through the real updater + // use the same arguments and deterministic markers as direct supervisor tests. + let shell_quote = |value: &str| format!("'{}'", value.replace('\'', "'\\''")); + let mut executable = + String::from("#!/bin/sh\nexport GAMENODE_TEST_PLUGIN_PROCESS=fixture\n"); + for (key, file) in [ + ("GAMENODE_TEST_PLUGIN_OPEN_MARKER", "opened-without-ready"), + ("GAMENODE_TEST_PLUGIN_CRASH_MARKER", "crash-once"), + ("GAMENODE_TEST_PLUGIN_TREE_PID", "tree-child-pid"), + ("GAMENODE_TEST_PLUGIN_TREE_OUTPUT", "tree-child-output"), + ] { + let path = self.directory.path().join(file); + executable.push_str(&format!( + "export {key}={}\n", + shell_quote(path.to_str().unwrap()) + )); + } + executable.push_str(&format!( + "export GAMENODE_TEST_PLUGIN_MODE={} GAMENODE_TEST_PLUGIN_VERSION={}\nexec {} --exact plugin_host::process::tests::fixture_process --nocapture\n", + shell_quote(mode), shell_quote(version), + shell_quote(std::env::current_exe().unwrap().to_str().unwrap()), + )); + let files = [ + ("plugin.json", manifest.as_slice()), + ("plugin", executable.as_bytes()), + ("LICENSE", b"fixture".as_slice()), + ] + .into_iter() + .map(|(name, data)| { + std::fs::write(package.path().join(name), data).unwrap(); + (name, format!("{:x}", sha2::Sha256::digest(data))) + }) + .collect::>(); + std::fs::set_permissions( + package.path().join("plugin"), + std::fs::Permissions::from_mode(0o700), + ) + .unwrap(); + let integrity = + serde_json::to_vec(&serde_json::json!({"schema": 1, "files": files})).unwrap(); + let mut signed = gamenode_platform::plugin_packages::SIGNATURE_DOMAIN_PREFIX.to_vec(); + signed.extend_from_slice(&integrity); + std::fs::write(package.path().join("integrity.json"), integrity).unwrap(); + std::fs::write( + package.path().join("signature.ed25519"), + key.sign(&signed).as_ref(), + ) + .unwrap(); + + package + } + + async fn package( + &self, + version: &str, + mode: &str, + active: bool, + ) -> ( + gamenode_platform::plugin_registry::InstalledPluginVersion, + ProcessConfig, + ) { + use ring::signature::KeyPair; + let publisher_key = Self::key().public_key().as_ref().try_into().unwrap(); + let package = self.signed_package(version, mode); + let installed = self + .registry + .install_verified("fixture.plugin", version, package.path(), active) + .unwrap(); + let packages = + super::super::managed_packages::ManagedPackageLifecycle::new(self.registry.clone()); + let report = packages + .inspect_candidate( + &installed.package_path, + publisher_key, + gamenode_platform::plugin_environment::EmulationPolicy::RequireNative, + ) + .await + .unwrap(); + let mut config = + super::super::runtime::managed_process_config(&installed, &report, publisher_key) + .unwrap(); + if mode == "extension-stall" { + config.startup_timeout = Duration::from_millis(700); + } + (installed, config) + } + + fn launch(&self) -> ExtensionLaunch { + let profile = self.api().profiles().require().unwrap(); + let selected = self.selected.clone(); + ExtensionLaunch { + target: ExtensionTarget { + context: TargetGameContext { + game_id: "42".into(), + installation_id: "steam:42".into(), + revision: "1".into(), + profile_id: profile.profile_id().into(), + }, + profile_epoch: profile.epoch(), + still_selected: Arc::new(move || selected.load(Ordering::Acquire)), + }, + required_permission: capability::GAME_LAUNCH, + } + } + + fn intent(&self) -> ExtensionIntent { + ExtensionIntent { + id: "one-use".into(), + store: Arc::new(super::super::intents::Intents::default()), + } + } + + async fn start(&self) -> ServiceContext { + let marker = self.directory.path().join("tree-child-pid"); + let _ = std::fs::remove_file(&marker); + self.processes + .ensure_extension_started(&self.slot, self.launch(), self.intent()) + .await + .unwrap(); + tokio::time::timeout(Duration::from_secs(3), async { + while !marker.exists() { + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .expect("child did not verify its negotiated context"); + self.api() + .resource_session_contexts() + .into_iter() + .next() + .unwrap() + } + + async fn assert_stopped(&self, context: &ServiceContext) { + tokio::time::timeout(Duration::from_secs(5), async { + while self.processes.process_id(&self.slot).await.is_some() { + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .expect("extension did not stop"); + assert!( + self.api() + .authorize_resource_session(Some(context)) + .is_err() + ); + let output = self.directory.path().join("tree-child-output"); + let size = std::fs::metadata(&output).map_or(0, |metadata| metadata.len()); + tokio::time::sleep(Duration::from_millis(150)).await; + assert_eq!( + std::fs::metadata(&output).map_or(0, |metadata| metadata.len()), + size + ); + } +} + +#[tokio::test] +async fn extension_process_fences_disable_profile_revocation_target_crash_and_removal() { + let f = ExtensionFixture::new("extension-crash").await; + let (installed, config) = f.package("1.0.0", "extension-crash", true).await; + f.processes.replace_config(&f.slot, config).await.unwrap(); + assert!(f.lifecycle.extension_runtime_available("fixture.plugin")); + assert!(f.processes.ensure_started(&f.slot).await.is_err()); + assert!( + f.processes + .ensure_extension_started(&f.slot, f.launch(), f.intent()) + .await + .is_err() + ); + + f.lifecycle.enable("fixture.plugin".into()).await.unwrap(); + let unavailable = ProviderProcesses::new_for_lifecycle( + f.api().clone(), + PathBuf::new(), + vec![f.processes.config(&f.slot).unwrap()], + f.state.clone(), + ) + .unwrap(); + assert!(!unavailable.extension_runtime_available(&f.slot)); + assert_eq!( + unavailable + .ensure_extension_started(&f.slot, f.launch(), f.intent()) + .await + .unwrap_err() + .code(), + tonic::Code::Unavailable, + ); + let mut foreign = f.launch(); + foreign.target.context.profile_id = "other-profile".into(); + assert!( + f.processes + .ensure_extension_started(&f.slot, foreign, f.intent()) + .await + .is_err() + ); + + let context = f.start().await; + f.lifecycle.disable("fixture.plugin".into()).await.unwrap(); + f.assert_stopped(&context).await; + f.lifecycle.enable("fixture.plugin".into()).await.unwrap(); + + let context = f.start().await; + let old_launch = f.launch(); + f.api().profiles().update(Some("account-two"), true); + f.assert_stopped(&context).await; + assert!(!f.lifecycle.enabled("fixture.plugin".into()).await.unwrap()); + assert!( + f.processes + .ensure_extension_started(&f.slot, old_launch, f.intent()) + .await + .is_err() + ); + f.api().profiles().update(Some("account-one"), true); + assert!(f.lifecycle.enabled("fixture.plugin".into()).await.unwrap()); + assert!(f.processes.process_id(&f.slot).await.is_none()); + + let context = f.start().await; + f.api().profiles().update(None, false); + f.assert_stopped(&context).await; + f.api().profiles().update(Some("account-one"), true); + + let context = f.start().await; + f.selected.store(false, Ordering::Release); + assert!(f.api().authorize_resource_session(Some(&context)).is_err()); + f.assert_stopped(&context).await; + assert!( + f.processes + .ensure_extension_started(&f.slot, f.launch(), f.intent()) + .await + .is_err() + ); + f.selected.store(true, Ordering::Release); + + let context = f.start().await; + f.api() + .revoke_session_permission(&f.slot, capability::GAME_LAUNCH) + .await; + f.assert_stopped(&context).await; + + let context = f.start().await; + let profile = f.api().profiles().require().unwrap(); + let snapshot = f + .lifecycle + .permission_snapshot("fixture.plugin".into()) + .await + .unwrap(); + f.lifecycle + .replace_permissions( + &tokio::sync::Mutex::new(()), + "fixture.plugin".into(), + profile.profile_id().into(), + snapshot.publisher_fingerprint.clone(), + snapshot.grant_revision, + Vec::new(), + ) + .await + .unwrap(); + f.assert_stopped(&context).await; + assert!( + f.processes + .ensure_extension_started(&f.slot, f.launch(), f.intent()) + .await + .is_err() + ); + + f.grant_action(); + let context = f.start().await; + let marker = f.directory.path().join("crash-once"); + std::fs::write(&marker, b"crash").unwrap(); + f.assert_stopped(&context).await; + std::fs::remove_file(marker).unwrap(); + + let context = f.start().await; + f.lifecycle.remove("fixture.plugin".into()).await.unwrap(); + f.assert_stopped(&context).await; + assert!(!f.lifecycle.extension_runtime_available("fixture.plugin")); + assert!(!installed.package_path.exists()); +} + +fn extension_updates(f: &ExtensionFixture) -> super::super::updates::PluginUpdateService { + let paths = gamenode_platform::paths::DataPaths::at(f.directory.path()); + let updates = super::super::updates::PluginUpdateService::open(&paths).unwrap(); + updates.set_lifecycle(f.lifecycle.clone()); + updates +} + +#[tokio::test] +async fn extension_process_idle_update_and_rollback_require_selection_and_run_no_actions() { + let f = ExtensionFixture::new("extension-hold").await; + let (original, original_config) = f.package("1.0.0", "extension-probe", true).await; + f.processes + .replace_config(&f.slot, original_config) + .await + .unwrap(); + let staged = f.signed_package("2.0.0", "extension-probe"); + let paths = gamenode_platform::paths::DataPaths::at(f.directory.path()); + let disconnected = super::super::updates::PluginUpdateService::open(&paths).unwrap(); + assert_eq!( + disconnected.managed_inventory().await.unwrap()[0].runtime_available, + Some(false) + ); + let updates = extension_updates(&f); + let marker = f.directory.path().join("opened-without-ready"); + + // Declining a staged update leaves both the process slot and registry untouched. + updates + .stage_extension_update_for_test(&original, staged.path()) + .await; + assert!( + updates + .approve("fixture.plugin", "2.0.0", None) + .await + .is_err() + ); + updates.decline("fixture.plugin").await; + assert!( + updates + .approve("fixture.plugin", "2.0.0", Some(f.launch().target)) + .await + .is_err() + ); + assert!(!marker.exists()); + assert_eq!( + f.registry.versions("fixture.plugin").unwrap(), + vec![original.clone()] + ); + assert_eq!( + f.registry.active("fixture.plugin").unwrap(), + Some(original.clone()) + ); + + // Readiness is also available for a disabled extension and preserves that preference. + updates + .stage_extension_update_for_test(&original, staged.path()) + .await; + assert_eq!( + updates + .approve("fixture.plugin", "2.0.0", Some(f.launch().target)) + .await + .unwrap(), + "2.0.0" + ); + assert!(marker.exists()); + assert!(f.processes.process_id(&f.slot).await.is_none()); + let candidate = f.registry.active("fixture.plugin").unwrap().unwrap(); + assert_eq!(candidate.version, "2.0.0"); + let inventory = updates.managed_inventory().await.unwrap(); + assert_eq!(inventory[0].runtime_available, Some(true)); + assert_eq!(inventory[0].enabled, Some(false)); + assert!(inventory[0].provider_id.is_empty()); + + f.lifecycle.enable("fixture.plugin".into()).await.unwrap(); + std::fs::remove_file(&marker).unwrap(); + let review = updates + .review_rollback("fixture.plugin", "1.0.0") + .await + .unwrap(); + assert!(review.extension_targets.is_some()); + assert!( + updates + .approve_rollback("fixture.plugin", "1.0.0", true, None) + .await + .is_err() + ); + updates.decline("fixture.plugin").await; + assert!( + updates + .approve_rollback("fixture.plugin", "1.0.0", true, Some(f.launch().target)) + .await + .is_err() + ); + assert!(!marker.exists()); + assert_eq!( + f.registry.active("fixture.plugin").unwrap(), + Some(candidate) + ); + + updates + .review_rollback("fixture.plugin", "1.0.0") + .await + .unwrap(); + assert_eq!( + updates + .approve_rollback("fixture.plugin", "1.0.0", true, Some(f.launch().target)) + .await + .unwrap(), + "1.0.0" + ); + assert!(marker.exists()); + assert!(f.processes.process_id(&f.slot).await.is_none()); + assert_eq!(f.registry.active("fixture.plugin").unwrap(), Some(original)); + assert_eq!( + updates.managed_inventory().await.unwrap()[0].enabled, + Some(true) + ); +} + +#[tokio::test] +async fn extension_readiness_denies_actions_even_after_ready() { + let f = ExtensionFixture::new("extension-hold").await; + let (_, config) = f.package("1.0.0", "extension-probe", true).await; + f.processes + .ensure_extension_ready_for_update(&f.slot, f.launch().target, config) + .await + .unwrap(); + let context = f + .api() + .resource_session_contexts() + .into_iter() + .next() + .unwrap(); + let endpoint = f.directory.path().join("plugins.sock"); + let channel = gamenode_plugin_sdk::connect(&endpoint).await.unwrap(); + assert_extension_actions_denied(channel, &context).await; + f.processes.stop_provider(&f.slot).await; + assert!(!f.api().connected(&f.slot)); +} + +#[tokio::test] +async fn extension_process_update_conditions_keep_previous_version_without_ready() { + for invalidation in ["none", "target", "profile", "grants"] { + let f = ExtensionFixture::new("extension-hold").await; + let (original, original_config) = f.package("1.0.0", "extension-hold", true).await; + f.processes + .replace_config(&f.slot, original_config.clone()) + .await + .unwrap(); + let mode = if invalidation == "grants" { + "extension-gated" + } else { + "extension-stall" + }; + let (candidate, mut config) = f.package("2.0.0", mode, false).await; + if invalidation != "none" { + config.startup_timeout = Duration::from_secs(5); + } + let marker = f.directory.path().join("opened-without-ready"); + let lifecycle = f.lifecycle.clone(); + let target = f.launch().target; + let activation = tokio::spawn(async move { + lifecycle + .activate_update( + "fixture.plugin".into(), + "1.0.0".into(), + candidate, + config, + Some(target), + ) + .await + }); + tokio::time::timeout(Duration::from_secs(6), async { + while !marker.exists() { + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .expect("candidate did not complete OpenSession"); + assert_eq!( + f.registry.active("fixture.plugin").unwrap(), + Some(original.clone()) + ); + assert!(!f.api().profiles().transition_is_locked()); + tokio::time::timeout( + Duration::from_secs(2), + tokio::task::spawn_blocking(|| { + let _publisher = super::super::managed_packages::lock_publisher_identity(); + }), + ) + .await + .unwrap() + .unwrap(); + match invalidation { + "target" => f.selected.store(false, Ordering::Release), + "profile" => { + f.api().profiles().update(Some("account-two"), true); + f.api().profiles().update(Some("account-one"), true); + } + "grants" => { + use super::super::grants::{PermissionState, PluginIdentity}; + let profile = f.api().profiles().require().unwrap(); + let identity = PluginIdentity { + plugin_id: "fixture.plugin".into(), + publisher_fingerprint: ExtensionFixture::publisher_fingerprint(), + profile_id: profile.profile_id().to_owned(), + }; + f.state + .open_grants(&profile) + .unwrap() + .revoke_permissions( + &identity, + &BTreeSet::from([capability::GAMES_INSTALL.into()]), + ) + .unwrap(); + std::fs::write(f.directory.path().join("allow-ready"), b"ready").unwrap(); + let error = activation.await.unwrap().unwrap_err(); + assert_eq!(error.message(), "extension grants changed during readiness"); + assert!( + f.state + .open_grants(&profile) + .unwrap() + .effective_grants(&identity) + .iter() + .any(|grant| grant.permission_id == capability::GAMES_INSTALL + && grant.state == PermissionState::Denied) + ); + assert!(f.processes.process_id(&f.slot).await.is_none()); + assert_eq!(f.registry.active("fixture.plugin").unwrap(), Some(original)); + assert_eq!( + f.processes.config(&f.slot).unwrap().executable, + original_config.executable + ); + continue; + } + _ => {} + } + assert!(activation.await.unwrap().is_err()); + assert!(f.processes.process_id(&f.slot).await.is_none()); + assert_eq!(f.registry.active("fixture.plugin").unwrap(), Some(original)); + assert_eq!( + f.processes.config(&f.slot).unwrap().executable, + original_config.executable + ); + } +} diff --git a/crates/app/src/plugin_host/profile.rs b/crates/app/src/plugin_host/profile.rs new file mode 100644 index 000000000..124ce87e2 --- /dev/null +++ b/crates/app/src/plugin_host/profile.rs @@ -0,0 +1,672 @@ +//! Binds third-party plugin profiles to the signed-in GameNode account. +//! +//! GameNode has no signed-out or local usage mode, so there is no anonymous plugin profile either. +//! The engine reports who is signed in: the verified account, or the cached last account while a +//! restored session awaits verification. Without an account the host issues no profile context, +//! starts no third-party process and answers profile-scoped services with UNAVAILABLE. Sign-out, +//! a rejected session and a verified account that differs from the cached one are profile changes: +//! they advance the epoch, which fences every context issued for the previous profile. +//! +//! Persistence is layered. Installed packages and publisher trust belong to the OS user; +//! activation, grants, configuration and private data belong to the account profile. + +use crate::plugin_host::grants::{ + GrantError, PermissionGrantStore, PluginIdentity, atomic_replace, ensure_private_dir, + ensure_private_file, sync_dir, +}; +use crate::plugin_host::namespace::ExternalNamespaceResolver; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use std::{ + collections::BTreeSet, + fs::{self, File, OpenOptions}, + io::{self, Read, Write}, + path::{Path, PathBuf}, + sync::{ + Mutex, + atomic::{AtomicU64, Ordering}, + }, +}; +use tokio::sync::watch; +use tonic::Status; + +const ACTIVATION_FILE: &str = "plugin-activation.json"; +const MAX_ACTIVATION_BYTES: u64 = 1024 * 1024; +static NEXT_TEMP: AtomicU64 = AtomicU64::new(1); + +/// The plugin profile of one GameNode account, valid while its epoch is current. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ProfileContext { + profile_id: String, + epoch: u64, + verified: bool, +} + +impl ProfileContext { + /// Opaque profile id derived from the account id. It is safe as a directory name and does + /// not reveal the account id in paths or namespace keys. + pub fn profile_id(&self) -> &str { + &self.profile_id + } + + pub fn epoch(&self) -> u64 { + self.epoch + } + + /// False while a restored session runs on the cached account before verification. + pub fn verified(&self) -> bool { + self.verified + } +} + +/// Derives the plugin profile id of a GameNode account. +pub fn profile_id_for_account(account_id: &str) -> String { + let mut hash = Sha256::new(); + hash.update(b"gamenode.plugin-profile.v1\0"); + hash.update(account_id.as_bytes()); + hash.finalize()[..16] + .iter() + .map(|byte| format!("{byte:02x}")) + .collect() +} + +/// What a profile update did to previously issued contexts. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ProfileTransition { + /// Same account (possibly now verified): issued contexts stay valid. + Unchanged, + /// The profile was replaced or removed: contexts of the previous profile are fenced. + Fenced, +} + +#[derive(Debug, Default)] +struct State { + account_id: Option, + current: Option, + epoch: u64, +} + +/// Host-owned source of the active plugin profile. +pub struct PluginProfiles { + transition: Mutex<()>, + state: Mutex, + layout: Mutex>, + changes: watch::Sender>, + permission_changes: watch::Sender<()>, +} + +impl Default for PluginProfiles { + fn default() -> Self { + Self { + transition: Mutex::new(()), + state: Mutex::new(State { + epoch: 1, + ..State::default() + }), + layout: Mutex::new(None), + changes: watch::Sender::new(None), + permission_changes: watch::Sender::new(()), + } + } +} + +impl std::fmt::Debug for PluginProfiles { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("PluginProfiles") + .field("current", &self.current()) + .finish() + } +} + +pub(crate) struct LockedProfileTransition<'a> { + profiles: &'a PluginProfiles, + _guard: std::sync::MutexGuard<'a, ()>, +} + +impl LockedProfileTransition<'_> { + /// Applies who is signed in. `account_id` is the verified account, or the cached last account + /// while a restored session is unverified; `None` after sign-out or a rejected session. + pub fn update(&self, account_id: Option<&str>, verified: bool) -> ProfileTransition { + let mut state = lock(&self.profiles.state); + let account_id = account_id.filter(|id| !id.trim().is_empty()); + if state.account_id.as_deref() == account_id { + if let Some(current) = state.current.as_mut() + && current.verified != verified + { + // Verifying the cached account keeps the same profile and its contexts. + current.verified = verified; + let current = state.current.clone(); + self.profiles.changes.send_replace(current); + } + return ProfileTransition::Unchanged; + } + state.epoch += 1; + state.account_id = account_id.map(str::to_owned); + state.current = account_id.map(|id| ProfileContext { + profile_id: profile_id_for_account(id), + epoch: state.epoch, + verified, + }); + let current = state.current.clone(); + drop(state); + self.profiles.changes.send_replace(current); + ProfileTransition::Fenced + } +} + +impl PluginProfiles { + /// Supplies the host-owned root for profile-scoped plugin grants and activation. + pub fn set_state_layout(&self, layout: PluginStateLayout) { + *lock(&self.layout) = Some(layout); + } + + /// Serializes account changes with durable plugin permission and shared-data commits. + /// Profile reads use a separate state lock so they can still run while the commit is syncing to disk. + pub(crate) fn lock_transition(&self) -> LockedProfileTransition<'_> { + LockedProfileTransition { + profiles: self, + _guard: lock(&self.transition), + } + } + + #[cfg(test)] + pub(crate) fn transition_is_locked(&self) -> bool { + matches!( + self.transition.try_lock(), + Err(std::sync::TryLockError::WouldBlock) + ) + } + + pub fn update(&self, account_id: Option<&str>, verified: bool) -> ProfileTransition { + self.lock_transition().update(account_id, verified) + } + + pub fn current(&self) -> Option { + lock(&self.state).current.clone() + } + + /// The current profile epoch. It advances on every profile change, including sign-out, so a + /// context captured earlier can never match a later profile. + pub fn epoch(&self) -> u64 { + lock(&self.state).epoch + } + + pub fn is_current(&self, epoch: u64) -> bool { + lock(&self.state) + .current + .as_ref() + .is_some_and(|current| current.epoch == epoch) + } + + /// The active profile, or UNAVAILABLE when no account session exists. This is distinct from + /// a permission denial: the plugin did nothing wrong, there is just no profile to serve. + pub fn require(&self) -> Result { + self.current().ok_or_else(no_profile) + } + + /// Third-party processes may run only while an account profile is active. + pub fn may_start_third_party(&self) -> bool { + lock(&self.state).current.is_some() + } + + /// Namespace resolver for an authenticated plugin in the active profile. + pub fn resolver( + &self, + plugin_id: &str, + publisher_fingerprint: &str, + provider_id: Option<&str>, + ) -> Result { + let profile = self.require()?; + ExternalNamespaceResolver::new( + PluginIdentity { + plugin_id: plugin_id.into(), + publisher_fingerprint: publisher_fingerprint.into(), + profile_id: profile.profile_id.clone(), + }, + provider_id.map(str::to_owned), + profile.epoch, + ) + .map_err(|_| Status::invalid_argument("invalid plugin identity")) + } + + /// Authenticated plugin identities known in the active profile's grant store. + pub fn identities(&self) -> Result, Status> { + let profile = self.require()?; + let layout = lock(&self.layout) + .clone() + .ok_or_else(|| Status::unavailable("plugin state layout is unavailable"))?; + let grants = layout + .open_grants(&profile) + .map_err(|_| Status::unavailable("plugin grants are unavailable"))?; + Ok(grants.identities()) + } + + /// Whether an authenticated plugin identity is enabled in the active account profile. + pub fn is_enabled(&self, plugin_id: &str) -> Result { + let profile = self.require()?; + let layout = lock(&self.layout) + .clone() + .ok_or_else(|| Status::unavailable("plugin state layout is unavailable"))?; + let activation = layout + .open_activation(&profile) + .map_err(|_| Status::unavailable("plugin activation state is unavailable"))?; + Ok(activation.is_enabled(plugin_id)) + } + + /// Whether this profile allows one signed plugin to contribute measured playtime. + /// The preference is independent of discovery, launch grants and plugin activation. + pub fn is_playtime_accounting_enabled(&self, plugin_id: &str) -> Result { + let profile = self.require()?; + let layout = lock(&self.layout) + .clone() + .ok_or_else(|| Status::unavailable("plugin state layout is unavailable"))?; + let activation = layout + .open_activation(&profile) + .map_err(|_| Status::unavailable("plugin accounting preference is unavailable"))?; + Ok(activation.is_playtime_accounting_enabled(plugin_id)) + } + + /// Persist the accounting choice before it is applied to subsequent runtime reports. + pub fn set_playtime_accounting_enabled( + &self, + plugin_id: &str, + enabled: bool, + ) -> Result<(), Status> { + let profile = self.require()?; + let layout = lock(&self.layout) + .clone() + .ok_or_else(|| Status::unavailable("plugin state layout is unavailable"))?; + let mut activation = layout + .open_activation(&profile) + .map_err(|_| Status::unavailable("plugin accounting preference is unavailable"))?; + activation + .set_playtime_accounting_enabled(plugin_id, enabled) + .map_err(|_| Status::unavailable("plugin accounting preference could not be saved")) + } + + /// Current host-consented permissions for a package identity in the active profile. + /// Used only for host actions explicitly initiated by the user, never to construct a plugin + /// RPC context or elevate a plugin request. + pub fn granted_permissions( + &self, + plugin_id: &str, + publisher_fingerprint: &str, + ) -> Result<(u64, std::collections::BTreeSet), Status> { + use crate::plugin_host::grants::PermissionState; + + let profile = self.require()?; + let layout = lock(&self.layout) + .clone() + .ok_or_else(|| Status::unavailable("plugin state layout is unavailable"))?; + let grants = layout + .open_grants(&profile) + .map_err(|_| Status::unavailable("plugin grants are unavailable"))?; + let identity = crate::plugin_host::grants::PluginIdentity { + plugin_id: plugin_id.to_owned(), + publisher_fingerprint: publisher_fingerprint.to_owned(), + profile_id: profile.profile_id, + }; + let revision = grants.revision(&identity); + let permissions = grants + .effective_grants(&identity) + .into_iter() + .filter(|grant| grant.state == PermissionState::Granted) + .map(|grant| grant.permission_id) + .collect(); + Ok((revision, permissions)) + } + + /// Notified with the new profile (or `None`) after every change. + pub fn subscribe(&self) -> watch::Receiver> { + self.changes.subscribe() + } + + pub(crate) fn subscribe_permissions(&self) -> watch::Receiver<()> { + self.permission_changes.subscribe() + } + + /// Wake in-flight work after a permission decision has been persisted. + pub(crate) fn notify_permissions_changed(&self) { + self.permission_changes.send_replace(()); + } +} + +fn lock(mutex: &Mutex) -> std::sync::MutexGuard<'_, T> { + mutex + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) +} + +pub(crate) fn no_profile() -> Status { + Status::unavailable("no GameNode account profile is active") +} + +/// Where third-party plugin state lives for one OS user. +/// +/// ```text +/// /packages/ installed packages (OS user) +/// /trust/ publisher-key trust (OS user) +/// /accounts// activation, grants, configuration, data (account) +/// ``` +#[derive(Clone, Debug)] +pub struct PluginStateLayout { + root: PathBuf, + /// The OS-user `plugin-data` folder of the private durable stores. Only the managed layout + /// knows it; a layout built with [`Self::new`] keeps private data out of reach. + data_root: Option, +} + +impl PluginStateLayout { + pub fn new(root: impl Into) -> Self { + Self { + root: root.into(), + data_root: None, + } + } + + /// Refuse the development-only plugin state layouts instead of silently ignoring them or + /// importing user trust/grants without review. This check is read-only and must run before + /// opening any current plugin stores. + pub(crate) fn refuse_legacy_layouts( + paths: &gamenode_platform::paths::DataPaths, + ) -> io::Result<()> { + for legacy in [ + paths.private_dir().join("publisher-keys.json"), + paths.data_dir().join("plugin-state"), + ] { + match fs::symlink_metadata(&legacy) { + Ok(_) => { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + format!( + "unsupported legacy third-party plugin state at {}; it was left untouched", + legacy.display() + ), + )); + } + Err(error) if error.kind() == io::ErrorKind::NotFound => {} + Err(error) => return Err(error), + } + } + Ok(()) + } + + /// The desktop runtime's existing state directory for managed plugins. + pub fn managed(paths: &gamenode_platform::paths::DataPaths) -> Self { + Self { + root: paths.plugin_data_dir().join("state"), + data_root: Some(paths.plugin_data_dir()), + } + } + + /// The OS-user `plugin-data` root of private plugin namespaces, when this layout came from + /// [`Self::managed`]. A bundle uninstall uses it to apply the delete-data retention choice. + pub fn plugin_data_root(&self) -> Option<&Path> { + self.data_root.as_deref() + } + + pub(super) fn prepare_managed(paths: &gamenode_platform::paths::DataPaths) -> io::Result { + Self::refuse_legacy_layouts(paths)?; + let layout = Self::managed(paths); + ensure_private_dir(&paths.plugin_data_dir())?; + ensure_private_dir(&layout.root)?; + Ok(layout) + } + + /// Installed packages, shared by every account of this OS user. + pub fn packages_dir(&self) -> PathBuf { + self.root.join("packages") + } + + /// Publisher-key trust, shared by every account of this OS user. + pub fn trust_dir(&self) -> PathBuf { + self.root.join("trust") + } + + /// Private state of one account profile. Never shared with another account. + pub fn account_dir(&self, profile: &ProfileContext) -> io::Result { + ensure_private_dir(&self.root)?; + let accounts = self.root.join("accounts"); + ensure_private_dir(&accounts)?; + let dir = accounts.join(&profile.profile_id); + ensure_private_dir(&dir)?; + Ok(dir) + } + + /// The permission grants of one account profile. + pub fn open_grants( + &self, + profile: &ProfileContext, + ) -> Result { + PermissionGrantStore::open(self.account_dir(profile)?) + } + + /// The activation (enabled) state of one account profile. + pub fn open_activation( + &self, + profile: &ProfileContext, + ) -> Result { + AccountActivationStore::open(self.account_dir(profile)?) + } + + /// Removes a plugin's activation and grants from every account without touching its private + /// configuration, storage, or secrets. Existing account directories are never followed when + /// they are symlinks. + pub fn remove_plugin_account_state(&self, plugin_id: &str) -> Result<(), GrantError> { + if plugin_id.trim().is_empty() + || plugin_id.len() > 256 + || plugin_id.chars().any(char::is_control) + { + return Err(GrantError::InvalidIdentity); + } + for account_dir in self.account_dirs()? { + let mut activation = AccountActivationStore::open(account_dir.clone())?; + if activation.is_enabled(plugin_id) { + activation.set_enabled(plugin_id, false)?; + } + let mut grants = PermissionGrantStore::open(&account_dir)?; + grants.remove_plugin(plugin_id)?; + } + Ok(()) + } + + /// Invalidates changed network declarations even in profiles that were inactive at update. + pub(super) fn revoke_network_for_package( + &self, + plugin_id: &str, + publisher_fingerprint: &str, + ) -> Result<(), GrantError> { + let network = + BTreeSet::from([gamenode_plugin_protocol::capability::NETWORK_FETCH.to_owned()]); + for account_dir in self.account_dirs()? { + let mut grants = PermissionGrantStore::open(&account_dir)?; + for identity in grants.identities().into_iter().filter(|identity| { + identity.plugin_id == plugin_id + && identity.publisher_fingerprint == publisher_fingerprint + }) { + grants.revoke_permissions(&identity, &network)?; + } + } + Ok(()) + } + + fn account_dirs(&self) -> Result, GrantError> { + match fs::symlink_metadata(&self.root) { + Ok(metadata) if metadata.is_dir() && !metadata.file_type().is_symlink() => {} + Ok(_) => return Err(GrantError::InvalidStore("unsafe plugin state root".into())), + Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()), + Err(error) => return Err(error.into()), + } + let accounts = self.root.join("accounts"); + match fs::symlink_metadata(&accounts) { + Ok(metadata) if metadata.is_dir() && !metadata.file_type().is_symlink() => {} + Ok(_) => return Err(GrantError::InvalidStore("unsafe accounts directory".into())), + Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()), + Err(error) => return Err(error.into()), + } + let entries = fs::read_dir(&accounts)?; + let mut directories = Vec::new(); + for entry in entries { + let entry = entry?; + let account_dir = entry.path(); + let metadata = fs::symlink_metadata(&account_dir)?; + if metadata.file_type().is_symlink() { + return Err(GrantError::InvalidStore("unsafe account directory".into())); + } + if metadata.is_dir() { + directories.push(account_dir); + } + } + Ok(directories) + } +} + +#[derive(Clone, Debug, Default, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct ActivationFile { + schema: u32, + enabled: BTreeSet, + #[serde(default)] + accounting_disabled: BTreeSet, +} + +/// Which installed plugins one account has enabled. Absent plugins are disabled. +#[derive(Debug)] +pub struct AccountActivationStore { + path: PathBuf, + state: ActivationFile, +} + +impl AccountActivationStore { + fn open(account_dir: PathBuf) -> Result { + let path = account_dir.join(ACTIVATION_FILE); + let state = match fs::symlink_metadata(&path) { + Ok(meta) if meta.file_type().is_file() && !meta.file_type().is_symlink() => { + if meta.len() > MAX_ACTIVATION_BYTES { + return Err(GrantError::InvalidStore("file exceeds size limit".into())); + } + ensure_private_file(&path)?; + let mut bytes = Vec::with_capacity(meta.len() as usize); + File::open(&path)? + .take(MAX_ACTIVATION_BYTES + 1) + .read_to_end(&mut bytes)?; + let state: ActivationFile = serde_json::from_slice(&bytes) + .map_err(|error| GrantError::InvalidStore(error.to_string()))?; + if state.schema != 1 { + return Err(GrantError::InvalidStore("unsupported schema".into())); + } + state + } + Ok(_) => return Err(GrantError::InvalidStore("unsafe activation file".into())), + Err(error) if error.kind() == io::ErrorKind::NotFound => ActivationFile { + schema: 1, + ..ActivationFile::default() + }, + Err(error) => return Err(error.into()), + }; + Ok(Self { path, state }) + } + + pub fn is_enabled(&self, plugin_id: &str) -> bool { + self.state.enabled.contains(plugin_id) + } + + pub fn enabled(&self) -> impl Iterator { + self.state.enabled.iter().map(String::as_str) + } + + pub fn is_playtime_accounting_enabled(&self, plugin_id: &str) -> bool { + !self.state.accounting_disabled.contains(plugin_id) + } + + pub fn set_playtime_accounting_enabled( + &mut self, + plugin_id: &str, + enabled: bool, + ) -> Result<(), GrantError> { + if plugin_id.trim().is_empty() + || plugin_id.len() > 256 + || plugin_id.chars().any(char::is_control) + { + return Err(GrantError::InvalidIdentity); + } + let mut next = self.state.clone(); + if enabled { + next.accounting_disabled.remove(plugin_id); + } else { + next.accounting_disabled.insert(plugin_id.to_owned()); + } + persist(&self.path, &next)?; + self.state = next; + Ok(()) + } + + /// Persists the change before it takes effect; a failed write leaves the state unchanged. + pub fn set_enabled(&mut self, plugin_id: &str, enabled: bool) -> Result<(), GrantError> { + if plugin_id.trim().is_empty() + || plugin_id.len() > 256 + || plugin_id.chars().any(char::is_control) + { + return Err(GrantError::InvalidIdentity); + } + let mut next = self.state.clone(); + if enabled { + next.enabled.insert(plugin_id.to_owned()); + } else { + next.enabled.remove(plugin_id); + } + persist(&self.path, &next)?; + self.state = next; + Ok(()) + } + + pub fn remove_plugin(&mut self, plugin_id: &str) -> Result<(), GrantError> { + if plugin_id.trim().is_empty() + || plugin_id.len() > 256 + || plugin_id.chars().any(char::is_control) + { + return Err(GrantError::InvalidIdentity); + } + let mut next = self.state.clone(); + if next.enabled.remove(plugin_id) { + persist(&self.path, &next)?; + self.state = next; + } + Ok(()) + } +} + +fn persist(path: &Path, state: &ActivationFile) -> Result<(), GrantError> { + let parent = path + .parent() + .ok_or_else(|| GrantError::InvalidStore("store has no parent".into()))?; + ensure_private_dir(parent)?; + let bytes = + serde_json::to_vec(state).map_err(|error| GrantError::InvalidStore(error.to_string()))?; + let temp = parent.join(format!( + ".plugin-activation-{}-{}", + std::process::id(), + NEXT_TEMP.fetch_add(1, Ordering::Relaxed) + )); + let mut options = OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600); + } + let mut file = options.open(&temp)?; + let result = (|| -> io::Result<()> { + file.write_all(&bytes)?; + file.sync_all()?; + atomic_replace(&temp, path)?; + sync_dir(parent) + })(); + if result.is_err() { + let _ = fs::remove_file(&temp); + } + result.map_err(Into::into) +} + +#[cfg(test)] +mod tests; diff --git a/crates/app/src/plugin_host/profile/tests.rs b/crates/app/src/plugin_host/profile/tests.rs new file mode 100644 index 000000000..d76f35262 --- /dev/null +++ b/crates/app/src/plugin_host/profile/tests.rs @@ -0,0 +1,501 @@ +use super::*; +use crate::plugin_host::grants::{ + EffectiveGrant, GrantScope, PermissionDecision, PermissionRequest, +}; +use gamenode_platform::paths::DataPaths; +use tempfile::TempDir; + +fn profiles_with(account: Option<&str>, verified: bool) -> PluginProfiles { + let profiles = PluginProfiles::default(); + profiles.update(account, verified); + profiles +} + +#[test] +fn legacy_publisher_pin_layout_is_refused_without_replacing_current_trust() { + let temp = TempDir::new().unwrap(); + let paths = DataPaths::at(temp.path()); + let legacy = paths.private_dir().join("publisher-keys.json"); + let current = PluginStateLayout::managed(&paths) + .trust_dir() + .join("publisher-keys.json"); + std::fs::create_dir_all(legacy.parent().unwrap()).unwrap(); + std::fs::create_dir_all(current.parent().unwrap()).unwrap(); + let legacy_bytes = br#"{"schema":1,"publishers":{"org.example":{"fingerprint":"old"}}}"#; + let current_bytes = br#"{"schema":1,"publishers":{"org.example":{"fingerprint":"current"}}}"#; + std::fs::write(&legacy, legacy_bytes).unwrap(); + std::fs::write(¤t, current_bytes).unwrap(); + + let error = PluginStateLayout::refuse_legacy_layouts(&paths).unwrap_err(); + assert!(error.to_string().contains("left untouched")); + assert_eq!(std::fs::read(&legacy).unwrap(), legacy_bytes); + assert_eq!(std::fs::read(¤t).unwrap(), current_bytes); +} + +#[test] +fn legacy_grants_directory_is_refused_without_changing_legacy_or_current_state() { + let temp = TempDir::new().unwrap(); + let paths = DataPaths::at(temp.path()); + let legacy = paths.data_dir().join("plugin-state"); + let layout = PluginStateLayout::prepare_managed(&paths).unwrap(); + let profiles = profiles_with(Some("user"), true); + let profile = profiles.current().unwrap(); + let current = layout.account_dir(&profile).unwrap().join("grants.json"); + std::fs::create_dir_all(legacy.join("accounts/profile-1")).unwrap(); + std::fs::create_dir_all(current.parent().unwrap()).unwrap(); + let legacy_bytes = b"legacy grants are not imported"; + let current_bytes = b"current grants remain unchanged"; + std::fs::write(legacy.join("accounts/profile-1/grants.json"), legacy_bytes).unwrap(); + std::fs::write(¤t, current_bytes).unwrap(); + + let error = PluginStateLayout::refuse_legacy_layouts(&paths).unwrap_err(); + assert!(error.to_string().contains("left untouched")); + assert_eq!( + std::fs::read(legacy.join("accounts/profile-1/grants.json")).unwrap(), + legacy_bytes + ); + assert_eq!(std::fs::read(current).unwrap(), current_bytes); +} + +#[test] +fn prepare_managed_refuses_legacy_state_before_creating_current_layout() { + let temp = TempDir::new().unwrap(); + let paths = DataPaths::at(temp.path()); + let legacy = paths.data_dir().join("plugin-state"); + std::fs::create_dir_all(&legacy).unwrap(); + std::fs::write(legacy.join("sentinel"), b"keep").unwrap(); + + assert!(PluginStateLayout::prepare_managed(&paths).is_err()); + assert_eq!(std::fs::read(legacy.join("sentinel")).unwrap(), b"keep"); + assert!(!paths.plugin_data_dir().exists()); +} + +#[test] +fn current_plugin_layout_is_allowed_when_no_legacy_state_exists() { + let temp = TempDir::new().unwrap(); + let paths = DataPaths::at(temp.path()); + PluginStateLayout::refuse_legacy_layouts(&paths).unwrap(); + PluginStateLayout::prepare_managed(&paths).unwrap(); + assert!(paths.plugin_data_dir().join("state").is_dir()); +} + +#[test] +fn no_account_session_issues_no_profile_and_reports_unavailable() { + let profiles = PluginProfiles::default(); + assert_eq!(profiles.current(), None); + assert!(!profiles.may_start_third_party()); + let error = profiles.require().unwrap_err(); + assert_eq!(error.code(), tonic::Code::Unavailable); + let error = profiles + .resolver("org.example.plugin", "fingerprint", None) + .unwrap_err(); + assert_eq!(error.code(), tonic::Code::Unavailable); + + // An empty account id is not an account. + assert_eq!( + profiles.update(Some(" "), true), + ProfileTransition::Unchanged + ); + assert!(profiles.current().is_none()); +} + +#[test] +fn profile_id_is_derived_from_the_account_without_exposing_it() { + let profiles = profiles_with(Some("user-123"), true); + let profile = profiles.current().unwrap(); + assert_eq!(profile.profile_id(), profile_id_for_account("user-123")); + assert_ne!(profile.profile_id(), "user-123"); + assert!(!profile.profile_id().contains("user-123")); + assert_eq!(profile.profile_id().len(), 32); + assert!(profile.profile_id().chars().all(|c| c.is_ascii_hexdigit())); + assert_ne!( + profile_id_for_account("user-123"), + profile_id_for_account("user-124") + ); +} + +#[test] +fn unverified_restore_uses_the_cached_account_and_verification_keeps_its_contexts() { + let profiles = PluginProfiles::default(); + assert_eq!( + profiles.update(Some("cached"), false), + ProfileTransition::Fenced + ); + let restored = profiles.current().unwrap(); + assert!(!restored.verified()); + assert!(profiles.may_start_third_party()); + + // Verification of the same account is not a profile change. + assert_eq!( + profiles.update(Some("cached"), true), + ProfileTransition::Unchanged + ); + let verified = profiles.current().unwrap(); + assert!(verified.verified()); + assert_eq!(verified.profile_id(), restored.profile_id()); + assert_eq!(verified.epoch(), restored.epoch()); + assert!(profiles.is_current(restored.epoch())); +} + +#[test] +fn sign_out_rejection_and_a_different_verified_account_fence_previous_contexts() { + let profiles = profiles_with(Some("cached"), false); + let cached = profiles.current().unwrap(); + let resolver = profiles + .resolver("org.example.plugin", "fingerprint", Some("example")) + .unwrap(); + + // Verification found a different account. + assert_eq!( + profiles.update(Some("other"), true), + ProfileTransition::Fenced + ); + let other = profiles.current().unwrap(); + assert_ne!(other.profile_id(), cached.profile_id()); + assert!(!profiles.is_current(cached.epoch())); + assert!(!resolver.is_current_profile_epoch(profiles.epoch())); + + // Sign-out (or a rejected session) removes the profile and fences again. + assert_eq!(profiles.update(None, false), ProfileTransition::Fenced); + assert!(profiles.current().is_none()); + assert!(!profiles.is_current(other.epoch())); + assert!(!profiles.may_start_third_party()); + + // Signing back in with the first account restores its profile id under a fresh epoch, so a + // context from before sign-out still cannot act. + profiles.update(Some("cached"), true); + let again = profiles.current().unwrap(); + assert_eq!(again.profile_id(), cached.profile_id()); + assert!(again.epoch() > other.epoch()); + assert!(!profiles.is_current(cached.epoch())); +} + +#[test] +fn namespace_owners_differ_between_accounts_for_the_same_plugin() { + let profiles = profiles_with(Some("first"), true); + let first = profiles + .resolver("org.example.plugin", "fingerprint", Some("example")) + .unwrap(); + profiles.update(Some("second"), true); + let second = profiles + .resolver("org.example.plugin", "fingerprint", Some("example")) + .unwrap(); + assert_ne!(first.storage_owner(), second.storage_owner()); + assert_ne!( + first.secret_owner().unwrap(), + second.secret_owner().unwrap() + ); +} + +#[tokio::test] +async fn subscribers_observe_each_profile_change() { + let profiles = PluginProfiles::default(); + let mut changes = profiles.subscribe(); + profiles.update(Some("account"), false); + changes.changed().await.unwrap(); + assert!(changes.borrow_and_update().is_some()); + profiles.update(None, false); + changes.changed().await.unwrap(); + assert!(changes.borrow_and_update().is_none()); +} + +fn grant_request() -> PermissionRequest { + PermissionRequest { + permission_id: "storage.persist".into(), + required: false, + allowed_scopes: [GrantScope::OwnPrivateNamespace].into(), + } +} + +fn identity(profile: &ProfileContext) -> PluginIdentity { + PluginIdentity { + plugin_id: "org.example.plugin".into(), + publisher_fingerprint: "fingerprint".into(), + profile_id: profile.profile_id().into(), + } +} + +#[test] +fn active_profile_exposes_only_its_authenticated_identities_and_activation() { + let temp = tempfile::tempdir().unwrap(); + let layout = PluginStateLayout::new(temp.path().join("plugins")); + let profiles = profiles_with(Some("account"), true); + profiles.set_state_layout(layout.clone()); + let current = profiles.current().unwrap(); + let identity = identity(¤t); + layout + .open_grants(¤t) + .unwrap() + .replace_grants(identity.clone(), &[grant_request()], &[]) + .unwrap(); + + assert_eq!( + profiles.identities().unwrap(), + std::slice::from_ref(&identity) + ); + assert!(!profiles.is_enabled(&identity.plugin_id).unwrap()); + layout + .open_activation(¤t) + .unwrap() + .set_enabled(&identity.plugin_id, true) + .unwrap(); + assert!(profiles.is_enabled(&identity.plugin_id).unwrap()); + + profiles.update(Some("another-account"), true); + assert!(profiles.identities().unwrap().is_empty()); + assert!(!profiles.is_enabled(&identity.plugin_id).unwrap()); +} + +#[test] +fn another_account_sees_packages_but_not_grants_or_activation() { + let temp = tempfile::tempdir().unwrap(); + let layout = PluginStateLayout::new(temp.path().join("plugins")); + let profiles = profiles_with(Some("first"), true); + let first = profiles.current().unwrap(); + + // OS-user state does not depend on the account. + let packages = layout.packages_dir(); + let trust = layout.trust_dir(); + + let mut grants = layout.open_grants(&first).unwrap(); + grants + .replace_grants( + identity(&first), + &[grant_request()], + &[PermissionDecision { + permission_id: "storage.persist".into(), + scope: GrantScope::OwnPrivateNamespace, + granted: true, + }], + ) + .unwrap(); + let mut activation = layout.open_activation(&first).unwrap(); + activation.set_enabled("org.example.plugin", true).unwrap(); + + profiles.update(Some("second"), true); + let second = profiles.current().unwrap(); + assert_eq!(layout.packages_dir(), packages); + assert_eq!(layout.trust_dir(), trust); + assert_ne!( + layout.account_dir(&first).unwrap(), + layout.account_dir(&second).unwrap() + ); + + let grants = layout.open_grants(&second).unwrap(); + assert!( + grants + .effective_grants(&identity(&second)) + .iter() + .all(|grant| grant.state != crate::plugin_host::grants::PermissionState::Granted) + ); + assert_eq!(grants.revision(&identity(&first)), 0); + let activation = layout.open_activation(&second).unwrap(); + assert!(!activation.is_enabled("org.example.plugin")); + assert_eq!(activation.enabled().count(), 0); + + // The first account keeps its state for its next sign-in. + profiles.update(None, false); + profiles.update(Some("first"), true); + let first_again = profiles.current().unwrap(); + let grants = layout.open_grants(&first_again).unwrap(); + let effective: Vec = grants.effective_grants(&identity(&first_again)); + assert!(effective.iter().any(|grant| { + grant.permission_id == "storage.persist" + && grant.state == crate::plugin_host::grants::PermissionState::Granted + })); + assert!( + layout + .open_activation(&first_again) + .unwrap() + .is_enabled("org.example.plugin") + ); +} + +#[test] +fn removing_plugin_clears_every_accounts_grants_and_activation_but_keeps_private_data() { + let temp = tempfile::tempdir().unwrap(); + let layout = PluginStateLayout::new(temp.path().join("plugins")); + let profiles = profiles_with(Some("first"), true); + let first = profiles.current().unwrap(); + let plugin_id = "org.example.plugin"; + + let mut grants = layout.open_grants(&first).unwrap(); + grants + .replace_grants( + identity(&first), + &[grant_request()], + &[PermissionDecision { + permission_id: "storage.persist".into(), + scope: GrantScope::OwnPrivateNamespace, + granted: true, + }], + ) + .unwrap(); + layout + .open_activation(&first) + .unwrap() + .set_enabled(plugin_id, true) + .unwrap(); + let private_data = layout + .account_dir(&first) + .unwrap() + .join("plugin-data") + .join(plugin_id); + std::fs::create_dir_all(&private_data).unwrap(); + std::fs::write(private_data.join("keep.json"), "user data").unwrap(); + + profiles.update(Some("second"), true); + let second = profiles.current().unwrap(); + let mut grants = layout.open_grants(&second).unwrap(); + grants + .replace_grants( + identity(&second), + &[grant_request()], + &[PermissionDecision { + permission_id: "storage.persist".into(), + scope: GrantScope::OwnPrivateNamespace, + granted: true, + }], + ) + .unwrap(); + layout + .open_activation(&second) + .unwrap() + .set_enabled(plugin_id, true) + .unwrap(); + + layout.remove_plugin_account_state(plugin_id).unwrap(); + + for profile in [&first, &second] { + assert!( + !layout + .open_activation(profile) + .unwrap() + .is_enabled(plugin_id) + ); + assert!( + layout + .open_grants(profile) + .unwrap() + .effective_grants(&identity(profile)) + .is_empty() + ); + } + assert_eq!( + std::fs::read_to_string(private_data.join("keep.json")).unwrap(), + "user data" + ); +} + +#[cfg(unix)] +#[test] +fn account_state_is_private_to_the_os_user() { + use std::os::unix::fs::PermissionsExt; + let temp = tempfile::tempdir().unwrap(); + let layout = PluginStateLayout::new(temp.path().join("plugins")); + let profile = profiles_with(Some("account"), true).current().unwrap(); + let mut activation = layout.open_activation(&profile).unwrap(); + activation.set_enabled("org.example.plugin", true).unwrap(); + let dir = layout.account_dir(&profile).unwrap(); + assert_eq!( + std::fs::metadata(&dir).unwrap().permissions().mode() & 0o777, + 0o700 + ); + assert_eq!( + std::fs::metadata(dir.join(ACTIVATION_FILE)) + .unwrap() + .permissions() + .mode() + & 0o777, + 0o600 + ); +} + +#[test] +fn playtime_accounting_preference_is_persistent_and_profile_scoped() { + let temp = tempfile::tempdir().unwrap(); + let layout = PluginStateLayout::new(temp.path().join("plugins")); + let profiles = PluginProfiles::default(); + profiles.set_state_layout(layout.clone()); + profiles.update(Some("first-account"), true); + + let first_profile = profiles.current().unwrap(); + layout + .open_activation(&first_profile) + .unwrap() + .set_enabled("org.example.reader", true) + .unwrap(); + + let first_profile = profiles.current().unwrap(); + let mut activation = layout.open_activation(&first_profile).unwrap(); + activation.set_enabled("org.example.reader", true).unwrap(); + + assert!( + profiles + .is_playtime_accounting_enabled("org.example.reader") + .unwrap() + ); + profiles + .set_playtime_accounting_enabled("org.example.reader", false) + .unwrap(); + assert!( + !profiles + .is_playtime_accounting_enabled("org.example.reader") + .unwrap() + ); + assert!( + layout + .open_activation(&first_profile) + .unwrap() + .is_enabled("org.example.reader") + ); + + let restarted = PluginProfiles::default(); + restarted.set_state_layout(layout.clone()); + restarted.update(Some("first-account"), true); + assert!( + !restarted + .is_playtime_accounting_enabled("org.example.reader") + .unwrap() + ); + assert!( + layout + .open_activation(&first_profile) + .unwrap() + .is_enabled("org.example.reader") + ); + + let restarted = PluginProfiles::default(); + restarted.set_state_layout(layout.clone()); + restarted.update(Some("first-account"), true); + assert!( + !restarted + .is_playtime_accounting_enabled("org.example.reader") + .unwrap() + ); + + profiles.update(Some("second-account"), true); + assert!( + profiles + .is_playtime_accounting_enabled("org.example.reader") + .unwrap() + ); + profiles.update(Some("first-account"), true); + assert!( + !profiles + .is_playtime_accounting_enabled("org.example.reader") + .unwrap() + ); +} + +#[test] +fn invalid_plugin_ids_do_not_change_activation() { + let temp = tempfile::tempdir().unwrap(); + let layout = PluginStateLayout::new(temp.path().join("plugins")); + let profile = profiles_with(Some("account"), true).current().unwrap(); + let mut activation = layout.open_activation(&profile).unwrap(); + for invalid in ["", " ", "bad\nid"] { + assert!(activation.set_enabled(invalid, true).is_err()); + } + assert_eq!(activation.enabled().count(), 0); +} diff --git a/crates/app/src/plugin_host/provider.rs b/crates/app/src/plugin_host/provider.rs index c63121866..da72fd15f 100644 --- a/crates/app/src/plugin_host/provider.rs +++ b/crates/app/src/plugin_host/provider.rs @@ -2,19 +2,99 @@ //! every provider message is validated before those services can be called. use std::collections::{BTreeSet, HashMap, VecDeque}; -use std::sync::{Arc, Mutex}; -use std::time::Duration; +use std::sync::{Arc, Mutex, Weak}; +use std::time::{Duration, Instant}; use gamenode_plugin_protocol::{ capability as cap, catalog::CatalogTransfer, models, proto::*, settings, }; -use tokio::sync::{mpsc, oneshot}; +use tokio::sync::{OwnedMutexGuard, mpsc, oneshot}; use tokio_stream::wrappers::ReceiverStream; use tonic::{Request, Response, Status}; +use super::namespace::ExternalNamespaceResolver; +use super::package::PlaytimeCapabilities; +use super::profile::PluginProfiles; +use super::runtime::RuntimeSessionHandler; +use super::shared_data::DataBroker; +use super::shared_pool::DurableSharedPool; + const MAX_OPERATIONS: usize = 32; const COMMAND_QUEUE: usize = 32; const HISTORY: usize = 128; +const AUTHORIZATION_AUDIT_LIMIT: usize = 256; + +/// Redacted host-side record of a denied authorization check. It deliberately +/// excludes session credentials, operation ids, and request payloads. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct AuthorizationAuditEvent { + pub plugin_id: String, + pub provider_id: String, + pub permission_id: String, + pub reason: DenialReason, + pub grant_revision: u64, +} + +fn denial_event( + session: &Session, + permission: &str, + reason: DenialReason, +) -> AuthorizationAuditEvent { + AuthorizationAuditEvent { + plugin_id: session.provider.registration.plugin_id.clone(), + provider_id: session.provider.registration.provider_id.clone(), + permission_id: permission.to_owned(), + reason, + grant_revision: session.grant_revision, + } +} + +fn denial(reason: DenialReason, permission: &str, revision: u64) -> Status { + use gamenode_plugin_protocol::prost::Message; + let details = DenialDetail { + reason: reason as i32, + permission_id: permission.to_owned(), + grant_revision: revision, + } + .encode_to_vec(); + Status::with_details( + tonic::Code::PermissionDenied, + "plugin permission denied", + details.into(), + ) +} + +fn permission_change(session: &Session, revoked: bool) -> PermissionChange { + let revision = session.grant_revision; + let mut grants = session + .grants + .iter() + .map(|permission_id| PermissionGrant { + permission_id: permission_id.clone(), + state: "granted".into(), + scope: "provider".into(), + reason: String::new(), + revision, + }) + .collect::>(); + for permission_id in cap::KNOWN { + if !session.grants.contains(*permission_id) { + grants.push(PermissionGrant { + permission_id: (*permission_id).into(), + state: "denied".into(), + scope: "provider".into(), + reason: "not_granted".into(), + revision, + }); + } + } + grants.sort_by(|a, b| a.permission_id.cmp(&b.permission_id)); + PermissionChange { + revision, + grants, + revoked, + } +} /// Implementations provide only safe diagnostics. Blocking work belongs on /// workers and mutations must check the supplied operation lease at commit. @@ -42,17 +122,116 @@ pub trait HostServices: Send + Sync { } } +/// Extension registrations have no provider-owned services. +pub(crate) struct ExtensionServices; + +#[tonic::async_trait] +impl HostServices for ExtensionServices { + async fn context(&self, _: Lease) -> Result { + Err(Status::permission_denied( + "extensions have no provider context", + )) + } + async fn account(&self, _: Lease, _: account_request::Action) -> Result { + Err(Status::permission_denied( + "extensions have no provider account", + )) + } + async fn secret(&self, _: Lease, _: SecretRequest) -> Result { + Err(Status::permission_denied( + "extensions have no provider secrets", + )) + } + async fn login(&self, _: Lease, _: LoginRequest) -> Result { + Err(Status::permission_denied( + "extensions have no provider login", + )) + } + async fn actions(&self, _: Lease, _: ActionDeclaration) -> Result { + Err(Status::permission_denied( + "extensions have no provider actions", + )) + } +} + +/// Who composed a registration. Official providers are bundled with GameNode; third-party +/// providers come from managed packages and are bound to the active GameNode account profile. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum RegistrationOrigin { + Official, + ThirdParty { publisher_fingerprint: String }, +} + +/// A provider owns a library namespace; an extension is launched for a host-selected game and +/// must never claim the target game's provider identity. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum RegistrationKind { + Provider, + Extension, +} + pub struct Registration { + /// Provider id for provider registrations or a host-generated internal key for extensions. pub provider_id: String, pub plugin_id: String, + /// Display name from the verified descriptor/manifest, retained for provenance. + pub declared_developer: String, + /// Digest of the exact verified package contents. Empty for bundled official providers. + pub package_digest: Vec, + pub kind: RegistrationKind, + pub origin: RegistrationOrigin, pub capabilities: Vec, /// Whether this provider's trusted manifest declares shared catalog access. pub shared_catalog: bool, + /// Policy copied from the signed third-party package manifest. Official providers use the + /// disabled default and cannot report plugin-owned runtime sessions. + pub playtime: PlaytimeCapabilities, pub services: Arc, } +impl PlaytimeCapabilities { + fn can_report_runtime_sessions(self) -> bool { + self.identifies_gameplay + && (self.identifies_pauses + || self.without_pause_detection + == super::package::PlaytimeAccountingMode::ApplicationOpen) + } + + fn can_report_transition(self, transition: i32) -> bool { + if !self.can_report_runtime_sessions() { + return false; + } + if matches!( + RuntimeSessionTransition::try_from(transition), + Ok(RuntimeSessionTransition::Paused | RuntimeSessionTransition::Resumed) + ) { + return self.identifies_pauses; + } + true + } +} + +/// Internal lookup key for one provider-free extension. It is not a provider id and is never +/// placed into the extension's authenticated `ServiceContext`. +pub(crate) fn extension_registration_id(plugin_id: &str) -> String { + format!("extension:{plugin_id}") +} + +fn context_provider_id(registration: &Registration) -> &str { + match registration.kind { + RegistrationKind::Provider => ®istration.provider_id, + RegistrationKind::Extension => "", + } +} + struct Provider { registration: Registration, + extension_schemas: + std::sync::RwLock>, + declared_capabilities: std::sync::RwLock>, + capabilities: std::sync::RwLock>, + /// Set for third-party providers: their profile epoch is the account profile's epoch. + profiles: Option>, account_epoch: std::sync::atomic::AtomicU64, profile_epoch: std::sync::atomic::AtomicU64, identity_revision: std::sync::atomic::AtomicU64, @@ -62,16 +241,120 @@ struct Provider { struct Pending { provider: Arc, credential: [u8; 32], + profile_epoch: Option, + session_kind: i32, + target_game: Option, ready: oneshot::Sender<()>, + closed: oneshot::Sender<()>, + extension: Option, +} + +pub(crate) struct SupervisedExtension { + pub target: super::process::ExtensionTarget, + pub required_permission: Option<&'static str>, + pub expected_version: Option, + pub intent: Option, + pub playtime: Option, } struct Session { provider: Arc, + package_version: String, credential: [u8; 32], grants: BTreeSet, + kind: i32, + target_game: Option, + grant_revision: u64, + permission_watchers: Vec>>, commands: Option>>, ready: Option>, + _closed: oneshot::Sender<()>, + extension: Option, + revoked: bool, completed: VecDeque, + /// The operation id of the session's resource context (API 1.6+); `None` for sessions that + /// negotiated an earlier minor, which cannot call resource services. + resource_operation: Option, + resource_context: Option, + runtime_contexts: HashMap, + runtime_instances: HashMap, +} + +#[derive(Clone)] +struct RuntimeInstanceEvidence { + last_received_at: Instant, + runtime_id: String, + active: bool, +} + +#[derive(Clone)] +struct RuntimeContextGrant { + game_id: String, + installation_id: String, + runtime_id: String, + runtime_instance_id: String, + content_id: String, + profile_epoch: u64, + grant_revision: u64, + library_revision: u64, + binding_revision: u64, + expires_at: Instant, +} + +fn runtime_instance_has_fresh_active_report( + evidence: Option<&RuntimeInstanceEvidence>, + runtime_id: &str, + now: Instant, +) -> bool { + evidence.is_some_and(|evidence| { + evidence.active + && evidence.runtime_id == runtime_id + && now.saturating_duration_since(evidence.last_received_at) <= Duration::from_secs(30) + }) +} + +impl Session { + fn extension_authority(&self) -> bool { + !self.revoked + && self.extension.as_ref().is_none_or(|extension| { + // Readiness uses an Extension handshake without a host-issued action intent. + extension.intent.is_some() + && self.commands.is_some() + && extension.target.is_current() + && self + .provider + .profiles + .as_ref() + .and_then(|profiles| profiles.current()) + .is_some_and(|profile| { + profile.verified() && profile.epoch() == extension.target.profile_epoch + }) + }) + } +} + +/// An authorized plugin-initiated resource call. It snapshots the session's scope at check time; +/// long-lived streams check again before each delivery. +#[derive(Clone, Debug)] +pub(crate) struct ResourceCaller { + pub session_id: String, + pub provider_id: String, + pub declared_developer: String, + pub origin: String, + pub package_digest: Vec, + pub package_version: String, + pub grants: BTreeSet, + pub grant_revision: u64, + pub profile_epoch: u64, + /// Host-owned private-resource namespace of an authenticated third-party plugin in the + /// active profile; `None` for official providers, which use trusted host adapters. + pub namespace: Option, +} + +impl ResourceCaller { + pub fn has(&self, permission: &str) -> bool { + self.grants.contains(permission) + } } struct Operation { @@ -86,6 +369,22 @@ struct Operation { secret_deleted: bool, identity_accepted: bool, settings: Option, + configuration: Option, + configuration_cleanup: bool, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +struct ConfigurationBinding { + profile_id: String, + session_id: String, + window_id: String, +} + +#[derive(Clone, Debug)] +struct ConfigurationWindow { + profile_epoch: u64, + session_id: String, + window_id: String, } #[derive(Default)] @@ -94,16 +393,34 @@ struct State { pending: Vec, sessions: HashMap, operations: HashMap<(String, String), Operation>, + authorization_audit: VecDeque, } #[derive(Clone, Default)] pub struct ProviderApi { state: Arc>, + profiles: Arc, + configuration_windows: Arc>>, + runtime_session_handler: Arc>>>, + shared_data_broker: Arc>>>, + /// The host-owned durable public pool; disabled unless the application supplies its folder. + shared_pool: Arc>>, +} + +/// Declared configuration surfaces and the active session's explicit grants. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ConfigurationModes { + pub external_declared: bool, + pub external_authorized: bool, + pub declarative_declared: bool, + pub declarative_authorized: bool, } pub struct Launch { pub credential: String, pub ready: oneshot::Receiver<()>, + pub(crate) closed: oneshot::Receiver<()>, } #[derive(Debug)] @@ -226,6 +543,45 @@ impl Lease { self.api.authorize(&self.context, permission).map(|_| ()) } + /// Host-owned namespace of the authenticated third-party plugin in its active account + /// profile. Ownership comes from the registration and profile, never from the request. + pub fn namespace(&self) -> Result { + let provider = self.api.authorize(&self.context, self.permission)?; + let RegistrationOrigin::ThirdParty { + publisher_fingerprint, + } = &provider.registration.origin + else { + return Err(Status::failed_precondition( + "official providers use trusted host adapters", + )); + }; + let profiles = provider + .profiles + .as_ref() + .ok_or_else(super::profile::no_profile)?; + let resolver = profiles.resolver( + &provider.registration.plugin_id, + publisher_fingerprint, + Some(&provider.registration.provider_id), + )?; + if !resolver.is_current_profile_epoch(self.context.profile_epoch) { + return Err(Status::failed_precondition("provider operation is stale")); + } + Ok(resolver) + } + + /// Reject a host-side scope mismatch with the same machine-readable denial + /// contract used for missing grants. + pub fn deny_scope(&self) -> Status { + self.deny_scope_for(self.permission) + } + + pub fn deny_scope_for(&self, permission: &'static str) -> Status { + self.api + .scope_denial(&self.context, permission) + .unwrap_or_else(|| Status::unauthenticated("provider session expired")) + } + /// Called by trusted service adapters inside `storage`, while the provider /// commit guard is held. Failed OS writes never establish a commit point. pub fn record_secret(&self, operation: SecretOperation, accepted: bool) -> Result<(), Status> { @@ -323,6 +679,9 @@ fn operation_timeout(kind: ProviderOperation) -> Duration { ProviderOperation::ReadAchievements => Duration::from_secs(300), ProviderOperation::Initialize | ProviderOperation::Check => Duration::from_secs(105), ProviderOperation::SettingsCancel => Duration::from_secs(3), + ProviderOperation::ConfigurationOpen + | ProviderOperation::ConfigurationFocus + | ProviderOperation::ConfigurationClose => Duration::from_secs(5), _ => Duration::from_secs(90), } } @@ -337,7 +696,10 @@ fn epoch(provider: &Provider) -> (u64, u64) { use std::sync::atomic::Ordering; ( provider.account_epoch.load(Ordering::Acquire), - provider.profile_epoch.load(Ordering::Acquire), + match &provider.profiles { + Some(profiles) => profiles.epoch(), + None => provider.profile_epoch.load(Ordering::Acquire), + }, ) } @@ -350,8 +712,18 @@ fn is_settings(kind: ProviderOperation) -> bool { ) } +fn is_configuration(kind: ProviderOperation) -> bool { + matches!( + kind, + ProviderOperation::ConfigurationOpen + | ProviderOperation::ConfigurationFocus + | ProviderOperation::ConfigurationClose + ) +} + fn account_scoped(kind: ProviderOperation) -> bool { !is_settings(kind) + && !is_configuration(kind) && !matches!( kind, ProviderOperation::Discover | ProviderOperation::ReadCounter @@ -370,6 +742,7 @@ fn permission_set(kind: ProviderOperation) -> BTreeSet<&'static str> { ], Discover => &[cap::CONTEXT, cap::DISCOVERY], SettingsDescribeRead | SettingsSubmit | SettingsCancel => &[cap::SETTINGS], + ConfigurationOpen | ConfigurationFocus | ConfigurationClose => &[cap::CONFIGURE], SignIn => &[ cap::CONTEXT, cap::ACCOUNT_READ, @@ -423,193 +796,1289 @@ fn permission_set(kind: ProviderOperation) -> BTreeSet<&'static str> { } impl ProviderApi { - pub fn registered(&self, provider_id: &str) -> bool { - lock(&self.state).providers.contains_key(provider_id) + pub(crate) fn set_shared_data_broker(&self, broker: &Arc) { + *lock(&self.shared_data_broker) = Some(Arc::downgrade(broker)); } - pub fn request_shutdown(&self, provider_id: &str) { - let state = lock(&self.state); - for (id, session) in &state.sessions { - if session.provider.registration.provider_id != provider_id { - continue; - } - if let Some(commands) = &session.commands { - let (account_epoch, profile_epoch) = epoch(&session.provider); - if let Ok(operation_id) = super::random_session_id() { - let _ = commands.try_send(Ok(ProviderCommand { - context: Some(ServiceContext { - session_id: id.clone(), - session_credential: session.credential.to_vec(), - provider_id: provider_id.into(), - operation_id, - account_epoch, - profile_epoch, - }), - operation: ProviderOperation::Shutdown as i32, - target_operation_id: String::new(), - settings: None, - achievements: None, - })); - } - } - } + /// Shares the application's durable public pool with lifecycle code that resolves owners + /// outside a plugin session (uninstall retention and its reviewed reuse). + pub fn set_shared_pool(&self, pool: Arc) { + *lock(&self.shared_pool) = pool; } - /// Registration is host-owned composition, never a plugin RPC. - pub fn register(&self, registration: Registration) -> Result<(), Status> { - if registration.provider_id.is_empty() - || registration.provider_id.len() > 128 - || registration.plugin_id.is_empty() - || registration.plugin_id.len() > 256 - { - return Err(Status::invalid_argument("invalid provider registration")); - } - cap::negotiate( - gamenode_plugin_protocol::API_MAJOR, - gamenode_plugin_protocol::API_MINOR, - ®istration.capabilities, - &[cap::ALL, &[cap::SETTINGS]].concat(), - ) - .map_err(|_| Status::invalid_argument("invalid provider grants"))?; - if !registration - .capabilities - .iter() - .any(|s| s == cap::CONTEXT || s == cap::SETTINGS) - { - return Err(Status::invalid_argument( - "full provider requires context access", - )); - } - let mut state = lock(&self.state); - if state.providers.contains_key(®istration.provider_id) - || state - .providers - .values() - .any(|p| p.registration.plugin_id == registration.plugin_id) - { - return Err(Status::already_exists("provider is already registered")); - } - state.providers.insert( - registration.provider_id.clone(), - Arc::new(Provider { - registration, - account_epoch: 1.into(), - profile_epoch: 1.into(), - identity_revision: 1.into(), - commits: Arc::new(tokio::sync::Mutex::new(())), - }), - ); - Ok(()) + pub(crate) fn shared_pool(&self) -> Arc { + lock(&self.shared_pool).clone() } - pub fn begin_launch(&self, provider_id: &str) -> Result { - let mut state = lock(&self.state); - let provider = state - .providers - .get(provider_id) - .cloned() - .ok_or_else(|| Status::not_found("provider is unavailable"))?; - if state.pending.len() + state.sessions.len() >= 16 { - return Err(Status::resource_exhausted("provider session capacity")); - } - if state - .pending - .iter() - .any(|p| p.provider.registration.provider_id == provider_id) - || state - .sessions - .values() - .any(|s| s.provider.registration.provider_id == provider_id) - { - return Err(Status::already_exists( - "provider already has a process session", + pub fn set_runtime_session_handler(&self, handler: Arc) { + *lock(&self.runtime_session_handler) = Some(handler); + } + + async fn runtime_session_context_event( + &self, + context: ServiceContext, + request: RuntimeSessionContextRequest, + ) -> Result<(), Status> { + if request.correlation_id.is_empty() || request.correlation_id.len() > 128 { + return Err(Status::invalid_argument( + "invalid runtime context correlation id", )); } - let mut credential = [0; 32]; - getrandom::fill(&mut credential) - .map_err(|_| Status::internal("could not create launch credential"))?; - let (ready, receiver) = oneshot::channel(); - state.pending.push(Pending { - provider, - credential, - ready, - }); - Ok(Launch { - credential: super::hex(&credential), - ready: receiver, - }) - } + let (provider, commands, grant_revision, owner_key, publisher_fingerprint) = { + let state = lock(&self.state); + let session = state + .sessions + .get(&context.session_id) + .ok_or_else(|| Status::unauthenticated("provider session expired"))?; + if !super::constant_time_eq(&session.credential, &context.session_credential) + || session.resource_context.as_ref() != Some(&context) + || session.kind != SessionKind::Extension as i32 + || session.provider.registration.kind != RegistrationKind::Extension + || !session.extension_authority() + { + return Err(Status::permission_denied( + "runtime context requires an active extension session", + )); + } + if !session.grants.contains(cap::GAME_SESSIONS_REPORT) { + return Err(Status::permission_denied( + "runtime reporting is not granted", + )); + } + let current = epoch(&session.provider); + if current.1 != context.profile_epoch || current.0 != context.account_epoch { + return Err(Status::failed_precondition( + "runtime context session is stale", + )); + } + let RegistrationOrigin::ThirdParty { + publisher_fingerprint, + } = &session.provider.registration.origin + else { + return Err(Status::permission_denied( + "runtime context requires an authenticated plugin", + )); + }; + if request.runtime_instance_id.is_empty() + || request.runtime_id.is_empty() + || request.content_id.is_empty() + || request.game_id.is_empty() + || request.installation_id.is_empty() + { + return Err(Status::invalid_argument("runtime context is incomplete")); + } + let active_runtime = runtime_instance_has_fresh_active_report( + session.runtime_instances.get(&request.runtime_instance_id), + &request.runtime_id, + Instant::now(), + ); + if !active_runtime { + return Err(Status::failed_precondition( + "runtime context requires a fresh active instance report", + )); + } + let playtime = session + .extension + .as_ref() + .and_then(|extension| extension.playtime) + .unwrap_or(session.provider.registration.playtime); + if !playtime.can_report_runtime_sessions() { + return Err(Status::permission_denied( + "runtime reporting is disabled by package policy", + )); + } + let profiles = session + .provider + .profiles + .as_ref() + .ok_or_else(super::profile::no_profile)?; + let resolver = profiles + .resolver( + &session.provider.registration.plugin_id, + publisher_fingerprint, + None, + ) + .map_err(|_| Status::unavailable("plugin scope is unavailable"))?; + ( + session.provider.clone(), + session.commands.clone().ok_or_else(|| { + Status::failed_precondition("provider stream is not connected") + })?, + session.grant_revision, + resolver.library_recipe_owner_key(), + publisher_fingerprint.clone(), + ) + }; - pub fn owns_launch(&self, credential: &[u8]) -> bool { - lock(&self.state) - .pending - .iter() - .any(|p| super::constant_time_eq(&p.credential, credential)) + // This call validates the current library and content binding before asking the user. + let handler = { lock(&self.runtime_session_handler).clone() }; + let authorization = if let Some(handler) = handler { + handler + .authorize_context( + provider.registration.plugin_id.clone(), + publisher_fingerprint, + owner_key, + context.profile_epoch, + request.clone(), + ) + .await + } else { + Err(Status::unavailable( + "runtime context authorization is unavailable", + )) + }; + + let (outcome, token, reason) = match authorization { + Ok(revisions) => { + let token = super::random_session_id()?; + let mut state = lock(&self.state); + let Some(session) = state.sessions.get_mut(&context.session_id) else { + return Err(Status::unauthenticated("provider session expired")); + }; + let current = epoch(&session.provider); + let runtime_still_active = runtime_instance_has_fresh_active_report( + session.runtime_instances.get(&request.runtime_instance_id), + &request.runtime_id, + Instant::now(), + ); + if !runtime_still_active { + ( + RuntimeSessionOutcome::RejectedStale, + String::new(), + "runtime evidence expired or ended during confirmation".to_owned(), + ) + } else if !super::constant_time_eq(&session.credential, &context.session_credential) + || session.resource_context.as_ref() != Some(&context) + || epoch(&session.provider) != (context.account_epoch, context.profile_epoch) + || current.1 != context.profile_epoch + || current.0 != context.account_epoch + || session.grant_revision != grant_revision + || !session.grants.contains(cap::GAME_SESSIONS_REPORT) + || !session.extension_authority() + { + ( + RuntimeSessionOutcome::RejectedUnauthorized, + String::new(), + "session or grant changed during approval".to_owned(), + ) + } else { + session + .runtime_contexts + .retain(|_, grant| grant.expires_at > Instant::now()); + if session.runtime_contexts.len() >= 64 { + return Err(Status::resource_exhausted( + "too many runtime context approvals", + )); + } + session.runtime_contexts.insert( + token.clone(), + RuntimeContextGrant { + game_id: request.game_id.clone(), + installation_id: request.installation_id.clone(), + runtime_id: request.runtime_id.clone(), + runtime_instance_id: request.runtime_instance_id.clone(), + content_id: request.content_id.clone(), + profile_epoch: context.profile_epoch, + grant_revision, + library_revision: revisions.library_revision, + binding_revision: revisions.binding_revision, + expires_at: Instant::now() + Duration::from_secs(30), + }, + ); + (RuntimeSessionOutcome::Accepted, token, String::new()) + } + } + Err(status) => ( + if status.code() == tonic::Code::PermissionDenied { + RuntimeSessionOutcome::RejectedUnauthorized + } else { + RuntimeSessionOutcome::RejectedUnavailable + }, + String::new(), + status.message().to_owned(), + ), + }; + commands + .send(Ok(ProviderCommand { + context: Some(context), + operation: ProviderOperation::RuntimeSessionContextResult as i32, + target_operation_id: request.correlation_id.clone(), + settings: None, + achievements: None, + runtime_session_result: None, + runtime_session_context_result: Some(RuntimeSessionContextResult { + correlation_id: request.correlation_id, + outcome: outcome as i32, + runtime_context_id: token, + reason, + denial: None, + }), + })) + .await + .map_err(|_| Status::unavailable("provider command stream closed")) } - pub fn open_session(&self, hello: &OpenSessionRequest) -> Result { - let mut state = lock(&self.state); - let index = state - .pending - .iter() - .position(|p| super::constant_time_eq(&p.credential, &hello.session_credential)) - .ok_or_else(|| Status::unauthenticated("unknown provider launch"))?; - let pending = &state.pending[index]; - if pending.provider.registration.plugin_id != hello.plugin_id - || hello.plugin_version.is_empty() - || hello.plugin_version.len() > 128 - { - return Err(Status::permission_denied("wrong provider identity")); - } - let allowed: Vec<&str> = pending - .provider - .registration + async fn runtime_session_event( + &self, + context: ServiceContext, + report: RuntimeSessionReport, + ) -> Result<(), Status> { + let received_at = Instant::now(); + let (provider, commands, grant_revision, target_game, owner_key) = { + let state = lock(&self.state); + let session = state + .sessions + .get(&context.session_id) + .ok_or_else(|| Status::unauthenticated("provider session expired"))?; + if !super::constant_time_eq(&session.credential, &context.session_credential) { + return Err(Status::unauthenticated( + "provider session credential is invalid", + )); + } + if !session.extension_authority() { + return Err(Status::permission_denied( + "extension session has no active target authority", + )); + } + if session.resource_context.as_ref() != Some(&context) + || session.kind != SessionKind::Extension as i32 + || session.provider.registration.kind != RegistrationKind::Extension + { + return Err(Status::permission_denied( + "runtime reports require a scoped extension session", + )); + } + let current = epoch(&session.provider); + if current.1 != context.profile_epoch || current.0 != context.account_epoch { + return Err(Status::failed_precondition( + "runtime report session is stale", + )); + } + let RegistrationOrigin::ThirdParty { + publisher_fingerprint, + } = &session.provider.registration.origin + else { + return Err(Status::permission_denied( + "runtime reports require an authenticated plugin", + )); + }; + let playtime = session + .extension + .as_ref() + .and_then(|extension| extension.playtime) + .unwrap_or(session.provider.registration.playtime); + if !playtime.can_report_transition(report.transition) { + return Err(Status::permission_denied( + "runtime reporting is disabled by the signed package policy", + )); + } + let profiles = session + .provider + .profiles + .as_ref() + .ok_or_else(super::profile::no_profile)?; + let resolver = profiles + .resolver( + &session.provider.registration.plugin_id, + publisher_fingerprint, + None, + ) + .map_err(|_| Status::unavailable("plugin scope is unavailable"))?; + ( + session.provider.clone(), + session.commands.clone().ok_or_else(|| { + Status::failed_precondition("provider stream is not connected") + })?, + session.grant_revision, + session.target_game.clone(), + resolver.library_recipe_owner_key(), + ) + }; + + let _commit = provider.commits.lock().await; + let ( + has_grant, + scope_matches, + revision_unchanged, + denial_audit, + context_authorized, + context_revision, + ) = { + let state = lock(&self.state); + let Some(session) = state.sessions.get(&context.session_id) else { + return Err(Status::unauthenticated("provider session expired")); + }; + if !super::constant_time_eq(&session.credential, &context.session_credential) + || session.resource_context.as_ref() != Some(&context) + || epoch(&session.provider) != (context.account_epoch, context.profile_epoch) + { + return Err(Status::unauthenticated( + "provider session context is invalid", + )); + } + if !session.extension_authority() { + return Err(Status::permission_denied( + "extension session has no active target authority", + )); + } + let has_grant = session.grants.contains(cap::GAME_SESSIONS_REPORT); + let initial_scope = report.runtime_context_id.is_empty() + && target_game.as_ref().is_some_and(|target| { + target.game_id == report.game_id + && target.installation_id == report.installation_id + }); + let now = Instant::now(); + let issued_context = (!report.runtime_context_id.is_empty()) + .then(|| session.runtime_contexts.get(&report.runtime_context_id)) + .flatten() + .filter(|grant| { + grant.expires_at > now + && grant.profile_epoch == context.profile_epoch + && grant.grant_revision == session.grant_revision + && grant.game_id == report.game_id + && grant.installation_id == report.installation_id + && grant.runtime_id == report.runtime_id + && grant.runtime_instance_id == report.runtime_instance_id + && grant.content_id == report.content_id + }); + let context_authorized = issued_context.is_some(); + let context_revision = + issued_context.map(|grant| super::runtime::RuntimeContextRevision { + library_revision: grant.library_revision, + binding_revision: grant.binding_revision, + }); + let scope_matches = (initial_scope || context_authorized) + && report.reporter_session_id == context.session_id; + let reason = if !has_grant { + DenialReason::NotGranted + } else if !scope_matches { + DenialReason::ScopeDenied + } else { + DenialReason::Revoked + }; + ( + has_grant, + scope_matches, + session.grant_revision == grant_revision, + (!has_grant || !scope_matches || session.grant_revision != grant_revision) + .then(|| denial_event(session, cap::GAME_SESSIONS_REPORT, reason)), + context_authorized, + context_revision, + ) + }; + let authorized = has_grant && scope_matches && revision_unchanged; + let mut result = if !authorized { + let reason = if !has_grant { + DenialReason::NotGranted + } else if !scope_matches { + DenialReason::ScopeDenied + } else { + DenialReason::Revoked + }; + if let Some(event) = denial_audit { + self.record_authorization_denial(event); + } + RuntimeSessionResult { + correlation_id: report.correlation_id.clone(), + outcome: RuntimeSessionOutcome::RejectedUnauthorized as i32, + host_session_id: String::new(), + accepted_sequence: 0, + accepted_at: 0, + reason: "report is outside the approved game/runtime session scope".into(), + denial: Some(DenialDetail { + reason: reason as i32, + permission_id: cap::GAME_SESSIONS_REPORT.into(), + grant_revision, + }), + } + } else if let Some(handler) = { lock(&self.runtime_session_handler).clone() } { + handler + .report( + provider.registration.plugin_id.clone(), + owner_key, + report.clone(), + context_authorized, + context_revision, + received_at, + ) + .await + } else { + RuntimeSessionResult { + correlation_id: report.correlation_id.clone(), + outcome: RuntimeSessionOutcome::RejectedUnavailable as i32, + host_session_id: String::new(), + accepted_sequence: 0, + accepted_at: 0, + reason: "runtime session accounting is unavailable".into(), + denial: None, + } + }; + if result.outcome == RuntimeSessionOutcome::Accepted as i32 { + let mut state = lock(&self.state); + if let Some(session) = state.sessions.get_mut(&context.session_id) { + if !report.runtime_context_id.is_empty() + && let Some(grant) = + session.runtime_contexts.get_mut(&report.runtime_context_id) + { + grant.expires_at = Instant::now() + Duration::from_secs(30); + } + let prior_active = session + .runtime_instances + .get(&report.runtime_instance_id) + .is_some_and(|evidence| evidence.active); + let active = match RuntimeSessionTransition::try_from(report.transition) { + Ok(RuntimeSessionTransition::Started | RuntimeSessionTransition::Resumed) => { + true + } + Ok( + RuntimeSessionTransition::Paused + | RuntimeSessionTransition::Ended + | RuntimeSessionTransition::IdentificationLost, + ) => false, + Ok(RuntimeSessionTransition::ContentChanged) => prior_active, + _ => false, + }; + session.runtime_instances.retain(|_, evidence| { + evidence.last_received_at.elapsed() <= Duration::from_secs(30) + }); + if session.runtime_instances.len() < 128 + || session + .runtime_instances + .contains_key(&report.runtime_instance_id) + { + session.runtime_instances.insert( + report.runtime_instance_id.clone(), + RuntimeInstanceEvidence { + last_received_at: received_at, + runtime_id: report.runtime_id.clone(), + active, + }, + ); + } + } + } + result.correlation_id = report.correlation_id.clone(); + commands + .send(Ok(ProviderCommand { + context: Some(context), + operation: ProviderOperation::RuntimeSessionResult as i32, + target_operation_id: report.correlation_id, + settings: None, + runtime_session_result: Some(result), + runtime_session_context_result: None, + achievements: None, + })) + .await + .map_err(|_| Status::unavailable("provider command stream closed")) + } + + /// Configures the private on-disk root used by the active plugin profile. + pub fn set_state_layout(&self, layout: super::profile::PluginStateLayout) { + self.profiles.set_state_layout(layout); + } + + fn scope_denial(&self, context: &ServiceContext, permission: &str) -> Option { + let state = lock(&self.state); + let session = state.sessions.get(&context.session_id)?; + let event = denial_event(session, permission, DenialReason::ScopeDenied); + let revision = event.grant_revision; + drop(state); + self.record_authorization_denial(event); + Some(denial(DenialReason::ScopeDenied, permission, revision)) + } + + fn record_authorization_denial(&self, event: AuthorizationAuditEvent) { + let mut state = lock(&self.state); + if state.authorization_audit.len() == AUTHORIZATION_AUDIT_LIMIT { + state.authorization_audit.pop_front(); + } + state.authorization_audit.push_back(event); + } + + /// Deliver a rejected stream submission to its authenticated operation + /// waiter before the Exchange stream is closed. A forged context cannot + /// cancel another operation: correlation requires the exact session, + /// credential, provider, and host-issued operation context. + fn reject_stream_operation(&self, context: &ServiceContext, error: Status) { + let operation = { + let mut state = lock(&self.state); + let Some(session) = state.sessions.get(&context.session_id) else { + return; + }; + if !super::constant_time_eq(&session.credential, &context.session_credential) + || session.provider.registration.provider_id != context.provider_id + { + return; + } + let key = (context.session_id.clone(), context.operation_id.clone()); + if !state + .operations + .get(&key) + .is_some_and(|operation| operation.context == *context) + { + return; + } + let operation = state.operations.remove(&key); + if let Some(session) = state.sessions.get_mut(&context.session_id) { + session.completed.push_back(context.operation_id.clone()); + while session.completed.len() > HISTORY { + session.completed.pop_front(); + } + } + operation + }; + if let Some(operation) = operation { + let _ = operation.result.send(Err(error)); + } + } + + /// Returns the bounded, redacted authorization-denial history for host UI + /// and diagnostics. This is never exposed through the plugin RPC surface. + pub fn authorization_audit(&self) -> Vec { + lock(&self.state) + .authorization_audit + .iter() + .cloned() + .collect() + } + + /// Authenticates the permission-control plane without requiring any data grant. + pub fn effective_permissions( + &self, + session_id: &str, + credential: &[u8], + ) -> Result<(u64, Vec), Status> { + let state = lock(&self.state); + let session = state + .sessions + .get(session_id) + .ok_or_else(|| Status::unauthenticated("unknown plugin session"))?; + if !super::constant_time_eq(&session.credential, credential) { + return Err(Status::unauthenticated("invalid plugin session credential")); + } + let change = permission_change(session, false); + Ok((change.revision, change.grants)) + } + + pub fn watch_permissions( + &self, + session_id: &str, + credential: &[u8], + after_revision: u64, + ) -> Result>, Status> { + let mut state = lock(&self.state); + let session = state + .sessions + .get_mut(session_id) + .ok_or_else(|| Status::unauthenticated("unknown plugin session"))?; + if !super::constant_time_eq(&session.credential, credential) { + return Err(Status::unauthenticated("invalid plugin session credential")); + } + let (tx, rx) = mpsc::channel(16); + if session.grant_revision > after_revision { + let change = permission_change(session, false); + let _ = tx.try_send(Ok(change)); + } + session.permission_watchers.push(tx); + Ok(ReceiverStream::new(rx)) + } + + /// Host-only grant update entry point. Persist the grant change before + /// calling this method; consumers then receive the new revision. + pub async fn replace_session_grants( + &self, + session_id: &str, + grants: BTreeSet, + ) -> Result { + if grants + .iter() + .any(|grant| !cap::KNOWN.contains(&grant.as_str())) + { + return Err(Status::invalid_argument("unknown plugin permission")); + } + // Serialize grant changes with every host-side effect commit. A queued + // operation which has not crossed its commit point will reauthorize + // against the new grant set after this guard is released. + let provider = lock(&self.state) + .sessions + .get(session_id) + .map(|session| session.provider.clone()) + .ok_or_else(|| Status::unauthenticated("unknown plugin session"))?; + let (revision, runtime_reporting_revoked, close_configuration, stop_extension) = { + let commit = provider.commits.lock().await; + let mut state = lock(&self.state); + let session = state + .sessions + .get_mut(session_id) + .ok_or_else(|| Status::unauthenticated("unknown plugin session"))?; + let removed: BTreeSet<_> = session.grants.difference(&grants).cloned().collect(); + let revoked = !removed.is_empty(); + let stop_extension = revoked && session.kind == SessionKind::Extension as i32; + session.revoked |= stop_extension; + session.grants = grants; + session.grant_revision = session.grant_revision.saturating_add(1); + let change = permission_change(session, revoked); + session + .permission_watchers + .retain(|watcher| watcher.try_send(Ok(change.clone())).is_ok()); + let revision = session.grant_revision; + let runtime_reporting_revoked = removed.contains(cap::GAME_SESSIONS_REPORT); + if revoked { + let obsolete: Vec<_> = state + .operations + .iter() + .filter(|((id, _), operation)| { + id == session_id + && operation.permissions.iter().any(|p| removed.contains(*p)) + }) + .map(|(key, operation)| { + let permission = operation + .permissions + .iter() + .find(|permission| removed.contains(**permission)) + .copied() + .unwrap_or(cap::CONTEXT); + (key.clone(), permission) + }) + .collect(); + for (key, permission) in obsolete { + if let Some(operation) = state.operations.remove(&key) { + let _ = operation.result.send(Err(denial( + DenialReason::Revoked, + permission, + revision, + ))); + } + } + } + let close_configuration = removed.contains(cap::CONFIGURE); + drop(state); + drop(commit); + ( + revision, + runtime_reporting_revoked, + close_configuration, + stop_extension, + ) + }; + if stop_extension { + self.disconnect_session(session_id).await; + // A removed report grant is no longer in the session's grant set when it closes. + let handler = { lock(&self.runtime_session_handler).clone() }; + if runtime_reporting_revoked && let Some(handler) = handler { + handler + .disconnected(provider.registration.plugin_id.clone()) + .await; + } + return Ok(revision); + } + if close_configuration { + let api = self.clone(); + let session_id = session_id.to_owned(); + tokio::spawn(async move { + if !api.close_configuration_for_session(&session_id).await { + tracing::warn!( + %session_id, + "plugin configuration window did not acknowledge close" + ); + } + }); + } + let runtime_session_handler = { lock(&self.runtime_session_handler).clone() }; + if runtime_reporting_revoked && let Some(handler) = runtime_session_handler { + handler + .disconnected(provider.registration.plugin_id.clone()) + .await; + } + Ok(revision) + } + + pub fn registered(&self, provider_id: &str) -> bool { + lock(&self.state).providers.contains_key(provider_id) + } + + pub fn request_shutdown(&self, provider_id: &str) { + let state = lock(&self.state); + for (id, session) in &state.sessions { + if session.provider.registration.provider_id == provider_id { + Self::send_shutdown(id, session); + } + } + } + + fn send_shutdown(session_id: &str, session: &Session) { + if let Some(commands) = &session.commands + && let Ok(operation_id) = super::random_session_id() + { + let (account_epoch, profile_epoch) = epoch(&session.provider); + let _ = commands.try_send(Ok(ProviderCommand { + context: Some(ServiceContext { + session_id: session_id.to_owned(), + session_credential: session.credential.to_vec(), + provider_id: context_provider_id(&session.provider.registration).into(), + operation_id, + account_epoch, + profile_epoch, + session_kind: session.kind, + target_game: session.target_game.clone(), + }), + operation: ProviderOperation::Shutdown as i32, + target_operation_id: String::new(), + settings: None, + runtime_session_result: None, + runtime_session_context_result: None, + achievements: None, + })); + } + } + + /// Requests a graceful shutdown of the process that owns a terminal one-shot extension job. + pub(crate) fn request_shutdown_session(&self, session_id: &str) { + if let Some(session) = lock(&self.state).sessions.get(session_id) { + Self::send_shutdown(session_id, session); + } + } + + /// Registration is host-owned composition, never a plugin RPC. + pub fn register(&self, registration: Registration) -> Result<(), Status> { + if registration.provider_id.is_empty() + || registration.provider_id.len() > 256 + || registration.plugin_id.is_empty() + || registration.plugin_id.len() > 256 + || registration.declared_developer.trim().is_empty() + || registration.declared_developer.len() > 256 + || registration + .package_digest + .iter() + .any(|_| registration.package_digest.len() != 32) + { + return Err(Status::invalid_argument("invalid provider registration")); + } + match registration.kind { + RegistrationKind::Provider if registration.provider_id.contains(':') => { + return Err(Status::invalid_argument("invalid provider registration")); + } + RegistrationKind::Extension + if !matches!(®istration.origin, RegistrationOrigin::ThirdParty { .. }) + || registration.provider_id + != extension_registration_id(®istration.plugin_id) + || registration.shared_catalog => + { + return Err(Status::invalid_argument( + "invalid provider-free extension registration", + )); + } + _ => {} + } + cap::negotiate( + gamenode_plugin_protocol::API_MAJOR, + gamenode_plugin_protocol::API_MINOR, + ®istration.capabilities, + cap::KNOWN, + ) + .map_err(|_| Status::invalid_argument("invalid provider grants"))?; + if registration .capabilities .iter() - .map(String::as_str) - .collect(); - let minor = cap::negotiate( + .any(|capability| capability == cap::GAME_SESSIONS_REPORT) + && !registration.playtime.can_report_runtime_sessions() + { + return Err(Status::invalid_argument( + "game.sessions.report requires a compatible signed playtime declaration", + )); + } + match registration.kind { + RegistrationKind::Provider + if !registration + .capabilities + .iter() + .any(|s| s == cap::CONTEXT || s == cap::SETTINGS || s == cap::CONFIGURE) => + { + return Err(Status::invalid_argument( + "full provider requires context access", + )); + } + RegistrationKind::Extension + if !registration.capabilities.iter().any(|s| { + s == cap::GAME_LAUNCH || s == cap::GAME_CUSTOM_LAUNCH || s == cap::GAMES_INSTALL + }) => + { + return Err(Status::invalid_argument( + "extension requires an approved game action", + )); + } + _ => {} + } + let _publisher = matches!(registration.origin, RegistrationOrigin::ThirdParty { .. }) + .then(super::managed_packages::lock_publisher_identity); + let mut state = lock(&self.state); + if state.providers.contains_key(®istration.provider_id) + || state + .providers + .values() + .any(|p| p.registration.plugin_id == registration.plugin_id) + { + return Err(Status::already_exists("provider is already registered")); + } + state.providers.insert( + registration.provider_id.clone(), + Arc::new(Provider { + extension_schemas: std::sync::RwLock::new(Vec::new()), + declared_capabilities: std::sync::RwLock::new(registration.capabilities.clone()), + capabilities: std::sync::RwLock::new(registration.capabilities.clone()), + profiles: matches!(registration.origin, RegistrationOrigin::ThirdParty { .. }) + .then(|| self.profiles.clone()), + registration, + account_epoch: 1.into(), + profile_epoch: 1.into(), + identity_revision: 1.into(), + commits: Arc::new(tokio::sync::Mutex::new(())), + }), + ); + Ok(()) + } + + pub fn begin_launch(&self, provider_id: &str) -> Result { + self.begin_launch_for_profile(provider_id, None) + } + + /// Attach descriptors derived by the host from the integrity-verified active package. + /// RPC payloads cannot register or replace this catalog. + pub(crate) fn set_extension_schemas( + &self, + provider_id: &str, + plugin_id: &str, + publisher_fingerprint: &str, + descriptors: Vec, + ) -> Result<(), Status> { + gamenode_plugin_protocol::extensions::validate_schema_catalog(&descriptors) + .map_err(|_| Status::invalid_argument("invalid package extension schema catalog"))?; + let state = lock(&self.state); + let provider = state + .providers + .get(provider_id) + .ok_or_else(|| Status::not_found("plugin registration not found"))?; + if provider.registration.plugin_id != plugin_id + || !matches!(&provider.registration.origin, RegistrationOrigin::ThirdParty { publisher_fingerprint: actual } if actual == publisher_fingerprint) + { + return Err(Status::permission_denied( + "schema catalog package identity mismatch", + )); + } + *provider + .extension_schemas + .write() + .unwrap_or_else(std::sync::PoisonError::into_inner) = descriptors; + Ok(()) + } + + pub(crate) fn extension_schemas_for_provider( + &self, + provider_id: &str, + ) -> Vec { + lock(&self.state) + .providers + .get(provider_id) + .map(|provider| { + provider + .extension_schemas + .read() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .clone() + }) + .unwrap_or_default() + } + + pub(crate) fn begin_launch_for_profile( + &self, + provider_id: &str, + expected_profile_epoch: Option, + ) -> Result { + self.begin_scoped_launch( + provider_id, + expected_profile_epoch, + SessionKind::Provider as i32, + None, + None, + ) + } + + #[cfg(test)] + pub(crate) fn begin_extension_launch( + &self, + provider_id: &str, + expected_profile_epoch: u64, + target_game: TargetGameContext, + ) -> Result { + cap::validate_target(&target_game) + .map_err(|_| Status::invalid_argument("invalid target game context"))?; + self.begin_scoped_launch( + provider_id, + Some(expected_profile_epoch), + SessionKind::Extension as i32, + Some(target_game), + None, + ) + } + + pub(crate) fn begin_supervised_extension( + &self, + slot_id: &str, + extension: SupervisedExtension, + ) -> Result { + let target = &extension.target; + cap::validate_target(&target.context) + .map_err(|_| Status::invalid_argument("invalid target game context"))?; + if !target.is_current() { + return Err(Status::failed_precondition( + "selected extension target is unavailable", + )); + } + self.begin_scoped_launch( + slot_id, + Some(target.profile_epoch), + SessionKind::Extension as i32, + Some(target.context.clone()), + Some(extension), + ) + } + + fn begin_scoped_launch( + &self, + provider_id: &str, + expected_profile_epoch: Option, + session_kind: i32, + target_game: Option, + extension: Option, + ) -> Result { + let mut state = lock(&self.state); + let provider = state + .providers + .get(provider_id) + .cloned() + .ok_or_else(|| Status::not_found("provider is unavailable"))?; + if (session_kind == SessionKind::Extension as i32) + != (provider.registration.kind == RegistrationKind::Extension) + { + return Err(Status::permission_denied( + "process launch kind does not match registration", + )); + } + // A third-party process runs only inside an active GameNode account profile. + let profile_epoch = if let Some(profiles) = provider.profiles.as_ref() { + let profile = profiles.require()?; + if expected_profile_epoch.is_some_and(|expected| expected != profile.epoch()) { + return Err(Status::failed_precondition( + "plugin profile changed during startup", + )); + } + if extension.is_some() + && (!profile.verified() + || target_game + .as_ref() + .is_none_or(|target| target.profile_id != profile.profile_id())) + { + return Err(Status::failed_precondition( + "extension target belongs to another profile", + )); + } + Some(profile.epoch()) + } else { + None + }; + if state.pending.len() + state.sessions.len() >= 16 { + return Err(Status::resource_exhausted("provider session capacity")); + } + if state + .pending + .iter() + .any(|p| p.provider.registration.provider_id == provider_id) + || state + .sessions + .values() + .any(|s| s.provider.registration.provider_id == provider_id) + { + return Err(Status::already_exists( + "provider already has a process session", + )); + } + let mut credential = [0; 32]; + getrandom::fill(&mut credential) + .map_err(|_| Status::internal("could not create launch credential"))?; + let (ready, receiver) = oneshot::channel(); + let (closed, disconnected) = oneshot::channel(); + state.pending.push(Pending { + provider, + credential, + profile_epoch, + session_kind, + target_game, + ready, + closed, + extension, + }); + Ok(Launch { + credential: super::hex(&credential), + ready: receiver, + closed: disconnected, + }) + } + + pub fn owns_launch(&self, credential: &[u8]) -> bool { + lock(&self.state) + .pending + .iter() + .any(|p| super::constant_time_eq(&p.credential, credential)) + } + + pub fn open_session(&self, hello: &OpenSessionRequest) -> Result { + let mut state = lock(&self.state); + let index = state + .pending + .iter() + .position(|p| super::constant_time_eq(&p.credential, &hello.session_credential)) + .ok_or_else(|| Status::unauthenticated("unknown provider launch"))?; + let profile_changed = state.pending[index] + .profile_epoch + .is_some_and(|expected| !self.profiles.is_current(expected)); + if profile_changed { + state.pending.remove(index); + return Err(Status::failed_precondition( + "plugin profile changed during startup", + )); + } + let pending = &state.pending[index]; + if pending.provider.registration.plugin_id != hello.plugin_id { + return Err(Status::unauthenticated( + "provider identity does not match launch", + )); + } + if hello.plugin_version.is_empty() || hello.plugin_version.len() > 128 { + return Err(Status::invalid_argument("invalid plugin version")); + } + if let Some(extension) = &pending.extension { + if !extension.target.is_current() { + return Err(Status::failed_precondition( + "selected extension target is unavailable", + )); + } + if extension + .expected_version + .as_ref() + .is_some_and(|version| *version != hello.plugin_version) + { + return Err(Status::unauthenticated( + "extension version does not match the verified package", + )); + } + } + let current_capabilities = pending + .provider + .capabilities + .read() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .clone(); + let allowed: Vec<&str> = current_capabilities.iter().map(String::as_str).collect(); + cap::validate_session_scope( + u32::try_from(hello.session_kind).unwrap_or(u32::MAX), + hello.target_game.is_some(), + ) + .map_err(|_| Status::invalid_argument("invalid session scope"))?; + let extension_session = hello.session_kind == SessionKind::Extension as i32; + let legacy_provider_scope = pending.session_kind == SessionKind::Provider as i32 + && hello.session_kind == SessionKind::Unspecified as i32; + if (!legacy_provider_scope && hello.session_kind != pending.session_kind) + || hello.target_game != pending.target_game + { + return Err(Status::permission_denied( + "session scope does not match the host-selected launch", + )); + } + if extension_session != (pending.provider.registration.kind == RegistrationKind::Extension) + { + return Err(Status::permission_denied( + "session kind does not match the registered plugin kind", + )); + } + if let Some(target) = hello.target_game.as_ref() { + cap::validate_target(target) + .map_err(|_| Status::invalid_argument("invalid target game context"))?; + } + let selection = cap::negotiate_range( hello.api_major, hello.api_minor, - &hello.requested_capabilities, - &allowed, + hello.min_api_major, + hello.min_api_minor, + hello.max_api_major, + hello.max_api_minor, + &hello + .features + .iter() + .map(|f| (f.id.clone(), f.required)) + .collect::>(), ) .map_err(|error| match error { - cap::NegotiationError::Capability => Status::permission_denied(error.to_string()), + cap::RangeNegotiationError::RequiredFeature => { + Status::failed_precondition(error.to_string()) + } + cap::RangeNegotiationError::Session => Status::invalid_argument(error.to_string()), _ => Status::failed_precondition(error.to_string()), })?; - let requested: BTreeSet = hello.requested_capabilities.iter().cloned().collect(); - if requested - != pending - .provider - .registration - .capabilities + if extension_session && selection.api_minor < cap::THIRD_PARTY_API_MINOR { + return Err(Status::failed_precondition( + "extension sessions require API 1.6", + )); + } + let mut seen_capabilities = BTreeSet::new(); + if hello.requested_capabilities.is_empty() + || hello + .requested_capabilities .iter() - .cloned() - .collect() + .any(|capability| !seen_capabilities.insert(capability.as_str())) { + return Err(Status::invalid_argument( + "invalid provider capability request", + )); + } + let requested: BTreeSet = hello.requested_capabilities.iter().cloned().collect(); + let declared_capabilities = pending + .provider + .declared_capabilities + .read() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .clone(); + let declared: BTreeSet = declared_capabilities.iter().cloned().collect(); + if !requested.is_subset(&declared) { + return Err(Status::permission_denied( + "requested provider permission is not declared by the package", + )); + } + let third_party = pending.provider.profiles.is_some(); + if !third_party && requested != current_capabilities.iter().cloned().collect() { return Err(Status::failed_precondition( "required provider capabilities are missing", )); } + let mut granted: BTreeSet = if third_party { + requested + .intersection(¤t_capabilities.iter().cloned().collect()) + .cloned() + .collect() + } else { + requested + }; + // An extension's context is the target the Core chose for this launch. It is an + // implicit session scope, not a permission to enumerate or widen the library. + if extension_session { + granted.insert(cap::CONTEXT.to_owned()); + } + // A full provider may be settings- or configuration-only, without library context; the + // registration check above accepts exactly those three capabilities. Context-requiring + // calls stay denied per operation, so the session still cannot enumerate the library. + const SESSION_SCOPE: [&str; 3] = [cap::CONTEXT, cap::SETTINGS, cap::CONFIGURE]; + if !SESSION_SCOPE + .iter() + .any(|capability| granted.contains(*capability)) + { + return Err(denial(DenialReason::NotGranted, cap::CONTEXT, 0)); + } + if let Some(permission) = pending + .extension + .as_ref() + .and_then(|extension| extension.required_permission) + && !granted.contains(permission) + { + return Err(denial(DenialReason::NotGranted, permission, 0)); + } + let granted_capabilities = granted.iter().cloned().collect::>(); + let minor = cap::negotiate( + selection.api_major, + selection.api_minor, + &granted_capabilities, + &allowed, + ) + .map_err(|error| match error { + cap::NegotiationError::Capability => { + if let Some(permission) = granted_capabilities + .iter() + .find(|permission| !cap::KNOWN.contains(&permission.as_str())) + { + Status::failed_precondition(format!( + "unsupported provider permission: {permission}" + )) + } else { + Status::invalid_argument(error.to_string()) + } + } + _ => Status::failed_precondition(error.to_string()), + })?; let pending = state.pending.remove(index); let session_id = super::random_session_id()?; + let resource_context = if minor >= cap::THIRD_PARTY_API_MINOR { + let (account_epoch, profile_epoch) = epoch(&pending.provider); + Some(ServiceContext { + session_id: session_id.clone(), + session_credential: pending.credential.to_vec(), + provider_id: context_provider_id(&pending.provider.registration).into(), + operation_id: super::random_session_id()?, + account_epoch, + profile_epoch: pending.profile_epoch.unwrap_or(profile_epoch), + session_kind: hello.session_kind, + target_game: pending.target_game.clone(), + }) + } else { + None + }; state.sessions.insert( session_id.clone(), Session { provider: pending.provider, + package_version: hello.plugin_version.clone(), credential: pending.credential, - grants: requested.clone(), + grants: granted.clone(), + kind: hello.session_kind, + target_game: pending.target_game, + grant_revision: 1, + permission_watchers: Vec::new(), commands: None, ready: Some(pending.ready), + _closed: pending.closed, + extension: pending.extension, + revoked: false, completed: VecDeque::new(), + resource_context: resource_context.clone(), + resource_operation: resource_context + .as_ref() + .map(|context| context.operation_id.clone()), + runtime_contexts: HashMap::new(), + runtime_instances: HashMap::new(), }, ); Ok(OpenSessionReply { + resource_context, session_id, - granted_capabilities: requested.into_iter().collect(), + granted_capabilities, api_major: gamenode_plugin_protocol::API_MAJOR, api_minor: minor, + features: selection + .features + .into_iter() + .map(|(id, supported, introduced_minor)| FeatureStatus { + id, + availability: if supported { + FeatureAvailability::Supported as i32 + } else { + FeatureAvailability::Unsupported as i32 + }, + introduced_minor, + }) + .collect(), + support_window: Some(SupportWindow { + minimum_api_minor: gamenode_plugin_protocol::MIN_API_MINOR, + maximum_api_minor: gamenode_plugin_protocol::API_MINOR, + support_ends_at: None, + policy: "supported by this GameNode build".into(), + }), }) } @@ -620,6 +2089,138 @@ impl ProviderApi { .any(|s| s.provider.registration.provider_id == provider_id && s.commands.is_some()) } + /// Registered providers bound to an account profile. Their supervised processes must stop + /// whenever that profile changes; official providers are deliberately excluded. + pub(crate) fn third_party_provider_ids(&self) -> Vec { + lock(&self.state) + .providers + .values() + .filter(|provider| provider.profiles.is_some()) + .map(|provider| provider.registration.provider_id.clone()) + .collect() + } + + /// Provider process registrations owned by one installed third-party plugin. + pub(crate) fn third_party_provider_ids_for_plugin(&self, plugin_id: &str) -> Vec { + lock(&self.state) + .providers + .values() + .filter(|provider| { + provider.profiles.is_some() && provider.registration.plugin_id == plugin_id + }) + .map(|provider| provider.registration.provider_id.clone()) + .collect() + } + + pub(crate) fn is_extension(&self, provider_id: &str) -> bool { + lock(&self.state) + .providers + .get(provider_id) + .is_some_and(|provider| provider.registration.kind == RegistrationKind::Extension) + } + + pub(crate) fn third_party_identity(&self, provider_id: &str) -> Option<(String, String)> { + lock(&self.state) + .providers + .get(provider_id) + .filter(|provider| provider.profiles.is_some()) + .and_then(|provider| match &provider.registration.origin { + RegistrationOrigin::ThirdParty { + publisher_fingerprint, + } => Some(( + provider.registration.plugin_id.clone(), + publisher_fingerprint.clone(), + )), + RegistrationOrigin::Official => None, + }) + } + + /// Replace the session capability ceiling from the currently validated package and its + /// profile's persisted grants. Effective permissions must be a subset of the signed manifest. + pub(crate) fn set_third_party_capabilities( + &self, + provider_id: &str, + declared: &[String], + effective: &[String], + ) -> Result<(), Status> { + let declared = declared.iter().map(String::as_str).collect::>(); + let effective = effective + .iter() + .map(String::as_str) + .collect::>(); + if declared + .iter() + .chain(effective.iter()) + .any(|permission| !cap::KNOWN.contains(permission)) + || !effective.is_subset(&declared) + || !declared.contains(cap::CONTEXT) + || !effective.contains(cap::CONTEXT) + { + return Err(Status::invalid_argument( + "invalid third-party permission set", + )); + } + let mut state = lock(&self.state); + let provider = state + .providers + .get_mut(provider_id) + .filter(|provider| provider.profiles.is_some()) + .ok_or_else(|| Status::not_found("third-party provider is not registered"))?; + *provider + .capabilities + .write() + .unwrap_or_else(std::sync::PoisonError::into_inner) = + effective.into_iter().map(str::to_owned).collect(); + *provider + .declared_capabilities + .write() + .unwrap_or_else(std::sync::PoisonError::into_inner) = + declared.into_iter().map(str::to_owned).collect(); + Ok(()) + } + + /// Fences sessions and unregisters a third-party plugin after its process has been stopped. + /// Official registrations are never eligible for removal through this lifecycle path. + pub(crate) async fn unregister_third_party_plugin( + &self, + plugin_id: &str, + ) -> Result, Status> { + let providers: Vec<_> = { + let state = lock(&self.state); + let matching = state + .providers + .values() + .filter(|provider| provider.registration.plugin_id == plugin_id) + .cloned() + .collect::>(); + if matching.iter().any(|provider| provider.profiles.is_none()) { + return Err(Status::permission_denied( + "official plugin registrations cannot be removed here", + )); + } + matching + }; + let provider_ids = providers + .iter() + .map(|provider| provider.registration.provider_id.clone()) + .collect::>(); + for provider in &providers { + drop(provider.commits.lock().await); + self.disconnect(&provider.registration.provider_id).await; + } + let api = self.clone(); + tokio::task::spawn_blocking(move || { + let _publisher = super::managed_packages::lock_publisher_identity(); + let mut state = lock(&api.state); + for provider_id in &provider_ids { + state.providers.remove(provider_id); + } + provider_ids + }) + .await + .map_err(|_| Status::internal("plugin unregistration worker failed")) + } + pub async fn disconnect(&self, provider_id: &str) { let ids = { let mut state = lock(&self.state); @@ -638,17 +2239,73 @@ impl ProviderApi { } } + /// The account-bound profile source shared by every third-party registration. + pub fn profiles(&self) -> Arc { + self.profiles.clone() + } + + /// Stops every third-party session after an account profile change. The profile epoch has + /// already advanced, so their contexts are stale; waiting for each commit guard lets a commit + /// that passed its check finish in the previous profile before the session goes away. + /// Official providers are not account-profile scoped and keep running. + pub async fn fence_third_party_sessions(&self) { + let sessions: Vec<_> = lock(&self.state) + .sessions + .iter() + .filter(|(_, session)| { + session.provider.profiles.is_some() + && session.extension.as_ref().is_none_or(|extension| { + !self.profiles.is_current(extension.target.profile_epoch) + }) + }) + .map(|(id, _)| id.clone()) + .collect(); + for session_id in sessions { + let _ = self.close_configuration_for_session(&session_id).await; + self.request_shutdown_session(&session_id); + self.disconnect_session(&session_id).await; + } + } + + /// Follows account profile changes for the lifetime of this API: each change fences and + /// stops third-party sessions. Call once from the host runtime. + pub fn spawn_profile_fencing(&self, runtime: &tokio::runtime::Handle) { + let api = self.clone(); + let mut changes = self.profiles.subscribe(); + runtime.spawn(async move { + let mut epoch = api.profiles.epoch(); + while changes.changed().await.is_ok() { + let current = api.profiles.epoch(); + if current != epoch { + epoch = current; + api.fence_third_party_sessions().await; + } + } + }); + } + /// Called by the profile owner before replacing profile-backed adapters. /// Existing sessions cannot acquire authority over the next profile. pub async fn invalidate_profile(&self) { let providers: Vec<_> = lock(&self.state).providers.values().cloned().collect(); for provider in providers { + let provider_id = provider.registration.provider_id.clone(); + let session_ids: Vec<_> = lock(&self.state) + .sessions + .iter() + .filter(|(_, session)| session.provider.registration.provider_id == provider_id) + .map(|(id, _)| id.clone()) + .collect(); + for session_id in session_ids { + let _ = self.close_configuration_for_session(&session_id).await; + } + self.request_shutdown(&provider_id); let guard = provider.commits.lock().await; provider .profile_epoch .fetch_add(1, std::sync::atomic::Ordering::AcqRel); drop(guard); - self.disconnect(&provider.registration.provider_id).await; + self.disconnect(&provider_id).await; } } @@ -661,7 +2318,7 @@ impl ProviderApi { return; }; let guard = provider.commits.lock().await; - let services = { + let (services, plugin_id, reported_sessions) = { let mut state = lock(&self.state); let Some(session) = state.sessions.remove(session_id) else { return; @@ -679,51 +2336,100 @@ impl ProviderApi { .send(Err(Status::unavailable("provider process disconnected"))); } } - session.provider.registration.services.clone() + ( + session.provider.registration.services.clone(), + session.provider.registration.plugin_id.clone(), + session.grants.contains(cap::GAME_SESSIONS_REPORT), + ) }; drop(guard); + self.configuration_windows + .lock() + .await + .retain(|_, window| window.session_id != session_id); services.session_closed(session_id).await; - } - - /// Delivers the validation error that ended a provider event stream to the operation it - /// belongs to, instead of reporting only that the process disconnected. - fn fail_operation(&self, context: Option<&ServiceContext>, error: &Status) { - let Some(context) = context else { - return; - }; - let mut state = lock(&self.state); - if let Some(operation) = state - .operations - .remove(&(context.session_id.clone(), context.operation_id.clone())) + if let Some(broker) = lock(&self.shared_data_broker) + .as_ref() + .and_then(Weak::upgrade) { - let _ = operation.result.send(Err(error.clone())); + broker.close_session(session_id); + } + let runtime_session_handler = { lock(&self.runtime_session_handler).clone() }; + if reported_sessions && let Some(handler) = runtime_session_handler { + handler.disconnected(plugin_id).await; } } + /// Delivers the validation error that ended a provider event stream to the operation it + /// belongs to, instead of reporting only that the process disconnected. fn authorize( &self, context: &ServiceContext, permission: &'static str, ) -> Result, Status> { let state = lock(&self.state); - let session = state - .sessions - .get(&context.session_id) - .ok_or_else(|| Status::unauthenticated("provider session expired"))?; - if !super::constant_time_eq(&session.credential, &context.session_credential) - || context.provider_id != session.provider.registration.provider_id - || !session.grants.contains(permission) - { - return Err(Status::permission_denied("provider scope denied")); + let Some(session) = state.sessions.get(&context.session_id) else { + return Err(Status::unauthenticated("provider session expired")); + }; + if !super::constant_time_eq(&session.credential, &context.session_credential) { + let event = denial_event(session, permission, DenialReason::ScopeDenied); + let revision = event.grant_revision; + drop(state); + self.record_authorization_denial(event); + return Err(denial(DenialReason::ScopeDenied, permission, revision)); + } + if session.provider.registration.kind == RegistrationKind::Extension { + return Err(Status::permission_denied( + "provider operations are unavailable to extensions", + )); + } + if context.session_kind != session.kind || context.target_game != session.target_game { + let event = denial_event(session, permission, DenialReason::ScopeDenied); + let revision = event.grant_revision; + drop(state); + self.record_authorization_denial(event); + return Err(denial(DenialReason::ScopeDenied, permission, revision)); + } + if context.provider_id != session.provider.registration.provider_id { + let event = denial_event(session, permission, DenialReason::ScopeDenied); + let revision = event.grant_revision; + drop(state); + self.record_authorization_denial(event); + return Err(denial(DenialReason::ScopeDenied, permission, revision)); } let operation = state .operations - .get(&(context.session_id.clone(), context.operation_id.clone())) - .ok_or_else(|| Status::failed_precondition("provider operation is stale"))?; + .get(&(context.session_id.clone(), context.operation_id.clone())); + // A close acknowledgement is a host cleanup signal. After profile fencing or grant + // revocation it may finish against the old context, but this exception applies only to + // the correlated `ui.configure` result and never authorizes provider/resource services. + let configuration_cleanup = permission == cap::CONFIGURE + && operation.is_some_and(|operation| { + operation.kind == ProviderOperation::ConfigurationClose + && operation.configuration_cleanup + }); + if !configuration_cleanup + && session + .provider + .profiles + .as_ref() + .is_some_and(|profiles| profiles.current().is_none()) + { + return Err(super::profile::no_profile()); + } + if !session.grants.contains(permission) && !configuration_cleanup { + let event = denial_event(session, permission, DenialReason::NotGranted); + let revision = event.grant_revision; + drop(state); + self.record_authorization_denial(event); + return Err(denial(DenialReason::NotGranted, permission, revision)); + } + let operation = + operation.ok_or_else(|| Status::failed_precondition("provider operation is stale"))?; let current = epoch(&session.provider); let account_scoped = account_scoped(operation.kind); if operation.context != *context - || current.1 != context.profile_epoch + || (!configuration_cleanup && current.1 != context.profile_epoch) || (account_scoped && (current.0 != context.account_epoch || operation.identity_revision @@ -734,12 +2440,204 @@ impl ProviderApi { { return Err(Status::failed_precondition("provider operation is stale")); } - if !operation.permissions.contains(permission) { - return Err(Status::permission_denied("operation capability denied")); + if !operation.permissions.contains(permission) && !configuration_cleanup { + let event = denial_event(session, permission, DenialReason::NotGranted); + let revision = event.grant_revision; + drop(state); + self.record_authorization_denial(event); + return Err(denial(DenialReason::NotGranted, permission, revision)); } Ok(session.provider.clone()) } + /// Authorizes a plugin-initiated resource call. The context must be the session's resource + /// context from `OpenSession`, for the active profile; it adds no authority, so `permission` + /// must still be one of the session's grants. A missing account profile makes the call + /// unavailable rather than denied. + pub(crate) fn authorize_resource( + &self, + context: Option<&ServiceContext>, + permission: &'static str, + ) -> Result { + self.resource_caller(context, Some(permission)) + } + + /// Authorizes a resource mutation while holding the provider's session commit lock. Session + /// disconnect waits for this guard, then removes any session-retained data written here. + pub(crate) async fn authorize_resource_commit( + &self, + context: &ServiceContext, + permission: &'static str, + ) -> Result<(ResourceCaller, OwnedMutexGuard<()>), Status> { + let initial = self.authorize_resource(Some(context), permission)?; + let provider = { + let state = lock(&self.state); + state + .sessions + .get(&context.session_id) + .map(|session| session.provider.clone()) + .ok_or_else(|| Status::unauthenticated("plugin session expired"))? + }; + let guard = provider.commits.clone().lock_owned().await; + let current = self.authorize_resource(Some(context), permission)?; + if current.grant_revision != initial.grant_revision + || current.profile_epoch != initial.profile_epoch + { + return Err(Status::failed_precondition( + "plugin permissions changed; retry the resource mutation", + )); + } + Ok((current, guard)) + } + + /// [`authorize_resource`](Self::authorize_resource) without naming a permission: the session, + /// credential, profile and operation checks only. A call whose permission is only known after + /// finding the record it touches (a job's) authorizes here, looks the record up under the + /// caller's own identity, and then calls `authorize_resource` with the record's permission. + pub(crate) fn authorize_resource_session( + &self, + context: Option<&ServiceContext>, + ) -> Result { + self.resource_caller(context, None) + } + + fn resource_caller( + &self, + context: Option<&ServiceContext>, + permission: Option<&'static str>, + ) -> Result { + // What a denial event names when no permission is being asked for. + let label = permission.unwrap_or("resource.session"); + let context = + context.ok_or_else(|| Status::unauthenticated("resource context required"))?; + let state = lock(&self.state); + let Some(session) = state.sessions.get(&context.session_id) else { + return Err(Status::unauthenticated("plugin session expired")); + }; + if !session.extension_authority() { + return Err(Status::permission_denied( + "extension session has no active target authority", + )); + } + let scope_denied = |session: &Session| { + let event = denial_event(session, label, DenialReason::ScopeDenied); + let revision = event.grant_revision; + (event, denial(DenialReason::ScopeDenied, label, revision)) + }; + if !super::constant_time_eq(&session.credential, &context.session_credential) + || context.session_kind != session.kind + || context.target_game != session.target_game + || context.provider_id != context_provider_id(&session.provider.registration) + { + let (event, status) = scope_denied(session); + drop(state); + self.record_authorization_denial(event); + return Err(status); + } + if session + .provider + .profiles + .as_ref() + .is_some_and(|profiles| profiles.current().is_none()) + { + return Err(super::profile::no_profile()); + } + let Some(operation) = session.resource_operation.as_deref() else { + return Err(Status::failed_precondition( + "resource services need API 1.6 or later", + )); + }; + let (_, profile_epoch) = epoch(&session.provider); + if !super::constant_time_eq(operation.as_bytes(), context.operation_id.as_bytes()) + || context.profile_epoch != profile_epoch + { + return Err(Status::failed_precondition("resource context is stale")); + } + if let Some(permission) = permission + && !session.grants.contains(permission) + { + let event = denial_event(session, permission, DenialReason::NotGranted); + let revision = event.grant_revision; + drop(state); + self.record_authorization_denial(event); + return Err(denial(DenialReason::NotGranted, permission, revision)); + } + let namespace = match ( + &session.provider.registration.origin, + session.provider.profiles.as_ref(), + ) { + ( + RegistrationOrigin::ThirdParty { + publisher_fingerprint, + }, + Some(profiles), + ) => profiles + .resolver( + &session.provider.registration.plugin_id, + publisher_fingerprint, + (session.provider.registration.kind == RegistrationKind::Provider) + .then_some(session.provider.registration.provider_id.as_str()), + ) + .ok(), + _ => None, + }; + Ok(ResourceCaller { + session_id: context.session_id.clone(), + provider_id: session.provider.registration.provider_id.clone(), + declared_developer: session.provider.registration.declared_developer.clone(), + origin: match session.provider.registration.origin { + RegistrationOrigin::Official => "official".into(), + RegistrationOrigin::ThirdParty { .. } => "third-party-package".into(), + }, + package_digest: session.provider.registration.package_digest.clone(), + package_version: session.package_version.clone(), + grants: session.grants.clone(), + grant_revision: session.grant_revision, + profile_epoch, + namespace, + }) + } + + /// The denial for a resource call whose permission is held but whose *scope* is not: it is + /// recorded like any authorization denial and carries the machine-readable detail. + pub(crate) fn deny_resource_scope( + &self, + caller: &ResourceCaller, + permission: &'static str, + ) -> Status { + let event = { + let state = lock(&self.state); + let Some(session) = state.sessions.get(&caller.session_id) else { + return Status::unauthenticated("plugin session expired"); + }; + denial_event(session, permission, DenialReason::ScopeDenied) + }; + let revision = event.grant_revision; + self.record_authorization_denial(event); + denial(DenialReason::ScopeDenied, permission, revision) + } + + /// Host-only original contexts for lifecycle consumers. Never refresh an old + /// session's profile epoch, and never return these credentials through a public RPC. + pub(crate) fn resource_session_contexts(&self) -> Vec { + lock(&self.state) + .sessions + .values() + .filter(|session| { + matches!( + session.provider.registration.origin, + RegistrationOrigin::ThirdParty { .. } + ) + }) + .filter_map(|session| session.resource_context.clone()) + .collect() + } + + /// Whether the plugin session `session_id` is still open. + pub(crate) fn session_is_open(&self, session_id: &str) -> bool { + lock(&self.state).sessions.contains_key(session_id) + } + fn lease( &self, context: Option, @@ -763,7 +2661,305 @@ impl ProviderApi { provider_id: &str, kind: ProviderOperation, ) -> Result { - self.execute_payload(provider_id, kind, None, None).await + if is_configuration(kind) { + return Err(Status::invalid_argument( + "configuration operations require a host-managed window", + )); + } + self.execute_payload(provider_id, kind, None, None, None, String::new()) + .await + } + + /// Opens or focuses the one external configuration window owned by this plugin in the + /// active account profile. The host supplies an opaque handle and requires every lifecycle + /// acknowledgement to echo that handle, session and profile exactly. + pub async fn configure( + &self, + provider_id: &str, + requested: ProviderOperation, + ) -> Result { + if !matches!( + requested, + ProviderOperation::ConfigurationOpen + | ProviderOperation::ConfigurationFocus + | ProviderOperation::ConfigurationClose + ) { + return Err(Status::invalid_argument("invalid configuration operation")); + } + + let provider = lock(&self.state) + .providers + .get(provider_id) + .cloned() + .ok_or_else(|| Status::unavailable("provider unavailable"))?; + if !matches!( + provider.registration.origin, + RegistrationOrigin::ThirdParty { .. } + ) { + return Err(Status::failed_precondition( + "external configuration is only available to third-party plugins", + )); + } + let profile = provider + .profiles + .as_ref() + .ok_or_else(super::profile::no_profile)? + .require()?; + let key = ( + provider.registration.plugin_id.clone(), + profile.profile_id().to_owned(), + ); + let active_session_id = lock(&self.state) + .sessions + .iter() + .find(|(_, session)| { + session.provider.registration.provider_id == provider_id + && session.commands.is_some() + }) + .map(|(id, _)| id.clone()) + .ok_or_else(|| Status::unavailable("provider process is unavailable"))?; + { + let state = lock(&self.state); + let session = state + .sessions + .get(&active_session_id) + .ok_or_else(|| Status::unavailable("provider process is unavailable"))?; + if !session.grants.contains(cap::CONFIGURE) { + return Err(denial( + DenialReason::NotGranted, + cap::CONFIGURE, + session.grant_revision, + )); + } + } + + // Serialize only lifecycle requests for configuration windows. Provider operations use + // their normal bounded command path and remain serviceable while this lock is held. + let mut windows = self.configuration_windows.lock().await; + let existing = windows + .get(&key) + .filter(|window| { + window.profile_epoch == profile.epoch() && window.session_id == active_session_id + }) + .cloned(); + if existing.is_none() { + windows.remove(&key); + } + + let (operation, window_id, store_on_accept) = match (requested, existing) { + (ProviderOperation::ConfigurationClose, None) + | (ProviderOperation::ConfigurationFocus, None) => { + return Err(Status::failed_precondition( + "plugin configuration window is not open", + )); + } + (ProviderOperation::ConfigurationOpen, Some(window)) => ( + ProviderOperation::ConfigurationFocus, + window.window_id, + false, + ), + (operation, Some(window)) => (operation, window.window_id, false), + (ProviderOperation::ConfigurationOpen, None) => ( + ProviderOperation::ConfigurationOpen, + super::random_session_id()?, + true, + ), + _ => unreachable!("validated configuration operation"), + }; + let binding = ConfigurationBinding { + profile_id: profile.profile_id().to_owned(), + session_id: active_session_id, + window_id: window_id.clone(), + }; + if store_on_accept { + windows.insert( + key.clone(), + ConfigurationWindow { + profile_epoch: profile.epoch(), + session_id: binding.session_id.clone(), + window_id: window_id.clone(), + }, + ); + } + let completion = match self + .execute_payload( + provider_id, + operation, + None, + None, + Some(binding), + window_id.clone(), + ) + .await + { + Ok(completion) => completion, + Err(error) => { + if error.code() == tonic::Code::ResourceExhausted { + windows.remove(&key); + } + return Err(error); + } + }; + let accepted = completion + .result + .configuration + .as_ref() + .is_some_and(|result| result.accepted); + if operation == ProviderOperation::ConfigurationClose { + if accepted { + windows.remove(&key); + } + } else if !accepted { + // A rejected Focus means the cached window handle no longer describes a live + // window. Clear it so the next Configure request can retry with a fresh Open. + windows.remove(&key); + } + Ok(completion) + } + + /// Close a configuration window before its process is stopped. The window entry is consumed + /// even if the plugin does not acknowledge, so a later session cannot inherit its handle. + pub(crate) async fn close_configuration_before_stop(&self, provider_id: &str) -> bool { + let session_id = lock(&self.state) + .sessions + .iter() + .find(|(_, session)| { + session.provider.registration.provider_id == provider_id + && session.commands.is_some() + }) + .map(|(id, _)| id.clone()); + match session_id { + Some(id) => self.close_configuration_for_session(&id).await, + None => false, + } + } + + /// A profile or permission fence has already invalidated the old context before this runs. + /// Send a narrowly scoped Close command using that old epoch and accept only its correlated + /// lifecycle result. This cleanup exception never authorizes data or provider operations. + async fn close_configuration_for_session(&self, session_id: &str) -> bool { + let window = { + let mut windows = self.configuration_windows.lock().await; + let entry = windows + .iter() + .find(|(_, window)| window.session_id == session_id) + .map(|(key, window)| (key.clone(), window.clone())); + entry.and_then(|(key, window)| windows.remove(&key).map(|_| (key, window))) + }; + let Some(((plugin_id, profile_id), window)) = window else { + return false; + }; + let operation_id = match super::random_session_id() { + Ok(operation_id) => operation_id, + Err(_) => return false, + }; + let (context, commands, result_receiver) = { + let mut state = lock(&self.state); + let ( + commands, + credential, + provider_id, + account_epoch, + session_kind, + target_game, + identity_revision, + ) = { + let Some(session) = state.sessions.get(session_id) else { + return false; + }; + if session.provider.registration.plugin_id != plugin_id + || !matches!( + session.provider.registration.origin, + RegistrationOrigin::ThirdParty { .. } + ) + { + return false; + } + let Some(commands) = session.commands.clone() else { + return false; + }; + ( + commands, + session.credential, + context_provider_id(&session.provider.registration).to_owned(), + session + .provider + .account_epoch + .load(std::sync::atomic::Ordering::Acquire), + session.kind, + session.target_game.clone(), + session + .provider + .identity_revision + .load(std::sync::atomic::Ordering::Acquire), + ) + }; + let context = ServiceContext { + session_id: session_id.to_owned(), + session_credential: credential.to_vec(), + provider_id, + operation_id, + account_epoch, + profile_epoch: window.profile_epoch, + session_kind, + target_game, + }; + let binding = ConfigurationBinding { + profile_id, + session_id: session_id.to_owned(), + window_id: window.window_id.clone(), + }; + let (result_sender, result_receiver) = oneshot::channel(); + state.operations.insert( + (session_id.to_owned(), context.operation_id.clone()), + Operation { + context: context.clone(), + kind: ProviderOperation::ConfigurationClose, + permissions: [cap::CONFIGURE].into(), + catalog: CatalogTransfer::default(), + requested_achievements: BTreeSet::new(), + result: result_sender, + identity_revision, + secret_written: false, + secret_deleted: false, + identity_accepted: false, + settings: None, + configuration: Some(binding), + configuration_cleanup: true, + }, + ); + (context, commands, result_receiver) + }; + let operation_id = context.operation_id.clone(); + if commands + .try_send(Ok(ProviderCommand { + context: Some(context), + operation: ProviderOperation::ConfigurationClose as i32, + target_operation_id: window.window_id, + settings: None, + runtime_session_result: None, + runtime_session_context_result: None, + achievements: None, + })) + .is_err() + { + lock(&self.state) + .operations + .remove(&(session_id.to_owned(), operation_id)); + return false; + } + match tokio::time::timeout(Duration::from_secs(5), result_receiver).await { + Ok(Ok(Ok(completion))) => completion + .result + .configuration + .is_some_and(|result| result.accepted), + _ => { + lock(&self.state) + .operations + .remove(&(session_id.to_owned(), operation_id)); + false + } + } } pub async fn execute_achievements( @@ -778,6 +2974,8 @@ impl ProviderApi { ProviderOperation::ReadAchievements, None, Some(request), + None, + String::new(), ) .await } @@ -791,6 +2989,8 @@ impl ProviderApi { request.operation(), Some(request), None, + None, + String::new(), ) .await } @@ -807,7 +3007,11 @@ impl ProviderApi { .find(|(_, s)| s.provider.registration.provider_id == provider && s.commands.is_some()) .ok_or_else(|| Status::unavailable("provider process unavailable"))?; if !session.grants.contains(cap::SETTINGS) { - return Err(Status::permission_denied("settings permission not granted")); + return Err(denial( + DenialReason::NotGranted, + cap::SETTINGS, + session.grant_revision, + )); } Ok(settings::Context { provider_id: provider.into(), @@ -820,42 +3024,60 @@ impl ProviderApi { pub fn settings_authorized(&self, provider: &str) -> bool { lock(&self.state).providers.get(provider).is_some_and(|p| { - p.registration - .capabilities + p.capabilities + .read() + .unwrap_or_else(std::sync::PoisonError::into_inner) .iter() .any(|c| c == cap::SETTINGS) }) } + /// Report configuration declarations separately from the permissions granted to the live + /// session. UI must never infer authorization from package declarations alone. + pub fn configuration_modes(&self, provider: &str) -> Result { + let state = lock(&self.state); + let registration = state + .providers + .get(provider) + .ok_or_else(|| Status::not_found("provider not registered"))?; + let external_declared = registration + .registration + .capabilities + .contains(&cap::CONFIGURE.into()); + let declarative_declared = registration + .registration + .capabilities + .contains(&cap::SETTINGS.into()); + let session = state.sessions.values().find(|session| { + session.provider.registration.provider_id == provider && session.commands.is_some() + }); + let external_authorized = external_declared + && session.is_some_and(|session| session.grants.contains(cap::CONFIGURE)); + let declarative_authorized = declarative_declared + && session.is_some_and(|session| session.grants.contains(cap::SETTINGS)); + Ok(ConfigurationModes { + external_declared, + external_authorized, + declarative_declared, + declarative_authorized, + }) + } + /// Revocation affects this process session immediately. A later launch /// negotiates again from the trusted descriptor's approved permission set. pub async fn revoke_session_permission(&self, provider_id: &str, permission: &str) { - let provider = lock(&self.state).providers.get(provider_id).cloned(); - let Some(provider) = provider else { + if !cap::KNOWN.contains(&permission) { return; - }; - let _guard = provider.commits.lock().await; - let mut state = lock(&self.state); - for session in state - .sessions - .values_mut() - .filter(|s| s.provider.registration.provider_id == provider_id) - { - session.grants.remove(permission); } - let obsolete: Vec<_> = state - .operations + let sessions: Vec<_> = lock(&self.state) + .sessions .iter() - .filter(|(_, op)| { - op.context.provider_id == provider_id && op.permissions.contains(permission) - }) - .map(|(key, _)| key.clone()) + .filter(|(_, session)| session.provider.registration.provider_id == provider_id) + .map(|(id, session)| (id.clone(), session.grants.clone())) .collect(); - for key in obsolete { - if let Some(op) = state.operations.remove(&key) { - let _ = op.result.send(Err(Status::permission_denied( - "provider permission revoked", - ))); + for (session_id, mut grants) in sessions { + if grants.remove(permission) { + let _ = self.replace_session_grants(&session_id, grants).await; } } } @@ -895,9 +3117,12 @@ impl ProviderApi { kind: ProviderOperation, settings: Option, achievements: Option, + configuration: Option, + target_operation_id: String, ) -> Result { if is_settings(kind) != settings.is_some() || (kind == ProviderOperation::ReadAchievements) != achievements.is_some() + || is_configuration(kind) != configuration.is_some() { return Err(Status::invalid_argument("missing operation scope")); } @@ -929,6 +3154,8 @@ impl ProviderApi { let provider = session.provider.clone(); let credential = session.credential; let grants = session.grants.clone(); + let session_kind = session.kind; + let target_game = session.target_game.clone(); let required = match kind { ProviderOperation::Discover => cap::DISCOVERY, ProviderOperation::SyncCatalog => cap::CATALOG, @@ -936,6 +3163,9 @@ impl ProviderApi { ProviderOperation::SettingsDescribeRead | ProviderOperation::SettingsSubmit | ProviderOperation::SettingsCancel => cap::SETTINGS, + ProviderOperation::ConfigurationOpen + | ProviderOperation::ConfigurationFocus + | ProviderOperation::ConfigurationClose => cap::CONFIGURE, ProviderOperation::ReadAchievements => cap::ACHIEVEMENTS, ProviderOperation::SignIn | ProviderOperation::FocusSignIn @@ -944,9 +3174,11 @@ impl ProviderApi { _ => cap::CONTEXT, }; if !grants.contains(required) { - return Err(Status::unimplemented( - "required provider capability is unavailable", - )); + let event = denial_event(session, required, DenialReason::NotGranted); + let revision = event.grant_revision; + drop(state); + self.record_authorization_denial(event); + return Err(denial(DenialReason::NotGranted, required, revision)); } let login_pending = state.operations.iter().any(|((id, _), operation)| { id == &session_id && operation.kind == ProviderOperation::SignIn @@ -1014,18 +3246,38 @@ impl ProviderApi { } let (account_epoch, profile_epoch) = epoch(&provider); let context = ServiceContext { - session_id, + session_id: session_id.clone(), session_credential: credential.to_vec(), provider_id: provider_id.into(), operation_id: super::random_session_id()?, account_epoch, profile_epoch, + session_kind, + target_game, }; if let Some(request) = &settings && !request.matches_service(&context, &provider.registration.plugin_id) { return Err(Status::failed_precondition("settings form expired")); } + if let Some(binding) = &configuration + && (!matches!( + provider.registration.origin, + RegistrationOrigin::ThirdParty { .. } + ) || binding.profile_id + != provider + .profiles + .as_ref() + .and_then(|profiles| profiles.current()) + .map(|profile| profile.profile_id().to_owned()) + .unwrap_or_default() + || binding.session_id != session_id + || binding.window_id != target_operation_id) + { + return Err(Status::failed_precondition( + "plugin configuration profile changed", + )); + } let (complete, result) = oneshot::channel(); let permissions = permission_set(kind) .into_iter() @@ -1050,6 +3302,8 @@ impl ProviderApi { secret_deleted: false, identity_accepted: false, settings: settings.clone(), + configuration: configuration.clone(), + configuration_cleanup: false, }, ); (context, commands, result) @@ -1060,8 +3314,10 @@ impl ProviderApi { .try_send(Ok(ProviderCommand { context: Some(context.clone()), operation: kind as i32, - target_operation_id: String::new(), + target_operation_id, settings: settings.map(Into::into), + runtime_session_result: None, + runtime_session_context_result: None, achievements: achievements.map(Into::into), })) .is_err() @@ -1086,13 +3342,26 @@ impl ProviderApi { let context = event .context .ok_or_else(|| Status::unauthenticated("provider context is required"))?; + if let Some(provider_event::Event::RuntimeSession(report)) = event.event.as_ref() { + return self.runtime_session_event(context, report.clone()).await; + } + if let Some(provider_event::Event::RuntimeSessionContext(request)) = event.event.as_ref() { + return self + .runtime_session_context_event(context, request.clone()) + .await; + } let permission = match event.event.as_ref() { Some(provider_event::Event::AccountStatus(_)) => cap::ACCOUNT_PUBLISH, Some(provider_event::Event::CatalogChunk(_)) => cap::CATALOG, Some(provider_event::Event::Result(result)) if result.settings.is_some() => { cap::SETTINGS } + Some(provider_event::Event::Result(result)) if result.configuration.is_some() => { + cap::CONFIGURE + } Some(provider_event::Event::Result(_)) => cap::CONTEXT, + Some(provider_event::Event::RuntimeSession(_)) => cap::GAME_SESSIONS_REPORT, + Some(provider_event::Event::RuntimeSessionContext(_)) => cap::GAME_SESSIONS_REPORT, _ => return Err(Status::invalid_argument("invalid provider event")), }; let provider = self.authorize(&context, permission)?; @@ -1104,18 +3373,16 @@ impl ProviderApi { { provider_event::Event::AccountStatus(status) => { if status.state == AccountConnection::NotConnected as i32 { - let state = lock(&self.state); - if state + // The temporary lock ends with this statement; the denial locks state again. + let undeleted_sign_out = lock(&self.state) .operations .get(&(context.session_id.clone(), context.operation_id.clone())) .is_some_and(|operation| { operation.kind == ProviderOperation::SignOut && !operation.secret_deleted - }) - { - return Err(Status::permission_denied( - "sign-out requires successful credential deletion", - )); + }); + if undeleted_sign_out { + return Err(self.scope_denial(&context, cap::ACCOUNT_PUBLISH).unwrap()); } } let status = status @@ -1141,6 +3408,8 @@ impl ProviderApi { .push(chunk) .map_err(|_| Status::invalid_argument("invalid catalog transfer"))?; } + provider_event::Event::RuntimeSession(_) => unreachable!("handled above"), + provider_event::Event::RuntimeSessionContext(_) => unreachable!("handled above"), provider_event::Event::Result(result) => { for (present, permission) in [ (result.status.is_some(), cap::ACCOUNT_PUBLISH), @@ -1167,18 +3436,35 @@ impl ProviderApi { }) { return Err(Status::invalid_argument("invalid login outcome")); } - let operation_kind = lock(&self.state) + let (operation_kind, configuration_binding) = lock(&self.state) .operations .get(&(context.session_id.clone(), context.operation_id.clone())) - .map(|operation| operation.kind) + .map(|operation| (operation.kind, operation.configuration.clone())) .ok_or_else(|| Status::failed_precondition("operation already completed"))?; + match (&configuration_binding, &result.configuration) { + (Some(expected), Some(actual)) + if actual.session_id == context.session_id + && expected.session_id == context.session_id + && (actual.profile_id.is_empty() + || actual.profile_id == expected.profile_id) + && actual.window_id == expected.window_id => {} + (None, None) if !is_configuration(operation_kind) => {} + _ => { + return Err(Status::invalid_argument( + "invalid plugin configuration acknowledgement", + )); + } + } if (result.login_outcome.is_some() && operation_kind != ProviderOperation::SignIn) || (result.focused.is_some() && operation_kind != ProviderOperation::FocusSignIn) - || (!result.achievements.is_empty() - && operation_kind != ProviderOperation::ReadAchievements) { - return Err(Status::permission_denied("invalid account result scope")); + return Err(self.scope_denial(&context, cap::LOGIN).unwrap()); + } + if !result.achievements.is_empty() + && operation_kind != ProviderOperation::ReadAchievements + { + return Err(self.scope_denial(&context, cap::ACHIEVEMENTS).unwrap()); } if result.counters.len() > 50_000 || result.counters.iter().any(|c| { @@ -1194,7 +3480,7 @@ impl ProviderApi { && (discovery.provider_id != context.provider_id || discovery.records.len() > 50_000) { - return Err(Status::permission_denied("wrong discovery provider")); + return Err(self.scope_denial(&context, cap::DISCOVERY).unwrap()); } let status: Option = result .status @@ -1238,18 +3524,18 @@ impl ProviderApi { .as_ref() .is_some_and(|s| s.state == AccountConnection::NotConnected as i32)) { - let _ = operation.result.send(Err(Status::permission_denied( - "sign-out requires successful credential deletion", - ))); - return Err(Status::permission_denied( - "sign-out requires successful credential deletion", - )); + let error = self + .scope_denial(&context, cap::SECRET_DELETE) + .unwrap_or_else(|| Status::unauthenticated("unknown session")); + let _ = operation.result.send(Err(error.clone())); + return Err(error); } if result.signed_out && operation.kind != ProviderOperation::SignOut { - let _ = operation - .result - .send(Err(Status::permission_denied("invalid account transition"))); - return Err(Status::permission_denied("invalid account transition")); + let error = self + .scope_denial(&context, cap::ACCOUNT_PUBLISH) + .unwrap_or_else(|| Status::unauthenticated("unknown session")); + let _ = operation.result.send(Err(error.clone())); + return Err(error); } let catalog = match operation .catalog @@ -1310,6 +3596,8 @@ impl ProviderApi { operation: ProviderOperation::Acknowledge as i32, target_operation_id: String::new(), settings: None, + runtime_session_result: None, + runtime_session_context_result: None, achievements: None, })); } @@ -1346,11 +3634,36 @@ impl provider_host_server::ProviderHost for ProviderApi { .sessions .get_mut(&context.session_id) .ok_or_else(|| Status::unauthenticated("unknown session"))?; - if !super::constant_time_eq(&session.credential, &context.session_credential) - || session.provider.registration.provider_id != context.provider_id - || session.commands.is_some() + if !super::constant_time_eq(&session.credential, &context.session_credential) { + return Err(Status::unauthenticated("invalid stream credential")); + } + if context_provider_id(&session.provider.registration) != context.provider_id { + let permission = cap::CONTEXT; + let detail = denial( + DenialReason::ScopeDenied, + permission, + session.grant_revision, + ); + let event = denial_event(session, permission, DenialReason::ScopeDenied); + drop(state); + self.record_authorization_denial(event); + return Err(detail); + } + if session.revoked + || (session.kind == SessionKind::Extension as i32 + && (context.session_kind != session.kind + || context.target_game != session.target_game + || session.extension.as_ref().is_some_and(|extension| { + !self.profiles.is_current(extension.target.profile_epoch) + || !extension.target.is_current() + }))) { - return Err(Status::permission_denied("invalid stream session")); + return Err(Status::permission_denied("invalid extension Ready context")); + } + if session.commands.is_some() { + return Err(Status::failed_precondition( + "provider stream already connected", + )); } session.commands = Some(tx.clone()); if let Some(ready) = session.ready.take() { @@ -1367,7 +3680,7 @@ impl provider_host_server::ProviderHost for ProviderApi { .is_none_or(|context| context.session_id != session_id) { let _ = tx - .send(Err(Status::permission_denied( + .send(Err(Status::unauthenticated( "event belongs to another stream session", ))) .await; @@ -1380,7 +3693,9 @@ impl provider_host_server::ProviderHost for ProviderApi { if error.code() == tonic::Code::FailedPrecondition { continue; } - api.fail_operation(event_context.as_ref(), &error); + if let Some(context) = event_context.as_ref() { + api.reject_stream_operation(context, error.clone()); + } let _ = tx.send(Err(error)).await; break; } @@ -1419,18 +3734,20 @@ impl provider_host_server::ProviderHost for ProviderApi { }; let (lease, services) = self.lease(request.context, permission)?; if matches!(action, account_request::Action::Clear(true)) { - let state = lock(&self.state); - let operation = state - .operations - .get(&( - lease.context.session_id.clone(), - lease.context.operation_id.clone(), - )) - .ok_or_else(|| Status::failed_precondition("stale account operation"))?; - if operation.kind != ProviderOperation::SignOut || !operation.secret_deleted { - return Err(Status::permission_denied( - "account removal requires credential deletion", - )); + // Release the state lock before denying: recording the denial locks it again. + let deleted_on_sign_out = { + let state = lock(&self.state); + let operation = state + .operations + .get(&( + lease.context.session_id.clone(), + lease.context.operation_id.clone(), + )) + .ok_or_else(|| Status::failed_precondition("stale account operation"))?; + operation.kind == ProviderOperation::SignOut && operation.secret_deleted + }; + if !deleted_on_sign_out { + return Err(lease.deny_scope_for(cap::SECRET_DELETE)); } } Ok(Response::new(services.account(lease, action).await?)) @@ -1441,14 +3758,6 @@ impl provider_host_server::ProviderHost for ProviderApi { request: Request, ) -> Result, Status> { let request = request.into_inner(); - if request.key != "session" - || request - .value - .as_ref() - .is_some_and(|v| v.is_empty() || v.len() > 32 * 1024) - { - return Err(Status::permission_denied("secret slot is not authorized")); - } let operation = SecretOperation::try_from(request.operation) .map_err(|_| Status::invalid_argument("invalid secret action"))?; if (operation == SecretOperation::Write) != request.value.is_some() { @@ -1461,6 +3770,21 @@ impl provider_host_server::ProviderHost for ProviderApi { _ => return Err(Status::invalid_argument("missing secret action")), }; let (lease, services) = self.lease(request.context.clone(), permission)?; + if request.key != "session" { + let namespace = lease + .namespace() + .map_err(|_| lease.deny_scope_for(permission))?; + namespace + .secret_slot(&request.key) + .map_err(|_| Status::invalid_argument("invalid logical secret key"))?; + } + if request + .value + .as_ref() + .is_some_and(|v| v.is_empty() || v.len() > 32 * 1024) + { + return Err(Status::invalid_argument("invalid secret value")); + } Ok(Response::new(services.secret(lease, request).await?)) } diff --git a/crates/app/src/plugin_host/provider/permissions_tests.rs b/crates/app/src/plugin_host/provider/permissions_tests.rs index 735442d42..ca4a2ad6d 100644 --- a/crates/app/src/plugin_host/provider/permissions_tests.rs +++ b/crates/app/src/plugin_host/provider/permissions_tests.rs @@ -1,6 +1,7 @@ //! Adversarial authorization cases exercise public RPC/event handlers. Adapter //! entry counters ensure rejection happens before host I/O or publication. use super::*; +use gamenode_plugin_protocol::prost::Message; use provider_host_server::ProviderHost; struct CountingServices { @@ -62,10 +63,15 @@ impl Harness { }); for (provider, plugin) in [("fixture", "fixture.plugin"), ("other", "other.plugin")] { api.register(Registration { + declared_developer: "Fixture developer".into(), + package_digest: Vec::new(), provider_id: provider.into(), plugin_id: plugin.into(), + kind: super::RegistrationKind::Provider, + origin: RegistrationOrigin::Official, capabilities: grants.iter().map(|v| (*v).into()).collect(), shared_catalog: false, + playtime: Default::default(), services: guarded.clone(), }) .unwrap(); @@ -108,6 +114,226 @@ impl Harness { } } +#[tokio::test] +async fn control_plane_requires_the_session_credential_and_streams_grant_revisions() { + let (h, _) = Harness::with_grants(&[cap::CONTEXT, cap::DISCOVERY]).await; + let context = h.client.host.context().clone(); + let api = super::super::super::PluginApi { + providers: h.api.clone(), + shared_policies: Default::default(), + data_broker: Default::default(), + shared_pool: Default::default(), + library: Default::default(), + storage: Default::default(), + files: Default::default(), + network: Default::default(), + notifications: Default::default(), + jobs: Default::default(), + leases: Default::default(), + processes: None, + intents: Default::default(), + saves: Default::default(), + fingerprints: Default::default(), + }; + + // The control plane is authenticated independently of data permissions, + // but never accepts an unknown session or another credential. + let denied = super::super::super::plugin_host_server::PluginHost::describe_api( + &api, + Request::new(DescribeApiRequest { + session_id: context.session_id.clone(), + session_credential: vec![0; 32], + }), + ) + .await + .unwrap_err(); + assert_eq!(denied.code(), tonic::Code::Unauthenticated); + let unknown = super::super::super::plugin_host_server::PluginHost::get_permissions( + &api, + Request::new(GetPermissionsRequest { + session_id: "another-session".into(), + session_credential: context.session_credential.clone(), + }), + ) + .await + .unwrap_err(); + assert_eq!(unknown.code(), tonic::Code::Unauthenticated); + + let metadata = h.client.host.describe_api().await.unwrap(); + assert_eq!((metadata.api_major, metadata.api_minor), (1, 6)); + let permissions = h.client.host.get_permissions().await.unwrap(); + assert_eq!(permissions.revision, 1); + assert!( + permissions + .grants + .iter() + .any(|grant| { grant.permission_id == cap::DISCOVERY && grant.state == "granted" }) + ); + assert!( + permissions + .grants + .iter() + .any(|grant| { grant.permission_id == cap::SECRET_READ && grant.state == "denied" }) + ); + + let mut changes = h + .client + .host + .watch_permission_changes(permissions.revision) + .await + .unwrap(); + let next_revision = h + .api + .replace_session_grants(&context.session_id, [cap::CONTEXT.to_owned()].into()) + .await + .unwrap(); + assert_eq!(next_revision, 2); + let change = tokio::time::timeout(Duration::from_secs(1), changes.message()) + .await + .unwrap() + .unwrap() + .unwrap(); + assert_eq!(change.revision, 2); + assert!(change.revoked); + assert!( + change + .grants + .iter() + .any(|grant| { grant.permission_id == cap::DISCOVERY && grant.state == "denied" }) + ); +} + +#[tokio::test] +async fn queued_storage_is_fenced_when_revocation_wins_commit_lock() { + let (h, _) = Harness::with_grants(&[cap::CONTEXT]).await; + let context = h.client.host.context().clone(); + let provider = lock(&h.api.state).providers.get("fixture").unwrap().clone(); + let (operation_result, _) = oneshot::channel(); + lock(&h.api.state).operations.insert( + (context.session_id.clone(), context.operation_id.clone()), + Operation { + context: context.clone(), + kind: ProviderOperation::Initialize, + permissions: [cap::CONTEXT].into(), + catalog: CatalogTransfer::default(), + result: operation_result, + identity_revision: 0, + secret_written: false, + secret_deleted: false, + identity_accepted: false, + settings: None, + configuration: None, + configuration_cleanup: false, + requested_achievements: Default::default(), + }, + ); + let held = provider.commits.clone().lock_owned().await; + + let revoke_api = h.api.clone(); + let session_id = context.session_id.clone(); + let (revoke_started, revoke_ready) = tokio::sync::oneshot::channel(); + let mut revoke = tokio::spawn(async move { + revoke_started.send(()).unwrap(); + revoke_api + .replace_session_grants(&session_id, BTreeSet::new()) + .await + }); + revoke_ready.await.unwrap(); + assert!( + tokio::time::timeout(Duration::from_millis(10), &mut revoke) + .await + .is_err() + ); + + let (storage_started, storage_ready) = tokio::sync::oneshot::channel(); + let committed = Arc::new(AtomicUsize::new(0)); + let committed_by_work = committed.clone(); + let lease = Lease { + api: h.api.clone(), + context, + permission: cap::CONTEXT, + }; + let storage = tokio::spawn(async move { + storage_started.send(()).unwrap(); + lease + .storage(move || { + committed_by_work.fetch_add(1, Ordering::SeqCst); + Ok(()) + }) + .await + }); + storage_ready.await.unwrap(); + tokio::task::yield_now().await; + drop(held); + + assert_eq!(revoke.await.unwrap().unwrap(), 2); + let status = storage.await.unwrap().unwrap_err(); + assert!(matches!( + status.code(), + tonic::Code::PermissionDenied | tonic::Code::FailedPrecondition + )); + assert_eq!(committed.load(Ordering::SeqCst), 0); +} + +#[tokio::test] +async fn revocation_cancels_pending_operations_with_revisioned_denial() { + let (h, _) = Harness::with_grants(&[cap::CONTEXT, cap::DISCOVERY]).await; + let context = h.client.host.context().clone(); + let api = h.api.clone(); + let pending = + tokio::spawn(async move { api.execute("fixture", ProviderOperation::Discover).await }); + + tokio::time::timeout(Duration::from_secs(1), async { + loop { + if lock(&h.api.state) + .operations + .iter() + .any(|((session_id, _), operation)| { + session_id == &context.session_id + && operation.kind == ProviderOperation::Discover + }) + { + break; + } + tokio::task::yield_now().await; + } + }) + .await + .unwrap(); + + h.api + .replace_session_grants(&context.session_id, [cap::CONTEXT.to_owned()].into()) + .await + .unwrap(); + let status = pending.await.unwrap().unwrap_err(); + assert_eq!(status.code(), tonic::Code::PermissionDenied); + let detail = DenialDetail::decode(status.details()).unwrap(); + assert_eq!(detail.reason, DenialReason::Revoked as i32); + assert_eq!(detail.permission_id, cap::DISCOVERY); + assert_eq!(detail.grant_revision, 2); +} + +#[tokio::test] +async fn control_plane_denials_include_decodable_permission_details() { + use gamenode_plugin_protocol::prost::Message; + let (h, _) = Harness::with_grants(&[cap::CONTEXT]).await; + let context = h.client.host.context().clone(); + let status = ProviderHost::account( + &h.api, + Request::new(AccountRequest { + context: Some(context), + action: Some(account_request::Action::Read(true)), + }), + ) + .await + .unwrap_err(); + assert_eq!(status.code(), tonic::Code::PermissionDenied); + let detail = DenialDetail::decode(status.details()).unwrap(); + assert_eq!(detail.reason, DenialReason::NotGranted as i32); + assert_eq!(detail.permission_id, cap::ACCOUNT_READ); + assert_eq!(detail.grant_revision, 1); +} + #[derive(Clone, Copy, Debug)] enum Access { Context, @@ -334,10 +560,12 @@ async fn every_missing_host_grant_is_rejected_before_adapter_or_domain_effects() .copied() .filter(|v| *v != case.capability()) .collect(); - // Settings-only descriptors can legitimately omit context. Include its - // independent feature solely to permit negotiating that negative case. + // Provider sessions need context to negotiate. For the negative context + // case, revoke it after opening the session so the RPC itself exercises + // the missing-grant check rather than failing during ClientSession::open. if matches!(case, Access::Context) { grants.push(cap::SETTINGS); + grants.push(cap::CONTEXT); } let (mut h, entered) = Harness::with_grants(&grants).await; if case.required_to_dispatch() { @@ -358,7 +586,10 @@ async fn every_missing_host_grant_is_rejected_before_adapter_or_domain_effects() .await .unwrap_err() }; - assert_eq!(error.code(), tonic::Code::Unimplemented, "{case:?}"); + assert_eq!(error.code(), tonic::Code::PermissionDenied, "{case:?}"); + let detail = DenialDetail::decode(error.details()).unwrap(); + assert_eq!(detail.reason, DenialReason::NotGranted as i32, "{case:?}"); + assert_eq!(detail.permission_id, case.capability(), "{case:?}"); assert!( tokio::time::timeout(Duration::from_millis(10), h.client.commands.message()) .await @@ -373,6 +604,12 @@ async fn every_missing_host_grant_is_rejected_before_adapter_or_domain_effects() }; let pending = h.execute(operation); let context = h.next(operation).await.context().clone(); + if matches!(case, Access::Context) { + h.api + .replace_session_grants(&context.session_id, [cap::SETTINGS.to_owned()].into()) + .await + .unwrap(); + } assert_eq!( case.attempt(&h.api, context).await.unwrap_err().code(), tonic::Code::PermissionDenied, @@ -404,6 +641,12 @@ async fn every_service_rejects_cross_provider_credentials_and_obsolete_sessions( tonic::Code::PermissionDenied, "{case:?}: provider" ); + let audit = h.api.authorization_audit(); + let denial = audit.last().expect("authorization denial is audited"); + assert_eq!(denial.plugin_id, "fixture.plugin"); + assert_eq!(denial.provider_id, "fixture"); + assert_eq!(denial.reason, DenialReason::ScopeDenied); + assert!(!format!("{denial:?}").contains("session_credential")); let other = h.api.begin_launch("other").unwrap(); let mut cross_plugin = context.clone(); cross_plugin.session_credential = (0..other.credential.len()) @@ -440,6 +683,35 @@ async fn every_service_rejects_cross_provider_credentials_and_obsolete_sessions( } } +#[test] +fn authorization_audit_is_bounded_and_contains_no_request_payload_fields() { + let api = ProviderApi::default(); + for sequence in 0..=AUTHORIZATION_AUDIT_LIMIT { + api.record_authorization_denial(AuthorizationAuditEvent { + plugin_id: format!("fixture.plugin.{sequence}"), + provider_id: "fixture-provider".into(), + permission_id: "secrets.read".into(), + reason: DenialReason::NotGranted, + grant_revision: sequence as u64, + }); + } + + let events = api.authorization_audit(); + assert_eq!(events.len(), AUTHORIZATION_AUDIT_LIMIT); + assert_eq!(events.first().unwrap().plugin_id, "fixture.plugin.1"); + assert_eq!(events.last().unwrap().plugin_id, "fixture.plugin.256"); + + let rendered = format!("{events:?}"); + for sensitive in [ + "session_credential", + "cookie-value", + "secret-value", + "raw-request", + ] { + assert!(!rendered.contains(sensitive)); + } +} + #[tokio::test] async fn shared_catalog_data_requires_declared_shared_access() { let mut h = Harness::new().await; diff --git a/crates/app/src/plugin_host/provider/profile_tests.rs b/crates/app/src/plugin_host/provider/profile_tests.rs new file mode 100644 index 000000000..4bad2bddf --- /dev/null +++ b/crates/app/src/plugin_host/provider/profile_tests.rs @@ -0,0 +1,259 @@ +//! Third-party providers run inside the active GameNode account profile; official providers +//! are bundled with GameNode and are not bound to it. +use super::*; +use crate::plugin_host::namespace::OwnerKind; +use crate::plugin_host::profile::ProfileTransition; + +fn third_party_registration(provider_id: &str) -> Registration { + Registration { + declared_developer: "Fixture developer".into(), + package_digest: Vec::new(), + provider_id: provider_id.into(), + plugin_id: format!("{provider_id}.plugin"), + kind: super::RegistrationKind::Provider, + origin: RegistrationOrigin::ThirdParty { + publisher_fingerprint: "cd".repeat(32), + }, + capabilities: vec![cap::CONTEXT.into()], + shared_catalog: false, + playtime: Default::default(), + services: Arc::new(Services::default()), + } +} + +fn official_registration(provider_id: &str) -> Registration { + Registration { + origin: RegistrationOrigin::Official, + ..third_party_registration(provider_id) + } +} + +fn unavailable(result: Result) -> bool { + result.err().map(|status| status.code()) == Some(tonic::Code::Unavailable) +} + +async fn wait_until_disconnected(api: &ProviderApi, provider_id: &str) { + tokio::time::timeout(Duration::from_secs(2), async { + while api.connected(provider_id) { + tokio::time::sleep(Duration::from_millis(5)).await; + } + }) + .await + .expect("third-party session was not fenced"); +} + +#[tokio::test] +async fn third_party_processes_start_only_inside_an_account_profile() { + let api = ProviderApi::default(); + api.register(third_party_registration("community")).unwrap(); + api.register(official_registration("bundled")).unwrap(); + + assert!(unavailable(api.begin_launch("community"))); + assert!(api.begin_launch("bundled").is_ok()); + + // The cached account of an unverified restore is enough to run. + api.profiles().update(Some("account-a"), false); + assert!(api.begin_launch("community").is_ok()); + + api.profiles().update(None, false); + assert!(unavailable(api.begin_launch("community"))); +} + +#[test] +fn official_providers_keep_host_launch_accounting_outside_plugin_runtime_reports() { + let api = ProviderApi::default(); + let registration = official_registration("bundled"); + assert_eq!(registration.playtime, Default::default()); + api.register(registration).unwrap(); + + // Bundled providers continue through the existing host-managed provider launch path. + assert!(api.begin_launch("bundled").is_ok()); + + // Plugin-reported runtime accounting is an extension-only feature and cannot change the + // official provider's existing accounting policy. + let error = api + .begin_extension_launch( + "bundled", + 0, + gamenode_plugin_protocol::proto::TargetGameContext { + game_id: "42".into(), + installation_id: "steam:123".into(), + profile_id: "account-a".into(), + revision: "revision-1".into(), + }, + ) + .err() + .expect("official providers cannot open extension reporting sessions"); + assert_eq!(error.code(), tonic::Code::PermissionDenied); +} + +#[test] +fn runtime_reporting_requires_a_compatible_signed_playtime_declaration() { + let api = ProviderApi::default(); + let mut registration = third_party_registration("community"); + registration + .capabilities + .push(cap::GAME_SESSIONS_REPORT.into()); + + let error = api + .register(registration) + .expect_err("default-disabled packages cannot report runtime sessions"); + assert_eq!(error.code(), tonic::Code::InvalidArgument); + + let mut application_open = third_party_registration("community"); + application_open + .capabilities + .push(cap::GAME_SESSIONS_REPORT.into()); + let application_open_policy = crate::plugin_host::package::PlaytimeCapabilities { + identifies_gameplay: true, + identifies_pauses: false, + without_pause_detection: + crate::plugin_host::package::PlaytimeAccountingMode::ApplicationOpen, + }; + assert!( + application_open_policy.can_report_transition(RuntimeSessionTransition::Started as i32) + ); + assert!( + !application_open_policy.can_report_transition(RuntimeSessionTransition::Paused as i32) + ); + assert!( + !application_open_policy.can_report_transition(RuntimeSessionTransition::Resumed as i32) + ); + application_open.playtime = application_open_policy; + api.register(application_open) + .expect("signed application-open declaration supports reporting without pause detection"); +} + +#[test] +fn pending_third_party_launch_is_rejected_after_profile_changes() { + let api = ProviderApi::default(); + api.register(third_party_registration("community")).unwrap(); + api.profiles().update(Some("account-a"), true); + let epoch = api.profiles().current().unwrap().epoch(); + let launch = api + .begin_launch_for_profile("community", Some(epoch)) + .unwrap(); + let credential = launch + .credential + .as_bytes() + .as_chunks::<2>() + .0 + .iter() + .map(|pair| u8::from_str_radix(std::str::from_utf8(pair).unwrap(), 16).unwrap()) + .collect(); + + api.profiles().update(Some("account-b"), true); + let request = gamenode_plugin_protocol::proto::OpenSessionRequest { + session_credential: credential, + ..Default::default() + }; + let error = api.open_session(&request).unwrap_err(); + assert_eq!(error.code(), tonic::Code::FailedPrecondition); + assert!(!api.owns_launch(&request.session_credential)); +} + +#[tokio::test] +async fn a_different_verified_account_fences_third_party_sessions_and_namespaces() { + let mut h = Harness::third_party("account-a").await; + let operation = h.execute(ProviderOperation::Check); + let client = h.next(ProviderOperation::Check).await; + let (lease, _) = h + .api + .lease(Some(client.context().clone()), cap::CONTEXT) + .unwrap(); + let previous = lease.namespace().unwrap(); + let owner = previous.storage_owner(); + + assert_eq!( + h.api.profiles().update(Some("account-b"), true), + ProfileTransition::Fenced + ); + // Issued contexts of the previous profile are stale before the session is even stopped. + assert!(lease.check().is_err()); + assert!(lease.namespace().is_err()); + let next = h + .api + .profiles() + .resolver("fixture.plugin", &"ab".repeat(32), Some("fixture")) + .unwrap(); + assert!(!next.owns(&owner, OwnerKind::Storage)); + + h.api.fence_third_party_sessions().await; + assert!(!h.api.connected("fixture")); + assert!(operation.await.unwrap().is_err()); + assert!(h.api.begin_launch("fixture").is_ok()); +} + +#[tokio::test] +async fn sign_out_makes_third_party_services_unavailable_and_stops_sessions() { + let mut h = Harness::third_party("account-a").await; + h.api + .spawn_profile_fencing(&tokio::runtime::Handle::current()); + let operation = h.execute(ProviderOperation::Check); + let client = h.next(ProviderOperation::Check).await; + let context = client.context().clone(); + assert!(h.api.lease(Some(context.clone()), cap::CONTEXT).is_ok()); + + h.api.profiles().update(None, false); + // No profile is a missing session, not a permission denial. + assert!(unavailable(h.api.lease(Some(context), cap::CONTEXT))); + assert!(unavailable(h.api.begin_launch("fixture"))); + wait_until_disconnected(&h.api, "fixture").await; + assert!(operation.await.unwrap().is_err()); +} + +#[tokio::test] +async fn verifying_the_cached_account_keeps_third_party_sessions() { + let mut h = Harness::third_party("account-a").await; + h.api + .spawn_profile_fencing(&tokio::runtime::Handle::current()); + let operation = h.execute(ProviderOperation::Check); + let client = h.next(ProviderOperation::Check).await; + let (lease, _) = h + .api + .lease(Some(client.context().clone()), cap::CONTEXT) + .unwrap(); + + // The harness profile is verified; dropping back to unverified and verifying again is the + // same account, so contexts stay valid and nothing is fenced. + for verified in [false, true] { + assert_eq!( + h.api.profiles().update(Some("account-a"), verified), + ProfileTransition::Unchanged + ); + } + tokio::time::sleep(Duration::from_millis(50)).await; + assert!(h.api.connected("fixture")); + lease.check().unwrap(); + lease.namespace().unwrap(); + client.finish(completed()).await.unwrap(); + operation.await.unwrap().unwrap(); +} + +#[tokio::test] +async fn official_providers_ignore_account_profile_changes() { + let mut h = Harness::new().await; + h.api + .spawn_profile_fencing(&tokio::runtime::Handle::current()); + let operation = h.execute(ProviderOperation::Check); + let client = h.next(ProviderOperation::Check).await; + let (lease, _) = h + .api + .lease(Some(client.context().clone()), cap::CONTEXT) + .unwrap(); + // Official providers use trusted host adapters, not a third-party namespace. + assert_eq!( + lease.namespace().unwrap_err().code(), + tonic::Code::FailedPrecondition + ); + + h.api.profiles().update(Some("account-a"), true); + h.api.profiles().update(None, false); + h.api.fence_third_party_sessions().await; + tokio::time::sleep(Duration::from_millis(50)).await; + + assert!(h.api.connected("fixture")); + lease.check().unwrap(); + client.finish(completed()).await.unwrap(); + operation.await.unwrap().unwrap(); +} diff --git a/crates/app/src/plugin_host/provider/tests.rs b/crates/app/src/plugin_host/provider/tests.rs index d193a0f5f..5261af08c 100644 --- a/crates/app/src/plugin_host/provider/tests.rs +++ b/crates/app/src/plugin_host/provider/tests.rs @@ -1,15 +1,133 @@ use super::*; -use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; -use gamenode_plugin_sdk::{Error, HostClient, Launch, Session as ClientSession}; +use gamenode_plugin_protocol::prost::Message; +use gamenode_plugin_sdk::{Error, HostClient, Launch, Session as ClientSession, SessionOptions}; #[path = "permissions_tests.rs"] mod permissions_tests; +#[path = "profile_tests.rs"] +mod profile_tests; #[derive(Default)] struct Services { reads: AtomicUsize, publications: AtomicUsize, + status: Mutex>, +} + +#[tokio::test] +async fn configuration_modes_separate_declarations_from_active_authorization() { + let harness = Harness::third_party_config("account").await; + let available = harness.api.configuration_modes("fixture").unwrap(); + assert!(available.external_declared && available.external_authorized); + assert!(available.declarative_declared && available.declarative_authorized); + + harness + .api + .revoke_session_permission("fixture", cap::SETTINGS) + .await; + let revoked = harness.api.configuration_modes("fixture").unwrap(); + assert!(revoked.declarative_declared); + assert!(!revoked.declarative_authorized); + assert!(revoked.external_authorized); +} + +#[derive(Default)] +struct RuntimeSessionFixture { + reports: AtomicUsize, + disconnects: AtomicUsize, + delay_next_authorization: AtomicBool, + authorization_started: tokio::sync::Notify, + continue_authorization: tokio::sync::Notify, +} + +#[tonic::async_trait] +impl super::super::runtime::RuntimeSessionHandler for RuntimeSessionFixture { + async fn authorize_context( + &self, + _plugin_id: String, + _publisher_fingerprint: String, + _owner_key: String, + _profile_epoch: u64, + request: RuntimeSessionContextRequest, + ) -> Result { + if self.delay_next_authorization.swap(false, Ordering::Relaxed) { + self.authorization_started.notify_one(); + self.continue_authorization.notified().await; + } + if request.game_id == "85" { + return Err(Status::permission_denied("user declined runtime context")); + } + Ok(super::super::runtime::RuntimeContextRevision { + library_revision: 1, + binding_revision: 1, + }) + } + + async fn report( + &self, + _plugin_id: String, + _owner_key: String, + report: RuntimeSessionReport, + _context_authorized: bool, + _context_revision: Option, + _received_at: std::time::Instant, + ) -> RuntimeSessionResult { + self.reports.fetch_add(1, Ordering::Relaxed); + RuntimeSessionResult { + correlation_id: report.correlation_id, + outcome: RuntimeSessionOutcome::Accepted as i32, + host_session_id: "host-session-fixture".into(), + accepted_sequence: report.sequence, + accepted_at: report.observed_at, + ..Default::default() + } + } + + async fn disconnected(&self, _plugin_id: String) { + self.disconnects.fetch_add(1, Ordering::Relaxed); + } +} + +#[test] +fn runtime_context_requires_a_matching_fresh_active_report() { + let now = std::time::Instant::now(); + let active = super::RuntimeInstanceEvidence { + last_received_at: now - Duration::from_secs(29), + runtime_id: "runtime:snes".into(), + active: true, + }; + assert!(super::runtime_instance_has_fresh_active_report( + Some(&active), + "runtime:snes", + now + )); + assert!(!super::runtime_instance_has_fresh_active_report( + Some(&active), + "runtime:other", + now + )); + + let expired = super::RuntimeInstanceEvidence { + last_received_at: now - Duration::from_secs(31), + ..active.clone() + }; + assert!(!super::runtime_instance_has_fresh_active_report( + Some(&expired), + "runtime:snes", + now + )); + + let stopped = super::RuntimeInstanceEvidence { + active: false, + ..active + }; + assert!(!super::runtime_instance_has_fresh_active_report( + Some(&stopped), + "runtime:snes", + now + )); } #[tonic::async_trait] @@ -34,8 +152,9 @@ impl HostServices for Services { async fn actions(&self, _: Lease, _: ActionDeclaration) -> Result { Err(Status::unimplemented("fixture")) } - fn publish_status(&self, _: models::AccountStatus) { + fn publish_status(&self, status: models::AccountStatus) { self.publications.fetch_add(1, Ordering::Relaxed); + *lock(&self.status) = Some(status); } } @@ -67,12 +186,47 @@ impl Harness { } async fn build(extra: &[&'static str], shared_catalog: bool) -> Self { + Self::build_with(extra, shared_catalog, RegistrationOrigin::Official, None).await + } + + /// A harness for a third-party provider running inside the profile of `account`. + async fn third_party(account: &str) -> Self { + Self::build_with( + &[], + false, + RegistrationOrigin::ThirdParty { + publisher_fingerprint: "ab".repeat(32), + }, + Some(account), + ) + .await + } + + async fn third_party_config(account: &str) -> Self { + Self::build_with( + &[cap::CONFIGURE, cap::LIBRARY_READ], + false, + RegistrationOrigin::ThirdParty { + publisher_fingerprint: "ab".repeat(32), + }, + Some(account), + ) + .await + } + + async fn build_with( + extra: &[&'static str], + shared_catalog: bool, + origin: RegistrationOrigin, + account: Option<&str>, + ) -> Self { let temp = tempfile::tempdir().unwrap(); use std::os::unix::fs::PermissionsExt; std::fs::set_permissions(temp.path(), std::fs::Permissions::from_mode(0o700)).unwrap(); let endpoint = temp.path().join("plugins.sock"); let root = super::super::PluginApi::default(); let api = root.providers.clone(); + api.profiles().update(account, true); let services = Arc::new(Services::default()); let mut capabilities = vec![ cap::CONTEXT, @@ -85,10 +239,15 @@ impl Harness { ]; capabilities.extend_from_slice(extra); api.register(Registration { + declared_developer: "Fixture developer".into(), + package_digest: Vec::new(), provider_id: "fixture".into(), plugin_id: "fixture.plugin".into(), + kind: RegistrationKind::Provider, + origin, capabilities: capabilities.iter().map(|s| (*s).into()).collect(), shared_catalog, + playtime: Default::default(), services: services.clone(), }) .unwrap(); @@ -107,19 +266,39 @@ impl Harness { root, ) .unwrap(); - let client = ClientSession::open( - Launch { - endpoint, - credential, - operation_id: "launch".into(), - }, - "fixture.plugin", - "fixture", - "1.0", - &capabilities, - ) - .await - .unwrap(); + let plugin_launch = Launch { + endpoint, + credential, + operation_id: "launch".into(), + }; + let client = if capabilities.contains(&cap::CONFIGURE) { + ClientSession::open_with_options( + plugin_launch, + "fixture.plugin", + "fixture", + "1.0", + &capabilities, + SessionOptions { + min_api_major: 1, + min_api_minor: gamenode_plugin_protocol::API_MINOR, + max_api_major: 1, + max_api_minor: gamenode_plugin_protocol::API_MINOR, + ..Default::default() + }, + ) + .await + .unwrap() + } else { + ClientSession::open( + plugin_launch, + "fixture.plugin", + "fixture", + "1.0", + &capabilities, + ) + .await + .unwrap() + }; launch.ready.await.unwrap(); Self { api, @@ -151,6 +330,11 @@ impl Harness { } async fn next(&mut self, expected: ProviderOperation) -> HostClient { + let command = self.next_command(expected).await; + self.client.host.for_command(&command).unwrap() + } + + async fn next_command(&mut self, expected: ProviderOperation) -> ProviderCommand { loop { let command = tokio::time::timeout(Duration::from_secs(2), self.client.commands.message()) @@ -162,7 +346,7 @@ impl Harness { continue; } assert_eq!(command.operation, expected as i32); - return self.client.host.for_command(&command).unwrap(); + return command; } } } @@ -175,6 +359,295 @@ fn completed() -> OperationResult { } } +fn configuration_result(command: &ProviderCommand) -> OperationResult { + OperationResult { + disposition: OperationDisposition::Completed as i32, + configuration: Some(ConfigurationResult { + session_id: command.context.as_ref().unwrap().session_id.clone(), + profile_id: super::super::profile::profile_id_for_account("account"), + window_id: command.target_operation_id.clone(), + accepted: true, + failure: String::new(), + }), + ..Default::default() + } +} + +async fn open_configuration_window(h: &mut Harness) -> (String, HostClient) { + let api = h.api.clone(); + let opening = tokio::spawn(async move { + api.configure("fixture", ProviderOperation::ConfigurationOpen) + .await + }); + let command = h.next_command(ProviderOperation::ConfigurationOpen).await; + let window_id = command.target_operation_id.clone(); + let host = h.client.host.for_command(&command).unwrap(); + host.finish(configuration_result(&command)).await.unwrap(); + opening.await.unwrap().unwrap(); + (window_id, host) +} + +#[tokio::test] +async fn revoking_configure_requests_close_and_removes_its_grant() { + let mut h = Harness::third_party_config("account").await; + let (window_id, _) = open_configuration_window(&mut h).await; + + let api = h.api.clone(); + let revoking = tokio::spawn(async move { + api.revoke_session_permission("fixture", cap::CONFIGURE) + .await; + }); + let close = h.next_command(ProviderOperation::ConfigurationClose).await; + assert_eq!(close.target_operation_id, window_id); + h.client + .host + .for_command(&close) + .unwrap() + .finish(configuration_result(&close)) + .await + .unwrap(); + revoking.await.unwrap(); + + let permissions = h.client.host.get_permissions().await.unwrap(); + assert!( + !permissions + .grants + .iter() + .any(|grant| grant.permission_id == cap::CONFIGURE && grant.state == "granted") + ); + assert_eq!( + h.api + .configure("fixture", ProviderOperation::ConfigurationOpen) + .await + .unwrap_err() + .code(), + tonic::Code::PermissionDenied + ); +} + +#[tokio::test] +async fn switching_verified_accounts_closes_the_old_window_and_fences_its_context() { + let mut h = Harness::third_party_config("account").await; + let (window_id, old_host) = open_configuration_window(&mut h).await; + let old_resources = old_host.resources().unwrap(); + assert!(old_resources.library_snapshot("").await.is_ok()); + + h.api.profiles().update(Some("next-account"), true); + assert_eq!( + old_resources.library_snapshot("").await.unwrap_err().code(), + tonic::Code::FailedPrecondition + ); + let api = h.api.clone(); + let fencing = tokio::spawn(async move { api.fence_third_party_sessions().await }); + let close = h.next_command(ProviderOperation::ConfigurationClose).await; + assert_eq!(close.target_operation_id, window_id); + h.client + .host + .for_command(&close) + .unwrap() + .finish(configuration_result(&close)) + .await + .unwrap(); + fencing.await.unwrap(); + + assert!(matches!( + old_host.get_permissions().await, + Err(gamenode_plugin_sdk::DetailedError::Unauthenticated) + )); +} + +#[tokio::test] +async fn signing_out_closes_the_window_before_ending_the_plugin_session() { + let mut h = Harness::third_party_config("account").await; + let (window_id, _) = open_configuration_window(&mut h).await; + + h.api.profiles().update(None, false); + let api = h.api.clone(); + let fencing = tokio::spawn(async move { api.fence_third_party_sessions().await }); + let close = h.next_command(ProviderOperation::ConfigurationClose).await; + assert_eq!(close.target_operation_id, window_id); + h.client + .host + .for_command(&close) + .unwrap() + .finish(configuration_result(&close)) + .await + .unwrap(); + fencing.await.unwrap(); + assert!(!h.api.connected("fixture")); +} + +async fn assert_managed_stop_closes_window(stop_plugin: bool) { + let mut h = Harness::third_party_config("account").await; + let (window_id, old_host) = open_configuration_window(&mut h).await; + let processes = crate::plugin_host::process::ProviderProcesses::new( + h.api.clone(), + h._temp.path().join("unused-plugin-endpoint"), + vec![], + ) + .unwrap(); + let stop = tokio::spawn(async move { + if stop_plugin { + processes.stop_plugin("fixture.plugin").await; + } else { + processes.stop_provider("fixture").await; + } + }); + + let close = h.next_command(ProviderOperation::ConfigurationClose).await; + assert_eq!(close.target_operation_id, window_id); + h.client + .host + .for_command(&close) + .unwrap() + .finish(configuration_result(&close)) + .await + .unwrap(); + stop.await.unwrap(); + + h.api.disconnect("fixture").await; + assert!(matches!( + old_host.get_permissions().await, + Err(gamenode_plugin_sdk::DetailedError::Unauthenticated) + )); +} + +#[tokio::test] +async fn disabling_or_removing_through_provider_stop_closes_configuration_first() { + // Disable and removal use stop_provider; the persisted lifecycle then disconnects the + // session, so a stale plugin-side configuration context cannot keep using its grants. + assert_managed_stop_closes_window(false).await; +} + +#[tokio::test] +async fn update_through_plugin_stop_closes_configuration_first() { + // Staged update uses stop_plugin, which routes each registered provider through the same + // close-before-stop path before replacing the process configuration. + assert_managed_stop_closes_window(true).await; +} + +#[tokio::test] +async fn configure_reuses_one_host_handle_for_open_focus_and_close() { + let mut h = Harness::third_party_config("account").await; + + let api = h.api.clone(); + let opening = tokio::spawn(async move { + api.configure("fixture", ProviderOperation::ConfigurationOpen) + .await + }); + let open_command = h.next_command(ProviderOperation::ConfigurationOpen).await; + let handle = open_command.target_operation_id.clone(); + assert!(!handle.is_empty()); + h.client + .host + .for_command(&open_command) + .unwrap() + .finish(configuration_result(&open_command)) + .await + .unwrap(); + opening.await.unwrap().unwrap(); + + let api = h.api.clone(); + let focusing = tokio::spawn(async move { + api.configure("fixture", ProviderOperation::ConfigurationOpen) + .await + }); + let focus_command = h.next_command(ProviderOperation::ConfigurationFocus).await; + assert_eq!(focus_command.target_operation_id, handle); + h.client + .host + .for_command(&focus_command) + .unwrap() + .finish(configuration_result(&focus_command)) + .await + .unwrap(); + focusing.await.unwrap().unwrap(); + + let api = h.api.clone(); + let closing = tokio::spawn(async move { + api.configure("fixture", ProviderOperation::ConfigurationClose) + .await + }); + let close_command = h.next_command(ProviderOperation::ConfigurationClose).await; + assert_eq!(close_command.target_operation_id, handle); + h.client + .host + .for_command(&close_command) + .unwrap() + .finish(configuration_result(&close_command)) + .await + .unwrap(); + closing.await.unwrap().unwrap(); +} + +#[tokio::test] +async fn rejected_focus_clears_stale_handle_for_the_next_configure_open() { + let mut h = Harness::third_party_config("account").await; + let (old_handle, _) = open_configuration_window(&mut h).await; + + let api = h.api.clone(); + let focusing = tokio::spawn(async move { + api.configure("fixture", ProviderOperation::ConfigurationFocus) + .await + }); + let focus_command = h.next_command(ProviderOperation::ConfigurationFocus).await; + h.client + .host + .for_command(&focus_command) + .unwrap() + .finish(OperationResult { + disposition: OperationDisposition::Failed as i32, + configuration: Some(ConfigurationResult { + session_id: focus_command.context.as_ref().unwrap().session_id.clone(), + profile_id: super::super::profile::profile_id_for_account("account"), + window_id: old_handle.clone(), + accepted: false, + failure: "window-closed".into(), + }), + ..Default::default() + }) + .await + .unwrap(); + focusing.await.unwrap().unwrap(); + + let api = h.api.clone(); + let opening = tokio::spawn(async move { + api.configure("fixture", ProviderOperation::ConfigurationOpen) + .await + }); + let open_command = h.next_command(ProviderOperation::ConfigurationOpen).await; + assert_ne!(open_command.target_operation_id, old_handle); + h.client + .host + .for_command(&open_command) + .unwrap() + .finish(configuration_result(&open_command)) + .await + .unwrap(); + opening.await.unwrap().unwrap(); +} + +#[tokio::test] +async fn configuration_ack_timeout_does_not_block_provider_operations() { + let mut h = Harness::third_party_config("account").await; + tokio::time::pause(); + let api = h.api.clone(); + let opening = tokio::spawn(async move { + api.configure("fixture", ProviderOperation::ConfigurationOpen) + .await + }); + let _open_command = h.next_command(ProviderOperation::ConfigurationOpen).await; + + let discovery = h.execute(ProviderOperation::Discover); + let discovery_host = h.next(ProviderOperation::Discover).await; + discovery_host.finish(completed()).await.unwrap(); + discovery.await.unwrap().unwrap(); + + tokio::time::advance(Duration::from_secs(5)).await; + let error = opening.await.unwrap().unwrap_err(); + assert_eq!(error.code(), tonic::Code::DeadlineExceeded); +} + #[tokio::test] async fn repeated_sign_in_does_not_invalidate_the_pending_attempt() { let mut h = Harness::new().await; @@ -195,14 +668,18 @@ async fn repeated_sign_in_does_not_invalidate_the_pending_attempt() { } #[tokio::test] -async fn unsupported_operation_is_rejected_before_dispatch() { +async fn ungranted_operation_is_denied_before_dispatch() { let h = Harness::new().await; let error = h .api .execute("fixture", ProviderOperation::ReadCounter) .await .unwrap_err(); - assert_eq!(error.code(), tonic::Code::Unimplemented); + // Grant enforcement runs first: an operation outside the grant is denied, with details. + assert_eq!(error.code(), tonic::Code::PermissionDenied); + let detail = DenialDetail::decode(error.details()).unwrap(); + assert_eq!(detail.reason, DenialReason::NotGranted as i32); + assert_eq!(detail.permission_id, cap::COUNTER); assert_eq!(h.services.reads.load(Ordering::Relaxed), 0); } @@ -368,10 +845,50 @@ async fn mismatched_provider_result_is_rejected_without_publishing_state() { ..Default::default() }); client.finish(result).await.unwrap(); - assert!(operation.await.unwrap().is_err()); + let error = operation.await.unwrap().unwrap_err(); + assert_eq!(error.code(), tonic::Code::PermissionDenied); + let denial = DenialDetail::decode(error.details()).unwrap(); + assert_eq!(denial.reason, DenialReason::ScopeDenied as i32); + assert_eq!(denial.permission_id, cap::DISCOVERY); assert_eq!(h.services.publications.load(Ordering::Relaxed), 0); } +#[tokio::test] +async fn rejected_submission_preserves_previous_successful_account_facts() { + let mut h = Harness::new().await; + let first = h.execute(ProviderOperation::Check); + let client = h.next(ProviderOperation::Check).await; + let mut accepted = completed(); + accepted.status = Some(AccountStatus { + state: AccountConnection::Connected as i32, + account_id: Some("account-previous".into()), + storage: SecretStorage::PrivateFile as i32, + ..Default::default() + }); + client.finish(accepted).await.unwrap(); + first.await.unwrap().unwrap(); + + let second = h.execute(ProviderOperation::Check); + let client = h.next(ProviderOperation::Check).await; + let mut rejected = completed(); + rejected.discovery = Some(DiscoveryResult { + provider_id: "foreign-provider".into(), + records: vec![], + ..Default::default() + }); + client.finish(rejected).await.unwrap(); + let error = second.await.unwrap().unwrap_err(); + assert_eq!(error.code(), tonic::Code::PermissionDenied); + let denial = DenialDetail::decode(error.details()).unwrap(); + assert_eq!(denial.reason, DenialReason::NotGranted as i32); + assert_eq!(denial.permission_id, cap::DISCOVERY); + + let status = lock(&h.services.status).clone().unwrap(); + assert_eq!(status.state, models::AccountState::Connected); + assert_eq!(status.account_id.as_deref(), Some("account-previous")); + assert_eq!(h.services.publications.load(Ordering::Relaxed), 1); +} + #[tokio::test] async fn sign_out_wins_over_a_queued_old_storage_write() { let mut h = Harness::new().await; @@ -699,3 +1216,443 @@ async fn achievement_text_with_raw_control_characters_is_still_rejected_by_the_h "the host keeps its control-character rejection as defense" ); } + +#[cfg(unix)] +#[tokio::test] +async fn provider_free_extension_gets_only_its_host_selected_launch_context() { + use gamenode_plugin_protocol::proto::TargetGameContext; + use std::os::unix::fs::PermissionsExt; + + let temp = tempfile::tempdir().unwrap(); + std::fs::set_permissions(temp.path(), std::fs::Permissions::from_mode(0o700)).unwrap(); + let endpoint = temp.path().join("extension.sock"); + let root = super::super::PluginApi::default(); + let api = root.providers.clone(); + api.profiles().update(Some("account-a"), true); + let plugin_id = "org.example.launch-helper"; + let internal_id = super::extension_registration_id(plugin_id); + api.register(Registration { + declared_developer: "Fixture developer".into(), + package_digest: Vec::new(), + provider_id: internal_id.clone(), + plugin_id: plugin_id.into(), + kind: RegistrationKind::Extension, + origin: RegistrationOrigin::ThirdParty { + publisher_fingerprint: "ef".repeat(32), + }, + capabilities: vec![ + cap::CONTEXT.into(), + cap::GAME_CUSTOM_LAUNCH.into(), + cap::GAME_SESSIONS_REPORT.into(), + ], + shared_catalog: false, + playtime: super::super::package::PlaytimeCapabilities { + identifies_gameplay: true, + identifies_pauses: true, + without_pause_detection: Default::default(), + }, + services: Arc::new(Services::default()), + }) + .unwrap(); + let runtime_sessions = Arc::new(RuntimeSessionFixture::default()); + api.set_runtime_session_handler(runtime_sessions.clone()); + + let target = TargetGameContext { + game_id: "42".into(), + installation_id: "steam:123".into(), + profile_id: "account-a".into(), + revision: "target-rev-1".into(), + }; + let launch = api + .begin_extension_launch(&internal_id, api.profiles().epoch(), target.clone()) + .unwrap(); + let credential: Vec = (0..launch.credential.len()) + .step_by(2) + .map(|index| u8::from_str_radix(&launch.credential[index..index + 2], 16).unwrap()) + .collect(); + let server = + super::super::PluginApiServer::start(&tokio::runtime::Handle::current(), &endpoint, root) + .unwrap(); + let mismatched = gamenode_plugin_sdk::Session::open_extension( + gamenode_plugin_sdk::Launch { + endpoint: endpoint.clone(), + credential: credential.clone(), + operation_id: "extension-launch-forged-target".into(), + }, + plugin_id, + "1.0.0", + TargetGameContext { + game_id: "43".into(), + ..target.clone() + }, + &[cap::GAME_CUSTOM_LAUNCH], + ) + .await; + assert!( + mismatched.is_err(), + "the plugin cannot replace Core's target" + ); + let mut session = gamenode_plugin_sdk::Session::open_extension( + gamenode_plugin_sdk::Launch { + endpoint: endpoint.clone(), + credential, + operation_id: "extension-launch".into(), + }, + plugin_id, + "1.0.0", + target, + &[cap::GAME_CUSTOM_LAUNCH, cap::GAME_SESSIONS_REPORT], + ) + .await + .unwrap(); + launch.ready.await.unwrap(); + assert!(session.host.context().provider_id.is_empty()); + let resource_context = session.host.resource_context().unwrap().clone(); + assert!(resource_context.provider_id.is_empty()); + assert_eq!(resource_context.target_game.as_ref().unwrap().game_id, "42"); + + let report = RuntimeSessionReport { + correlation_id: "runtime-report-1".into(), + game_id: "42".into(), + installation_id: "steam:123".into(), + content_id: "rom:zelda".into(), + runtime_id: "runtime:snes".into(), + runtime_instance_id: "instance:one".into(), + reporter_session_id: resource_context.session_id.clone(), + sequence: 1, + observed_at: 100, + transition: RuntimeSessionTransition::Started as i32, + source_observation_id: "observation:one".into(), + runtime_context_id: String::new(), + }; + session + .host + .report_runtime_session(report.clone()) + .await + .unwrap(); + let accepted = tokio::time::timeout(Duration::from_secs(2), session.commands.message()) + .await + .unwrap() + .unwrap() + .unwrap(); + assert_eq!( + accepted.operation, + ProviderOperation::RuntimeSessionResult as i32 + ); + assert_eq!(accepted.target_operation_id, "runtime-report-1"); + let result = accepted.runtime_session_result.unwrap(); + assert_eq!(result.correlation_id, "runtime-report-1"); + assert_eq!(result.outcome, RuntimeSessionOutcome::Accepted as i32); + assert_eq!(result.accepted_sequence, 1); + assert_eq!(runtime_sessions.reports.load(Ordering::Relaxed), 1); + + let mut unapproved_b = report.clone(); + unapproved_b.game_id = "84".into(); + unapproved_b.installation_id = "steam:456".into(); + unapproved_b.correlation_id = "runtime-report-unapproved".into(); + assert!(matches!( + session.host.report_runtime_session(unapproved_b).await, + Err(gamenode_plugin_sdk::Error::Protocol) + )); + assert_eq!(runtime_sessions.reports.load(Ordering::Relaxed), 1); + + runtime_sessions + .delay_next_authorization + .store(true, Ordering::Relaxed); + session + .host + .request_runtime_session_context(RuntimeSessionContextRequest { + correlation_id: "context-stale".into(), + game_id: "84".into(), + installation_id: "steam:456".into(), + runtime_id: "runtime:snes".into(), + runtime_instance_id: "instance:one".into(), + content_id: "rom:metroid".into(), + }) + .await + .unwrap(); + runtime_sessions.authorization_started.notified().await; + { + let mut state = api.state.lock().unwrap(); + state + .sessions + .get_mut(&resource_context.session_id) + .unwrap() + .runtime_instances + .get_mut("instance:one") + .unwrap() + .last_received_at = std::time::Instant::now() - Duration::from_secs(31); + } + runtime_sessions.continue_authorization.notify_one(); + let stale_context = tokio::time::timeout(Duration::from_secs(2), session.commands.message()) + .await + .unwrap() + .unwrap() + .unwrap() + .runtime_session_context_result + .unwrap(); + assert_eq!( + stale_context.outcome, + RuntimeSessionOutcome::RejectedStale as i32 + ); + assert!(stale_context.runtime_context_id.is_empty()); + { + let mut state = api.state.lock().unwrap(); + state + .sessions + .get_mut(&resource_context.session_id) + .unwrap() + .runtime_instances + .get_mut("instance:one") + .unwrap() + .last_received_at = std::time::Instant::now(); + } + + session + .host + .request_runtime_session_context(RuntimeSessionContextRequest { + correlation_id: "context-b".into(), + game_id: "84".into(), + installation_id: "steam:456".into(), + runtime_id: "runtime:snes".into(), + runtime_instance_id: "instance:one".into(), + content_id: "rom:metroid".into(), + }) + .await + .unwrap(); + let context_approval = tokio::time::timeout(Duration::from_secs(2), session.commands.message()) + .await + .unwrap() + .unwrap() + .unwrap(); + assert_eq!( + context_approval.operation, + ProviderOperation::RuntimeSessionContextResult as i32 + ); + let context_token = context_approval + .runtime_session_context_result + .unwrap() + .runtime_context_id; + assert!(!context_token.is_empty()); + + let mut report_b = report.clone(); + report_b.correlation_id = "runtime-report-b".into(); + report_b.game_id = "84".into(); + report_b.installation_id = "steam:456".into(); + report_b.content_id = "rom:metroid".into(); + report_b.runtime_context_id = context_token.clone(); + report_b.sequence = 2; + report_b.observed_at = 110; + report_b.transition = RuntimeSessionTransition::ContentChanged as i32; + report_b.source_observation_id = "observation:b".into(); + session + .host + .report_runtime_session(report_b.clone()) + .await + .unwrap(); + let accepted_b = tokio::time::timeout(Duration::from_secs(2), session.commands.message()) + .await + .unwrap() + .unwrap() + .unwrap(); + assert_eq!( + accepted_b.runtime_session_result.unwrap().outcome, + RuntimeSessionOutcome::Accepted as i32 + ); + assert_eq!(runtime_sessions.reports.load(Ordering::Relaxed), 2); + + let mut forged_b = report_b; + forged_b.correlation_id = "runtime-report-forged".into(); + forged_b.game_id = "85".into(); + forged_b.sequence = 3; + forged_b.source_observation_id = "observation:forged".into(); + session.host.report_runtime_session(forged_b).await.unwrap(); + let rejected_b = tokio::time::timeout(Duration::from_secs(2), session.commands.message()) + .await + .unwrap() + .unwrap() + .unwrap(); + assert_eq!( + rejected_b.runtime_session_result.unwrap().outcome, + RuntimeSessionOutcome::RejectedUnauthorized as i32 + ); + assert_eq!(runtime_sessions.reports.load(Ordering::Relaxed), 2); + + session + .host + .request_runtime_session_context(RuntimeSessionContextRequest { + correlation_id: "context-denied".into(), + game_id: "85".into(), + installation_id: "steam:789".into(), + runtime_id: "runtime:snes".into(), + runtime_instance_id: "instance:one".into(), + content_id: "rom:castlevania".into(), + }) + .await + .unwrap(); + let denied_context = tokio::time::timeout(Duration::from_secs(2), session.commands.message()) + .await + .unwrap() + .unwrap() + .unwrap() + .runtime_session_context_result + .unwrap(); + assert_eq!( + denied_context.outcome, + RuntimeSessionOutcome::RejectedUnauthorized as i32 + ); + assert!(denied_context.runtime_context_id.is_empty()); + + // A process/session restart discards the old host-issued target token. The new process must + // report its selected game under a new runtime instance and obtain a fresh approval for B. + drop(session); + api.disconnect(&internal_id).await; + let restarted_launch = api + .begin_extension_launch( + &internal_id, + api.profiles().epoch(), + resource_context.target_game.as_ref().unwrap().clone(), + ) + .unwrap(); + let restarted_credential: Vec = (0..restarted_launch.credential.len()) + .step_by(2) + .map(|index| { + u8::from_str_radix(&restarted_launch.credential[index..index + 2], 16).unwrap() + }) + .collect(); + let mut restarted = gamenode_plugin_sdk::Session::open_extension( + gamenode_plugin_sdk::Launch { + endpoint: endpoint.clone(), + credential: restarted_credential, + operation_id: "extension-launch-restarted".into(), + }, + plugin_id, + "1.0.0", + resource_context.target_game.as_ref().unwrap().clone(), + &[cap::GAME_CUSTOM_LAUNCH, cap::GAME_SESSIONS_REPORT], + ) + .await + .unwrap(); + restarted_launch.ready.await.unwrap(); + let restarted_context = restarted.host.resource_context().unwrap(); + let mut restarted_report = report.clone(); + restarted_report.correlation_id = "runtime-report-restarted".into(); + restarted_report.reporter_session_id = restarted_context.session_id.clone(); + restarted_report.runtime_instance_id = "instance:two".into(); + restarted_report.sequence = 1; + restarted_report.observed_at = 120; + restarted_report.source_observation_id = "observation:restarted".into(); + restarted + .host + .report_runtime_session(restarted_report.clone()) + .await + .unwrap(); + let restarted_started = + tokio::time::timeout(Duration::from_secs(2), restarted.commands.message()) + .await + .unwrap() + .unwrap() + .unwrap(); + assert_eq!( + restarted_started.runtime_session_result.unwrap().outcome, + RuntimeSessionOutcome::Accepted as i32 + ); + + let mut old_token_report = restarted_report.clone(); + old_token_report.correlation_id = "runtime-report-old-token".into(); + old_token_report.game_id = "84".into(); + old_token_report.installation_id = "steam:456".into(); + old_token_report.content_id = "rom:metroid".into(); + old_token_report.runtime_instance_id = "instance:two".into(); + old_token_report.runtime_context_id = context_token.clone(); + old_token_report.sequence = 2; + old_token_report.observed_at = 130; + old_token_report.transition = RuntimeSessionTransition::ContentChanged as i32; + old_token_report.source_observation_id = "observation:old-token".into(); + restarted + .host + .report_runtime_session(old_token_report) + .await + .unwrap(); + let old_token_result = + tokio::time::timeout(Duration::from_secs(2), restarted.commands.message()) + .await + .unwrap() + .unwrap() + .unwrap(); + assert_eq!( + old_token_result.runtime_session_result.unwrap().outcome, + RuntimeSessionOutcome::RejectedUnauthorized as i32 + ); + assert_eq!(runtime_sessions.reports.load(Ordering::Relaxed), 3); + + restarted + .host + .request_runtime_session_context(RuntimeSessionContextRequest { + correlation_id: "context-b-after-restart".into(), + game_id: "84".into(), + installation_id: "steam:456".into(), + runtime_id: "runtime:snes".into(), + runtime_instance_id: "instance:two".into(), + content_id: "rom:metroid".into(), + }) + .await + .unwrap(); + let fresh_context = tokio::time::timeout(Duration::from_secs(2), restarted.commands.message()) + .await + .unwrap() + .unwrap() + .unwrap() + .runtime_session_context_result + .unwrap(); + assert_eq!( + fresh_context.outcome, + RuntimeSessionOutcome::Accepted as i32 + ); + assert!(!fresh_context.runtime_context_id.is_empty()); + assert_ne!(fresh_context.runtime_context_id, context_token); + + let mut fresh_report = restarted_report; + fresh_report.correlation_id = "runtime-report-b-after-restart".into(); + fresh_report.game_id = "84".into(); + fresh_report.installation_id = "steam:456".into(); + fresh_report.content_id = "rom:metroid".into(); + fresh_report.runtime_context_id = fresh_context.runtime_context_id; + fresh_report.sequence = 2; + fresh_report.observed_at = 140; + fresh_report.transition = RuntimeSessionTransition::ContentChanged as i32; + fresh_report.source_observation_id = "observation:b-after-restart".into(); + restarted + .host + .report_runtime_session(fresh_report) + .await + .unwrap(); + let fresh_result = tokio::time::timeout(Duration::from_secs(2), restarted.commands.message()) + .await + .unwrap() + .unwrap() + .unwrap(); + assert_eq!( + fresh_result.runtime_session_result.unwrap().outcome, + RuntimeSessionOutcome::Accepted as i32 + ); + assert_eq!(runtime_sessions.reports.load(Ordering::Relaxed), 4); + + api.replace_session_grants(&restarted_context.session_id, BTreeSet::new()) + .await + .unwrap(); + assert!(!api.connected(&internal_id)); + assert!( + api.authorize_resource_session(Some(restarted_context)) + .is_err() + ); + assert_eq!(runtime_sessions.reports.load(Ordering::Relaxed), 4); + + drop(restarted); + api.disconnect(&internal_id).await; + assert!(matches!( + api.begin_launch(&internal_id), + Err(error) if error.code() == tonic::Code::PermissionDenied + )); + drop(server); +} diff --git a/crates/app/src/plugin_host/publisher_trust.rs b/crates/app/src/plugin_host/publisher_trust.rs new file mode 100644 index 000000000..e1203703e --- /dev/null +++ b/crates/app/src/plugin_host/publisher_trust.rs @@ -0,0 +1,646 @@ +//! User-approved publisher key pinning for third-party plugins. +//! +//! A valid package signature proves only that the package was signed by the +//! presented key. It does not identify the publisher as official or trusted. +//! The first key and every replacement key require an explicit user decision. +//! +//! This store performs synchronous filesystem work; callers must use a worker +//! thread when opening or updating it from async/UI code. + +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use std::{ + collections::BTreeMap, + fs::{self, File, OpenOptions}, + io::{self, Read, Write}, + path::{Path, PathBuf}, + sync::atomic::{AtomicU64, Ordering}, +}; +use thiserror::Error; + +const FILE_NAME: &str = "publisher-keys.json"; +const MAX_STORE_BYTES: u64 = 1024 * 1024; +/// How many replaced fingerprints one plugin's trust entry remembers for a reviewed data +/// migration. The oldest are dropped first. +const MAX_PRIOR_FINGERPRINTS: usize = 8; +static NEXT_TEMP: AtomicU64 = AtomicU64::new(1); + +#[derive(Debug, Error)] +pub enum TrustStoreError { + #[error("publisher identity requires explicit user confirmation")] + ConfirmationRequired, + #[error("publisher key changed; explicit re-trust is required")] + KeyChanged, + #[error("publisher key fingerprint does not match the confirmation")] + FingerprintMismatch, + #[error("plugin identity is invalid")] + InvalidPluginId, + #[error("Ed25519 public key must contain exactly 32 bytes")] + InvalidPublicKey, + #[error("publisher trust store is invalid: {0}")] + InvalidStore(String), + #[error(transparent)] + Io(#[from] io::Error), +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum KeyStatus { + Untrusted { + presented_fingerprint: String, + }, + Trusted { + fingerprint: String, + }, + Changed { + pinned_fingerprint: String, + presented_fingerprint: String, + }, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +struct StoreFile { + schema: u32, + publishers: BTreeMap, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +struct PinnedPublisher { + fingerprint: String, + /// Fingerprints this plugin was pinned to before the current one. Re-trust records the key it + /// replaced so the host can offer a reviewed data migration from the old identity. Schema 1 + /// entries have no history. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + prior_fingerprints: Vec, +} + +/// Durable map from external plugin IDs to user-pinned Ed25519 key fingerprints. +pub struct PublisherTrustStore { + path: PathBuf, + publishers: BTreeMap, +} + +impl PublisherTrustStore { + /// Opens `/publisher-keys.json`, creating an empty store if absent. + /// The directory and file are restricted to the current user on Unix. + pub fn open(private_dir: impl AsRef) -> Result { + let directory = private_dir.as_ref(); + ensure_private_dir(directory)?; + let path = directory.join(FILE_NAME); + let publishers = match fs::symlink_metadata(&path) { + Ok(meta) if meta.file_type().is_file() => { + if meta.len() > MAX_STORE_BYTES { + return Err(TrustStoreError::InvalidStore( + "file exceeds the size limit".into(), + )); + } + ensure_private_file(&path)?; + let file = File::open(&path)?; + let mut bytes = Vec::with_capacity(meta.len() as usize); + file.take(MAX_STORE_BYTES + 1).read_to_end(&mut bytes)?; + if bytes.len() as u64 > MAX_STORE_BYTES { + return Err(TrustStoreError::InvalidStore( + "file exceeds the size limit".into(), + )); + } + let document: StoreFile = serde_json::from_slice(&bytes) + .map_err(|error| TrustStoreError::InvalidStore(error.to_string()))?; + if !(1..=2).contains(&document.schema) { + return Err(TrustStoreError::InvalidStore( + "unsupported schema version".into(), + )); + } + for (plugin_id, publisher) in &document.publishers { + validate_plugin_id(plugin_id)?; + if !is_fingerprint(&publisher.fingerprint) + || publisher + .prior_fingerprints + .iter() + .any(|prior| !is_fingerprint(prior)) + { + return Err(TrustStoreError::InvalidStore( + "malformed publisher fingerprint".into(), + )); + } + } + document.publishers + } + Ok(_) => { + return Err(TrustStoreError::InvalidStore( + "store path is not a regular file".into(), + )); + } + Err(error) if error.kind() == io::ErrorKind::NotFound => BTreeMap::new(), + Err(error) => return Err(error.into()), + }; + Ok(Self { path, publishers }) + } + + /// Computes the user-visible status for a candidate signing key. + pub fn inspect( + &self, + plugin_id: &str, + public_key: &[u8], + ) -> Result { + validate_plugin_id(plugin_id)?; + let presented_fingerprint = fingerprint(public_key)?; + Ok(match self.publishers.get(plugin_id) { + None => KeyStatus::Untrusted { + presented_fingerprint, + }, + Some(pinned) if pinned.fingerprint == presented_fingerprint => KeyStatus::Trusted { + fingerprint: presented_fingerprint, + }, + Some(pinned) => KeyStatus::Changed { + pinned_fingerprint: pinned.fingerprint.clone(), + presented_fingerprint, + }, + }) + } + + /// Pins a first key only when the user confirms the exact displayed fingerprint. + pub fn confirm_first_key( + &mut self, + plugin_id: &str, + public_key: &[u8], + confirmed_fingerprint: &str, + ) -> Result { + validate_plugin_id(plugin_id)?; + let candidate = fingerprint(public_key)?; + if self.publishers.contains_key(plugin_id) { + return Err(TrustStoreError::KeyChanged); + } + if !constant_time_eq(candidate.as_bytes(), confirmed_fingerprint.as_bytes()) { + return Err(TrustStoreError::FingerprintMismatch); + } + let mut next = self.publishers.clone(); + next.insert( + plugin_id.to_owned(), + PinnedPublisher { + fingerprint: candidate.clone(), + prior_fingerprints: Vec::new(), + }, + ); + self.persist(&next)?; + self.publishers = next; + Ok(candidate) + } + + /// Replaces a pinned key only after explicit confirmation of its new fingerprint. The key it + /// replaces is remembered for a reviewed data migration, never trusted automatically. + pub fn retrust_key( + &mut self, + plugin_id: &str, + public_key: &[u8], + confirmed_new_fingerprint: &str, + ) -> Result { + validate_plugin_id(plugin_id)?; + let candidate = fingerprint(public_key)?; + let Some(previous) = self.publishers.get(plugin_id) else { + return Err(TrustStoreError::ConfirmationRequired); + }; + if !constant_time_eq(candidate.as_bytes(), confirmed_new_fingerprint.as_bytes()) { + return Err(TrustStoreError::FingerprintMismatch); + } + let mut next = self.publishers.clone(); + next.insert( + plugin_id.to_owned(), + PinnedPublisher { + fingerprint: candidate.clone(), + prior_fingerprints: remember_prior(previous, &candidate), + }, + ); + self.persist(&next)?; + self.publishers = next; + Ok(candidate) + } + + /// Pins one key for several plugin ids in a single write. A bundle is one distribution unit + /// with one publisher, so one fingerprint confirmation covers every component; a failure + /// leaves no component pinned. Existing pins are replaced the same way `retrust_key` replaces + /// one, because the review already showed the change and the user confirmed the new value. + pub fn confirm_publishers( + &mut self, + plugin_ids: &[String], + public_key: &[u8], + confirmed_fingerprint: &str, + ) -> Result { + if plugin_ids.is_empty() { + return Err(TrustStoreError::InvalidPluginId); + } + let candidate = fingerprint(public_key)?; + if !constant_time_eq(candidate.as_bytes(), confirmed_fingerprint.as_bytes()) { + return Err(TrustStoreError::FingerprintMismatch); + } + let mut next = self.publishers.clone(); + for plugin_id in plugin_ids { + validate_plugin_id(plugin_id)?; + let prior_fingerprints = next + .get(plugin_id) + .map(|previous| remember_prior(previous, &candidate)) + .unwrap_or_default(); + next.insert( + plugin_id.clone(), + PinnedPublisher { + fingerprint: candidate.clone(), + prior_fingerprints, + }, + ); + } + self.persist(&next)?; + self.publishers = next; + Ok(candidate) + } + + /// Fingerprints the plugin was pinned to before its current key, oldest first. The host uses + /// this only to offer a reviewed data migration; a prior key is never trusted automatically. + pub fn prior_fingerprints(&self, plugin_id: &str) -> Vec { + self.publishers + .get(plugin_id) + .map(|publisher| publisher.prior_fingerprints.clone()) + .unwrap_or_default() + } + + /// Returns whether a candidate key is exactly the key the user approved. + pub fn is_pinned(&self, plugin_id: &str, public_key: &[u8]) -> Result { + Ok(matches!( + self.inspect(plugin_id, public_key)?, + KeyStatus::Trusted { .. } + )) + } + + fn persist( + &self, + publishers: &BTreeMap, + ) -> Result<(), TrustStoreError> { + let parent = self + .path + .parent() + .ok_or_else(|| TrustStoreError::InvalidStore("store has no parent directory".into()))?; + ensure_private_dir(parent)?; + let data = serde_json::to_vec(&StoreFile { + schema: 2, + publishers: publishers.clone(), + }) + .map_err(|error| TrustStoreError::InvalidStore(error.to_string()))?; + if data.len() as u64 > MAX_STORE_BYTES { + return Err(TrustStoreError::InvalidStore( + "serialized store exceeds the size limit".into(), + )); + } + let temp = parent.join(format!( + ".publisher-keys-{}-{}", + std::process::id(), + NEXT_TEMP.fetch_add(1, Ordering::Relaxed) + )); + let mut options = OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600); + } + let mut file = options.open(&temp)?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + file.set_permissions(fs::Permissions::from_mode(0o600))?; + } + let write_result = (|| -> io::Result<()> { + file.write_all(&data)?; + file.sync_all()?; + atomic_replace(&temp, &self.path)?; + sync_dir(parent)?; + Ok(()) + })(); + if write_result.is_err() { + let _ = fs::remove_file(&temp); + } + write_result?; + ensure_private_file(&self.path)?; + Ok(()) + } +} + +fn remember_prior(previous: &PinnedPublisher, new_fingerprint: &str) -> Vec { + let mut prior = previous.prior_fingerprints.clone(); + if !prior.contains(&previous.fingerprint) { + prior.push(previous.fingerprint.clone()); + } + prior.retain(|fingerprint| fingerprint != new_fingerprint); + if prior.len() > MAX_PRIOR_FINGERPRINTS { + let excess = prior.len() - MAX_PRIOR_FINGERPRINTS; + prior.drain(0..excess); + } + prior +} + +fn fingerprint(public_key: &[u8]) -> Result { + if public_key.len() != 32 { + return Err(TrustStoreError::InvalidPublicKey); + } + let digest = Sha256::digest(public_key); + let mut output = String::with_capacity(71); + output.push_str("SHA256:"); + for byte in digest { + use std::fmt::Write as _; + write!(&mut output, "{byte:02x}").expect("writing into a String cannot fail"); + } + Ok(output) +} + +/// Returns the canonical, user-visible fingerprint for a publisher's Ed25519 public key. +pub fn key_fingerprint(public_key: &[u8]) -> String { + fingerprint(public_key).unwrap_or_default() +} + +fn is_fingerprint(value: &str) -> bool { + value.len() == 71 + && value.starts_with("SHA256:") + && value[7..].bytes().all(|byte| byte.is_ascii_hexdigit()) +} + +fn validate_plugin_id(plugin_id: &str) -> Result<(), TrustStoreError> { + if plugin_id.is_empty() + || plugin_id.len() > 256 + || !plugin_id + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-' | b':')) + { + return Err(TrustStoreError::InvalidPluginId); + } + Ok(()) +} + +fn constant_time_eq(left: &[u8], right: &[u8]) -> bool { + if left.len() != right.len() { + return false; + } + left.iter() + .zip(right) + .fold(0u8, |diff, (a, b)| diff | (a ^ b)) + == 0 +} + +#[cfg(unix)] +fn ensure_private_dir(path: &Path) -> io::Result<()> { + use std::os::unix::fs::{DirBuilderExt, PermissionsExt}; + match fs::symlink_metadata(path) { + Ok(meta) if meta.file_type().is_symlink() || !meta.is_dir() => Err(io::Error::new( + io::ErrorKind::InvalidInput, + "unsafe trust directory", + )), + Ok(meta) => { + if meta.permissions().mode() & 0o077 != 0 { + fs::set_permissions(path, fs::Permissions::from_mode(0o700))?; + } + Ok(()) + } + Err(error) if error.kind() == io::ErrorKind::NotFound => { + fs::DirBuilder::new().mode(0o700).create(path) + } + Err(error) => Err(error), + } +} + +#[cfg(not(unix))] +fn ensure_private_dir(path: &Path) -> io::Result<()> { + match fs::symlink_metadata(path) { + Ok(meta) if meta.file_type().is_symlink() || !meta.is_dir() => Err(io::Error::new( + io::ErrorKind::InvalidInput, + "unsafe trust directory", + )), + Ok(_) => Ok(()), + Err(error) if error.kind() == io::ErrorKind::NotFound => fs::create_dir(path), + Err(error) => Err(error), + } +} + +#[cfg(unix)] +fn ensure_private_file(path: &Path) -> io::Result<()> { + use std::os::unix::fs::PermissionsExt; + let meta = fs::symlink_metadata(path)?; + if meta.file_type().is_symlink() || !meta.is_file() { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "unsafe trust file", + )); + } + if meta.permissions().mode() & 0o077 != 0 { + fs::set_permissions(path, fs::Permissions::from_mode(0o600))?; + } + Ok(()) +} + +#[cfg(not(unix))] +fn ensure_private_file(path: &Path) -> io::Result<()> { + let meta = fs::symlink_metadata(path)?; + if meta.file_type().is_symlink() || !meta.is_file() { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "unsafe trust file", + )); + } + Ok(()) +} + +fn sync_dir(path: &Path) -> io::Result<()> { + #[cfg(unix)] + File::open(path)?.sync_all()?; + #[cfg(not(unix))] + let _ = path; + Ok(()) +} + +fn atomic_replace(from: &Path, to: &Path) -> io::Result<()> { + #[cfg(windows)] + { + use std::os::windows::ffi::OsStrExt; + use windows_sys::Win32::Storage::FileSystem::{ + MOVEFILE_REPLACE_EXISTING, MOVEFILE_WRITE_THROUGH, MoveFileExW, + }; + let from = from + .as_os_str() + .encode_wide() + .chain(Some(0)) + .collect::>(); + let to = to + .as_os_str() + .encode_wide() + .chain(Some(0)) + .collect::>(); + // SAFETY: both paths are NUL-terminated UTF-16 buffers valid for this call. + let result = unsafe { + MoveFileExW( + from.as_ptr(), + to.as_ptr(), + MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH, + ) + }; + if result == 0 { + Err(io::Error::last_os_error()) + } else { + Ok(()) + } + } + #[cfg(not(windows))] + { + fs::rename(from, to) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use tempfile::tempdir; + + #[test] + fn first_key_requires_exact_user_confirmation_and_survives_reopen() { + let directory = tempdir().unwrap(); + let key = [7; 32]; + let mut store = PublisherTrustStore::open(directory.path()).unwrap(); + let fingerprint = match store.inspect("org.example.plugin", &key).unwrap() { + KeyStatus::Untrusted { + presented_fingerprint, + } => presented_fingerprint, + other => panic!("unexpected status: {other:?}"), + }; + assert!(matches!( + store.confirm_first_key("org.example.plugin", &key, "wrong"), + Err(TrustStoreError::FingerprintMismatch) + )); + store + .confirm_first_key("org.example.plugin", &key, &fingerprint) + .unwrap(); + drop(store); + let store = PublisherTrustStore::open(directory.path()).unwrap(); + assert!(store.is_pinned("org.example.plugin", &key).unwrap()); + assert!(matches!( + store.inspect("org.example.plugin", &[8; 32]).unwrap(), + KeyStatus::Changed { .. } + )); + } + + #[test] + fn key_rotation_requires_explicit_retrust_and_exact_new_fingerprint() { + let directory = tempdir().unwrap(); + let old = [1; 32]; + let new = [2; 32]; + let mut store = PublisherTrustStore::open(directory.path()).unwrap(); + let old_fingerprint = match store.inspect("org.example.plugin", &old).unwrap() { + KeyStatus::Untrusted { + presented_fingerprint, + } => presented_fingerprint, + _ => unreachable!(), + }; + store + .confirm_first_key("org.example.plugin", &old, &old_fingerprint) + .unwrap(); + assert!(matches!( + store.confirm_first_key("org.example.plugin", &new, "any"), + Err(TrustStoreError::KeyChanged) + )); + assert!(matches!( + store.retrust_key("org.example.plugin", &new, "wrong"), + Err(TrustStoreError::FingerprintMismatch) + )); + let new_fingerprint = match store.inspect("org.example.plugin", &new).unwrap() { + KeyStatus::Changed { + presented_fingerprint, + .. + } => presented_fingerprint, + _ => unreachable!(), + }; + store + .retrust_key("org.example.plugin", &new, &new_fingerprint) + .unwrap(); + assert!(store.is_pinned("org.example.plugin", &new).unwrap()); + assert!(!store.is_pinned("org.example.plugin", &old).unwrap()); + assert_eq!( + store.prior_fingerprints("org.example.plugin"), + vec![old_fingerprint.clone()] + ); + drop(store); + + // The replaced key is remembered across reopening so a reviewed migration can be offered. + let store = PublisherTrustStore::open(directory.path()).unwrap(); + assert_eq!( + store.prior_fingerprints("org.example.plugin"), + vec![old_fingerprint.clone()] + ); + assert!(store.prior_fingerprints("org.example.unknown").is_empty()); + assert_eq!( + store.inspect("org.example.plugin", &new).unwrap(), + KeyStatus::Trusted { + fingerprint: new_fingerprint, + } + ); + } + + #[test] + fn a_schema_one_store_still_loads_without_migration_history() { + let directory = tempdir().unwrap(); + let key = [3; 32]; + let fingerprint = key_fingerprint(&key); + fs::write( + directory.path().join(FILE_NAME), + format!(r#"{{"schema":1,"publishers":{{"org.example.plugin":{{"fingerprint":"{fingerprint}"}}}}}}"#), + ) + .unwrap(); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + fs::set_permissions( + directory.path().join(FILE_NAME), + fs::Permissions::from_mode(0o600), + ) + .unwrap(); + } + let store = PublisherTrustStore::open(directory.path()).unwrap(); + assert!(store.is_pinned("org.example.plugin", &key).unwrap()); + assert!(store.prior_fingerprints("org.example.plugin").is_empty()); + } + + #[test] + fn repeated_retrust_keeps_a_bounded_oldest_first_history() { + let directory = tempdir().unwrap(); + let mut store = PublisherTrustStore::open(directory.path()).unwrap(); + let first = [1; 32]; + let first_fingerprint = key_fingerprint(&first); + store + .confirm_first_key("org.example.plugin", &first, &first_fingerprint) + .unwrap(); + let mut previous = first; + let mut expected = Vec::new(); + for byte in 2..=11u8 { + let next = [byte; 32]; + store + .retrust_key("org.example.plugin", &next, &key_fingerprint(&next)) + .unwrap(); + expected.push(key_fingerprint(&previous)); + previous = next; + } + let history = store.prior_fingerprints("org.example.plugin"); + assert_eq!(history.len(), MAX_PRIOR_FINGERPRINTS); + assert_eq!(history, expected[expected.len() - MAX_PRIOR_FINGERPRINTS..]); + assert!(!history.contains(&key_fingerprint(&previous))); + } + + #[test] + fn refuses_symlink_and_malformed_stores() { + let directory = tempdir().unwrap(); + let store_path = directory.path().join(FILE_NAME); + fs::write(&store_path, br#"{"schema":9,"publishers":{}}"#).unwrap(); + assert!(matches!( + PublisherTrustStore::open(directory.path()), + Err(TrustStoreError::InvalidStore(_)) + )); + fs::remove_file(&store_path).unwrap(); + #[cfg(unix)] + { + std::os::unix::fs::symlink(directory.path().join("missing"), &store_path).unwrap(); + assert!(PublisherTrustStore::open(directory.path()).is_err()); + } + } +} diff --git a/crates/app/src/plugin_host/resource_leases.rs b/crates/app/src/plugin_host/resource_leases.rs new file mode 100644 index 000000000..68c62e525 --- /dev/null +++ b/crates/app/src/plugin_host/resource_leases.rs @@ -0,0 +1,295 @@ +//! Host-owned coordination for shared emulator resources. +//! +//! A runtime launch holds a use lease for every shared save resource it may touch. Backup and +//! restore hold an exclusive lease for the complete operation. Acquiring a set is atomic: either +//! every key is reserved or none is. The plugin protocol never receives these keys or leases. + +#[cfg(test)] +use super::grants::PluginIdentity; +use sha2::{Digest, Sha256}; +use std::collections::{BTreeMap, BTreeSet}; +use std::sync::{Arc, Mutex}; + +const MAX_LEASE_KEYS: usize = 64; + +/// An opaque host-derived identity for one reviewed shared save resource. +/// +/// The key identifies the host-resolved backing resource. Authorization remains bound to the +/// plugin, profile, epoch and reviewed revision, but those values must not split the lock for +/// the same backing resource. It is never accepted from plugin input or exposed over IPC. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct ResourceLeaseKey([u8; 32]); + +impl ResourceLeaseKey { + /// Derives the shared lock for a host-canonicalized backing folder. Aliases, approval ids and + /// profile revisions deliberately do not split it: every route to the same folder must + /// serialize against one key. + pub(crate) fn from_backing_identity(backing: &[u8]) -> Option { + if backing.is_empty() || backing.len() > 32 * 1024 { + return None; + } + let mut digest = Sha256::new(); + digest.update(b"gamenode.shared-save-resource.lease.v1\0"); + hash_part(&mut digest, backing); + Some(Self(digest.finalize().into())) + } + + #[cfg(test)] + pub(crate) fn derive( + identity: &PluginIdentity, + profile_epoch: u64, + resource_id: &str, + resource_revision: u64, + approved_handle_identity: &[u8], + ) -> Option { + if profile_epoch == 0 + || resource_id.is_empty() + || resource_id.len() > 256 + || resource_revision == 0 + || approved_handle_identity.is_empty() + { + return None; + } + // These fields establish that the request was reviewed; they are deliberately not part + // of the lock identity. All aliases and revisions of a backing resource must serialize. + let _ = identity; + Self::from_backing_identity(approved_handle_identity) + } +} + +fn hash_part(digest: &mut Sha256, bytes: &[u8]) { + digest.update((bytes.len() as u64).to_be_bytes()); + digest.update(bytes); +} + +/// A conflict or inability to determine the resource state. Both deny the requested operation. +#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)] +pub enum ResourceLeaseError { + #[error("the shared resource is in use")] + Busy, + #[error("the shared resource state cannot be determined")] + Unknown, +} + +/// Marker for an RAII lease. Dropping it releases every key in its atomic set. +pub trait ResourceLease: Send + Sync {} + +/// Serializes supervised runtime use against backup and restore. +pub(crate) trait ResourceLeaseCoordinator: Send + Sync { + /// Atomically reserve all keys for supervised runtime use. + fn acquire_use( + &self, + keys: &[ResourceLeaseKey], + ) -> Result, ResourceLeaseError>; + + /// Atomically reserve all keys exclusively for backup or restore. + fn acquire_exclusive( + &self, + keys: &[ResourceLeaseKey], + ) -> Result, ResourceLeaseError>; +} + +#[derive(Clone, Copy, Debug, Default)] +struct State { + uses: usize, + exclusive: bool, +} + +/// In-process coordinator shared by the launch supervisor and backup host. +#[derive(Default)] +pub struct ResourceLeases { + state: Arc>>, +} + +struct LeaseGuard { + state: Arc>>, + keys: Vec, + exclusive: bool, +} + +impl ResourceLease for LeaseGuard {} + +impl Drop for LeaseGuard { + fn drop(&mut self) { + let Ok(mut state) = self.state.lock() else { + // A poisoned coordinator cannot safely infer that a resource is idle. Keep the + // reservations in place; subsequent acquisitions also fail closed. + return; + }; + for key in &self.keys { + let remove = if let Some(entry) = state.get_mut(key) { + if self.exclusive { + entry.exclusive = false; + } else { + entry.uses = entry.uses.saturating_sub(1); + } + entry.uses == 0 && !entry.exclusive + } else { + false + }; + if remove { + state.remove(key); + } + } + } +} + +impl ResourceLeases { + fn reserve( + &self, + keys: &[ResourceLeaseKey], + exclusive: bool, + ) -> Result, ResourceLeaseError> { + if keys.is_empty() || keys.len() > MAX_LEASE_KEYS { + return Err(ResourceLeaseError::Unknown); + } + let unique = keys.iter().copied().collect::>(); + if unique.len() != keys.len() { + return Err(ResourceLeaseError::Unknown); + } + let mut state = self.state.lock().map_err(|_| ResourceLeaseError::Unknown)?; + if unique.iter().any(|key| { + state + .get(key) + .is_some_and(|entry| entry.exclusive || (exclusive && entry.uses > 0)) + }) { + return Err(ResourceLeaseError::Busy); + } + for key in &unique { + let entry = state.entry(*key).or_default(); + if exclusive { + entry.exclusive = true; + } else { + entry.uses += 1; + } + } + Ok(Box::new(LeaseGuard { + state: Arc::clone(&self.state), + keys: unique.into_iter().collect(), + exclusive, + })) + } +} + +impl ResourceLeaseCoordinator for ResourceLeases { + fn acquire_use( + &self, + keys: &[ResourceLeaseKey], + ) -> Result, ResourceLeaseError> { + self.reserve(keys, false) + } + + fn acquire_exclusive( + &self, + keys: &[ResourceLeaseKey], + ) -> Result, ResourceLeaseError> { + self.reserve(keys, true) + } +} + +impl ResourceLeases { + /// Production path for backup and restore jobs. + pub fn lease_exclusive( + &self, + keys: &[ResourceLeaseKey], + ) -> Result, ResourceLeaseError> { + ResourceLeaseCoordinator::acquire_exclusive(self, keys) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn key(value: u8) -> ResourceLeaseKey { + ResourceLeaseKey([value; 32]) + } + + #[test] + fn use_and_exclusive_leases_exclude_each_other_and_release_on_drop() { + let leases = ResourceLeases::default(); + let use_lease = leases.acquire_use(&[key(1)]).unwrap(); + assert!(matches!( + leases.acquire_exclusive(&[key(1)]), + Err(ResourceLeaseError::Busy) + )); + drop(use_lease); + + let exclusive = leases.acquire_exclusive(&[key(1)]).unwrap(); + assert!(matches!( + leases.acquire_use(&[key(1)]), + Err(ResourceLeaseError::Busy) + )); + drop(exclusive); + assert!(leases.acquire_use(&[key(1)]).is_ok()); + } + + #[test] + fn multi_key_acquisition_is_atomic() { + let leases = ResourceLeases::default(); + let held = leases.acquire_use(&[key(2)]).unwrap(); + assert!(matches!( + leases.acquire_exclusive(&[key(1), key(2)]), + Err(ResourceLeaseError::Busy) + )); + assert!(leases.acquire_use(&[key(1)]).is_ok()); + drop(held); + } + + #[test] + fn concurrent_exclusive_acquisitions_have_one_winner() { + let leases = Arc::new(ResourceLeases::default()); + let barrier = Arc::new(std::sync::Barrier::new(3)); + let workers = (0..2) + .map(|_| { + let leases = Arc::clone(&leases); + let barrier = Arc::clone(&barrier); + std::thread::spawn(move || { + let result = leases.acquire_exclusive(&[key(3), key(4)]); + barrier.wait(); + result.is_ok() + }) + }) + .collect::>(); + barrier.wait(); + let winners = workers + .into_iter() + .map(|worker| worker.join().expect("lease worker did not panic")) + .filter(|won| *won) + .count(); + assert_eq!(winners, 1); + } + + #[test] + fn resource_identity_remains_stable_across_authorization_changes() { + let identity = PluginIdentity { + plugin_id: "org.example.emulator".into(), + publisher_fingerprint: "ab".repeat(32), + profile_id: "account-a".into(), + }; + let derive = |epoch, id, revision, handle| { + ResourceLeaseKey::derive(&identity, epoch, id, revision, handle).unwrap() + }; + let baseline = derive(1, "card-1", 4, b"approved-folder-a"); + assert_eq!(baseline, derive(2, "card-1", 4, b"approved-folder-a")); + assert_eq!(baseline, derive(1, "card-2", 4, b"approved-folder-a")); + assert_eq!(baseline, derive(1, "card-1", 5, b"approved-folder-a")); + assert_ne!(baseline, derive(1, "card-1", 4, b"approved-folder-b")); + let mut other_identity = identity; + other_identity.profile_id = "account-b".into(); + assert_eq!( + baseline, + ResourceLeaseKey::derive(&other_identity, 1, "card-1", 4, b"approved-folder-a") + .unwrap() + ); + let leases = ResourceLeases::default(); + let _use_lease = leases.acquire_use(&[baseline]).unwrap(); + let after_review = + ResourceLeaseKey::derive(&other_identity, 2, "renamed", 7, b"approved-folder-a") + .unwrap(); + assert!(matches!( + leases.acquire_exclusive(&[after_review]), + Err(ResourceLeaseError::Busy) + )); + } +} diff --git a/crates/app/src/plugin_host/resources.rs b/crates/app/src/plugin_host/resources.rs new file mode 100644 index 000000000..6e0a79a88 --- /dev/null +++ b/crates/app/src/plugin_host/resources.rs @@ -0,0 +1,2219 @@ +//! The API 1.6 `ResourceHost` service. Library list/get/watch are served from the host-owned +//! [`LibraryFeed`], shared Data access through the bounded broker, and display metadata and +//! favorites through the engine's [`LibraryHost`]; other methods remain `UNIMPLEMENTED` until +//! their adapters exist, and `DescribeApi` advertises only what is served. +//! +//! Calls are plugin-initiated: they carry the session's resource context from `OpenSession`, +//! which [`ProviderApi::authorize_resource`] checks against the session, profile and grants. + +use std::collections::HashMap; +use std::pin::Pin; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; + +use futures_util::Stream; +use gamenode_platform::plugin_shared_data::{OwnerScope, RecordProvenance}; +use gamenode_plugin_protocol::{ + capability as cap, + prost_types::{self, value::Kind}, + proto::*, +}; +use serde_json::{Map as JsonMap, Number as JsonNumber, Value as JsonValue}; +use tokio::sync::{broadcast, mpsc}; +use tokio_stream::wrappers::ReceiverStream; +use tonic::{Request, Response, Status}; + +mod artwork; +mod backups; +mod custom_launch; +mod diagnostics; +pub(crate) mod files; +mod games; +mod jobs; +mod libraries; +mod locations; +mod matching; +mod mutations; +mod network; +mod notifications; +mod observations; +mod performance; +mod persistence; +mod ports; +mod runtimes; +mod saves; +mod storage; +mod tools; + +use self::mutations::mutation_key; +use super::files::FileAccess; +use super::fingerprints; +use super::intents::Intents; +use super::jobs::Jobs; +use super::library::{ + Change, CursorBinding, CursorError, DEFAULT_PAGE_SIZE, LibraryFeed, MAX_PAGE_SIZE, + MAX_SEARCH_BYTES, ResumeError, Scope, +}; +use super::network::NetworkAccess; +use super::notifications::Notifications; +use super::provider::{ProviderApi, ResourceCaller}; +use super::saves::SaveAccess; +use super::shared_data::{ + BrokerError, DataBroker, ProjectedRecord, QueryCursor, QueryRequest, SubscriptionEnd, +}; +use super::shared_pool::{DurableSharedPool, DurableWrite}; +use super::sharing_policy::{AccessDecision, AccessRequest, Authorizer, Delivery}; +use super::storage::PluginStorage; + +/// Open `LibraryWatch` streams allowed per plugin session. +pub const MAX_WATCHES_PER_SESSION: usize = 8; +/// How often an idle watch rechecks its authorization. +const WATCH_RECHECK: Duration = Duration::from_secs(5); +const WATCH_QUEUE: usize = 16; +const MAX_PROVIDER_ID_BYTES: usize = 128; +const MAX_DATA_CURSORS: usize = 4096; +const DATA_CURSOR_TTL: Duration = Duration::from_secs(5 * 60); + +/// The ResourceHost methods this build serves, for `DescribeApi`. +pub const SERVED: &[Served] = &[ + Served::new("PortsList", cap::PORTS_READ, true, "host catalog"), + Served::new("PortsDetail", cap::PORTS_READ, false, "host catalog"), + Served::new( + "PortsRequestInstall", + cap::PORTS_INSTALL, + false, + "host catalog; Core guided setup", + ), + Served::new( + "ToolsList", + cap::TOOLS_READ, + true, + "host catalog; scoped game", + ), + Served::new( + "ToolsRequestApply", + cap::TOOLS_APPLY, + false, + "scoped game; Core tools review", + ), + Served::new( + "ToolsRequestRemove", + cap::TOOLS_REMOVE, + false, + "scoped game; Core tools review", + ), + Served::new( + "BackupsList", + cap::BACKUPS_READ, + true, + "approved save profile", + ), + Served::new( + "BackupsRequestCreate", + cap::BACKUPS_CREATE, + false, + "approved save profile", + ), + Served::new( + "BackupsRequestRestore", + cap::BACKUPS_RESTORE, + false, + "approved save profile; confirmation required", + ), + Served::new( + "StorageDiagnosticsPublishBenchmark", + cap::STORAGE_DIAGNOSTICS_PUBLISH, + false, + "host-attributed volume report; Core starts no benchmark process", + ), + Served::new( + "StorageDiagnosticsPublishSmart", + cap::STORAGE_DIAGNOSTICS_PUBLISH, + false, + "host-attributed volume report; Core starts no SMART process", + ), + Served::new( + "ComputerPublishHardware", + cap::COMPUTER_HARDWARE_PUBLISH, + false, + "host-attributed sensitive hardware observation; no collector is started", + ), + Served::new( + "GamePresencePublish", + cap::GAME_PRESENCE_PUBLISH, + false, + "host-attributed sensitive game status with bounded expiry", + ), + Served::new( + "GamePresenceClear", + cap::GAME_PRESENCE_PUBLISH, + false, + "the caller's own game/session presence", + ), + Served::new( + "GamePerformancePublishSamples", + cap::GAME_PERFORMANCE_PUBLISH, + false, + "authenticated, bounded session-retained performance series", + ), + Served::new( + "GamePerformanceEndSeries", + cap::GAME_PERFORMANCE_PUBLISH, + false, + "the caller's own performance series", + ), + Served::new( + "LibrariesList", + cap::LIBRARY_ROOTS_READ, + true, + PRIVATE_NAMESPACE, + ), + Served::new( + "LibrariesGet", + cap::LIBRARY_ROOTS_READ, + false, + PRIVATE_NAMESPACE, + ), + Served::new( + "LibrariesWatch", + cap::LIBRARY_ROOTS_READ, + false, + PRIVATE_NAMESPACE, + ), + Served::new( + "LibrariesCreate", + cap::LIBRARY_ROOTS_CREATE, + false, + PRIVATE_NAMESPACE, + ), + Served::new( + "LibrariesUpdate", + cap::LIBRARY_ROOTS_UPDATE, + false, + PRIVATE_NAMESPACE, + ), + Served::new( + "LibrariesRemove", + cap::LIBRARY_ROOTS_DELETE, + false, + PRIVATE_NAMESPACE, + ), + Served::new( + "LibrariesAddRoot", + cap::LIBRARY_ROOTS_CREATE, + false, + PRIVATE_NAMESPACE, + ), + Served::new( + "LibrariesUpdateRoot", + cap::LIBRARY_ROOTS_UPDATE, + false, + PRIVATE_NAMESPACE, + ), + Served::new( + "LibrariesRemoveRoot", + cap::LIBRARY_ROOTS_DELETE, + false, + PRIVATE_NAMESPACE, + ), + Served::new("LibraryList", cap::LIBRARY_READ, true, READ_SCOPE), + Served::new("LibraryGet", cap::LIBRARY_READ, false, READ_SCOPE), + Served::new("LibraryWatch", cap::LIBRARY_READ, false, READ_SCOPE), + Served::new( + "RuntimesList", + cap::GAME_RUNTIME_READ, + true, + RUNTIME_READ_SCOPE, + ), + Served::new( + "RuntimesGet", + cap::GAME_RUNTIME_READ, + false, + RUNTIME_READ_SCOPE, + ), + Served::new( + "RuntimesWatch", + cap::GAME_RUNTIME_READ, + false, + RUNTIME_READ_SCOPE, + ), + Served::new( + "RuntimesRequestAccess", + cap::GAME_RUNTIME_CREATE, + false, + PRIVATE_NAMESPACE, + ), + Served::new( + "RuntimesRegister", + cap::GAME_RUNTIME_CREATE, + false, + PRIVATE_NAMESPACE, + ), + Served::new( + "RuntimesUpdate", + cap::GAME_RUNTIME_UPDATE, + false, + PRIVATE_NAMESPACE, + ), + Served::new( + "RuntimesRemove", + cap::GAME_RUNTIME_DELETE, + false, + PRIVATE_NAMESPACE, + ), + Served::new("GamesRegisterContent", cap::DISCOVERY, false, OWN_OR_TARGET), + Served::new( + "MetadataUpdate", + cap::LIBRARY_METADATA_WRITE, + false, + OWN_ENTRIES, + ), + Served::new("FavoritesList", cap::FAVORITES_READ, true, OWN_ENTRIES), + Served::new("FavoritesSet", cap::FAVORITES_WRITE, false, OWN_ENTRIES), + Served::new("MatchingSearch", cap::MATCHING_READ, false, CATALOG), + Served::new("MatchingAssign", cap::MATCHING_WRITE, false, OWN_ENTRIES), + Served::new("ArtworkRead", cap::ARTWORK_READ, false, OWN_ENTRIES), + Served::new("ArtworkSet", cap::ARTWORK_WRITE, false, OWN_ENTRIES), + Served::new("StorageGet", cap::STORAGE_READ, false, PRIVATE_NAMESPACE), + Served::new("StoragePut", cap::STORAGE_WRITE, false, PRIVATE_NAMESPACE), + Served::new( + "StorageDelete", + cap::STORAGE_DELETE, + false, + PRIVATE_NAMESPACE, + ), + Served::new( + "PersistenceGetUsage", + cap::STORAGE_PERSIST, + false, + PRIVATE_NAMESPACE, + ), + Served::new( + "PersistenceListEntries", + cap::STORAGE_PERSIST, + true, + PRIVATE_NAMESPACE, + ), + Served::new( + "PersistenceDeleteEntries", + cap::STORAGE_PERSIST, + false, + PRIVATE_NAMESPACE, + ), + Served::new( + "PersistenceClear", + cap::STORAGE_PERSIST, + false, + PRIVATE_NAMESPACE, + ), + Served::new( + "PersistenceSetRetentionPolicy", + cap::STORAGE_PERSIST, + false, + PRIVATE_NAMESPACE, + ), + Served::new( + "FilesRequestAccess", + cap::FILES_READ, + false, + APPROVED_FOLDERS, + ), + Served::new("FilesList", cap::FILES_READ, true, APPROVED_FOLDERS), + Served::new("FilesRead", cap::FILES_READ, false, APPROVED_FOLDERS), + Served::new("FilesWrite", cap::FILES_WRITE, false, APPROVED_FOLDERS), + Served::new("FilesDelete", cap::FILES_DELETE, false, APPROVED_FOLDERS), + Served::new("NetworkFetch", cap::NETWORK_FETCH, false, APPROVED_ORIGINS), + Served::new( + "NotificationsPublish", + cap::NOTIFICATIONS_PUBLISH, + false, + OWN_NOTICES, + ), + Served::new("GamesRequestLaunch", cap::GAME_LAUNCH, false, OWN_OR_TARGET), + Served::new( + "GamesProposeCustomLaunch", + cap::GAME_CUSTOM_LAUNCH, + false, + OWN_OR_TARGET, + ), + Served::new( + "GamesRequestCustomLaunch", + cap::GAME_CUSTOM_LAUNCH, + false, + OWN_OR_TARGET, + ), + Served::new( + "GamesRemoveCustomLaunch", + cap::GAME_CUSTOM_LAUNCH, + false, + OWN_OR_TARGET, + ), + Served::new( + "GamesRequestInstall", + cap::GAMES_INSTALL, + false, + OWN_OR_TARGET, + ), + Served::new("JobsGet", UNDERLYING, false, OWN_JOBS), + Served::new("JobsWatch", UNDERLYING, false, OWN_JOBS), + Served::new("JobsCancel", UNDERLYING, false, OWN_JOBS), + Served::new("DataPublish", cap::DATA_PUBLISH, false, DATA_SCOPE), + Served::new("DataGet", DATA_READ_SCOPE, false, DATA_SCOPE), + Served::new("DataList", DATA_READ_SCOPE, true, DATA_SCOPE), + Served::new("DataWatch", DATA_READ_SCOPE, false, DATA_SCOPE), +]; + +const OWN_OR_TARGET: &str = + "own provider entries; an extension session's selected game; needs the user's intent"; + +/// Jobs have no permission of their own: each needs the one of the operation that made it. +const UNDERLYING: &str = ""; +const OWN_JOBS: &str = "jobs this plugin started in this profile; the permission of the operation that started the job"; + +const READ_SCOPE: &str = "own provider; library.read.all for every provider"; +const OWN_ENTRIES: &str = "own provider entries"; +const CATALOG: &str = "GameNode catalog (title search)"; +const PRIVATE_NAMESPACE: &str = "own plugin/publisher/profile namespace"; +/// Runtime reads stay owner-private unless the query explicitly selects the common catalog. +const RUNTIME_READ_SCOPE: &str = + "own runtimes; granted runtime catalog category for other plugins' shared records"; +const OWN_NOTICES: &str = "plain text attributed to the calling plugin"; +const APPROVED_ORIGINS: &str = "exact HTTPS origins the user approved for this plugin"; +const APPROVED_FOLDERS: &str = "folder the user approved for this plugin and installation"; +const DATA_READ_SCOPE: &str = "authenticated owner data or explicit current sharing grants"; +const DATA_SCOPE: &str = "host-attributed dataset fields projected under current sharing policy"; + +/// The `Saves` service methods this build serves, for `DescribeApi`. +pub const SAVES_SERVED: &[Served] = saves::SERVED; + +/// The `Locations` service methods this build serves, for `DescribeApi`. +pub const LOCATIONS_SERVED: &[Served] = locations::SERVED; + +/// The `StorageDiagnostics` service methods this build serves, for `DescribeApi`. +pub const DIAGNOSTICS_SERVED: &[Served] = diagnostics::SERVED; + +/// The `Computer` service methods this build serves, for `DescribeApi`. +pub const COMPUTER_SERVED: &[Served] = observations::COMPUTER_SERVED; + +/// The `GamePresence` service methods this build serves, for `DescribeApi`. +pub const PRESENCE_SERVED: &[Served] = observations::PRESENCE_SERVED; + +/// The `GamePerformance` service methods this build serves, for `DescribeApi`. +pub const PERFORMANCE_SERVED: &[Served] = performance::SERVED; + +/// A served method's `DescribeApi` facts. +pub struct Served { + pub method: &'static str, + pub permission: &'static str, + pub paged: bool, + pub ownership: &'static str, +} + +impl Served { + const fn new( + method: &'static str, + permission: &'static str, + paged: bool, + ownership: &'static str, + ) -> Self { + Self { + method, + permission, + paged, + ownership, + } + } +} + +type BoxStream = Pin> + Send + 'static>>; + +#[derive(Clone)] +pub struct ResourceApi { + providers: ProviderApi, + library: Arc, + watches: Arc>>, + mutations: Arc, + searches: Arc, + /// Bounds the plugin pictures being decoded at once. + decoders: Arc, + /// Bounds backup/history workers, including calls that are not jobs. + backup_slots: Arc, + /// The plugins' private key/value storage. + storage: Arc, + /// File approvals and handles. + files: Arc, + /// Approved origins and limits for network fetches. + network: Arc, + /// The notifications plugins ask Core to show. + notifications: Arc, + /// The long operations plugins started. + jobs: Jobs, + /// What the user wanted to start. + intents: Arc, + /// The grants for other plugins' save profiles. + saves: Arc, + /// The content fingerprints of approved places. + snapshots: Arc, + libraries: Arc, + /// Host-owned records and policy projection boundary for domain/Data reads. + data: Arc, + /// The durable public pool; refuses durable publication when the host has no data folder. + shared_pool: Arc, + shared_authorizer: Arc, + data_cursors: Arc>>, + performance_batch_times: Arc>>, + performance_cursors: Arc>>, + /// Host-owned coordinator shared with supervised launches, when connected by the application. + leases: Arc, + /// Platform process inspection; absent in tests or unsupported builds, where checks fail + /// closed. + processes: Option>, +} + +struct DataCursorEntry { + session_id: String, + cursor: QueryCursor, + scope_hash: Option<[u8; 32]>, + expires_at: Instant, +} + +/// Unit-test and compatibility fallback: own records remain available after the endpoint's +/// session check, while foreign records are denied unless production injects the sharing store. +struct DenySharedData; + +impl Authorizer for DenySharedData { + fn revision(&self, _recipient: &super::grants::PluginIdentity) -> u64 { + 0 + } + + fn decide(&self, _request: &AccessRequest<'_>) -> AccessDecision { + AccessDecision::default() + } +} + +impl ResourceApi { + pub(crate) async fn confirm_runtime_context( + &self, + plugin_id: String, + publisher_fingerprint: String, + profile_epoch: u64, + game_id: String, + installation_id: String, + game_name: String, + ) -> Result { + use super::intents::{Binding, ConfirmationRequest, Operation, Verdict}; + let _pending = self.intents.begin_pending(&Binding { + plugin_id: plugin_id.clone(), + publisher_fingerprint: publisher_fingerprint.clone(), + profile_epoch, + game_id, + installation_id, + operation: Operation::RuntimeSessionContext, + target_revision: 0, + recipe_id: String::new(), + recipe_revision: 0, + plan_fingerprint: String::new(), + })?; + Ok(matches!( + self.intents + .confirm(ConfirmationRequest { + plugin_id, + publisher_fingerprint, + game_name, + operation: Operation::RuntimeSessionContext, + details: Vec::new(), + launch_plan: None, + }) + .await?, + Verdict::Approved { .. } + )) + } + + #[allow(clippy::too_many_arguments)] + pub fn new( + providers: ProviderApi, + library: Arc, + storage: Arc, + files: Arc, + network: Arc, + notifications: Arc, + jobs: Jobs, + intents: Arc, + saves: Arc, + snapshots: Arc, + leases: Arc, + processes: Option>, + ) -> Self { + Self { + providers, + libraries: Arc::default(), + jobs, + intents, + saves, + snapshots, + library, + storage, + files, + network, + notifications, + watches: Arc::default(), + mutations: Arc::default(), + searches: Arc::default(), + decoders: Arc::new(tokio::sync::Semaphore::new(artwork::DECODE_SLOTS)), + backup_slots: Arc::new(tokio::sync::Semaphore::new(2)), + data: Arc::new(DataBroker::new()), + shared_pool: Arc::new(DurableSharedPool::disabled()), + shared_authorizer: Arc::new(DenySharedData), + data_cursors: Arc::default(), + performance_batch_times: Arc::default(), + performance_cursors: Arc::default(), + leases, + processes, + } + } + + /// Attach the host's live sharing policy index. Production owns its persistence and passes + /// the same revisioned policy used by settings/activation reviews. + pub fn with_shared_data( + mut self, + data: Arc, + authorizer: Arc, + ) -> Self { + self.providers.set_shared_data_broker(&data); + self.data = data; + self.shared_authorizer = authorizer; + self + } + + /// Attach the host-owned durable public pool. Production supplies the application data + /// folder; without one a durable publication fails instead of falling back to the session. + pub fn with_shared_pool(mut self, pool: Arc) -> Self { + self.shared_pool = pool; + self + } + + fn scope(caller: &ResourceCaller, provider_id: &str) -> Result { + if provider_id.len() > MAX_PROVIDER_ID_BYTES { + return Err(Status::invalid_argument("provider_id is too long")); + } + Ok(Scope { + own_provider: caller.provider_id.clone(), + read_all: caller.has(cap::LIBRARY_READ_ALL), + provider_filter: (!provider_id.is_empty()).then(|| provider_id.to_owned()), + }) + } + + /// Holds one of the session's watch slots until dropped. + fn watch_slot(&self, session_id: &str) -> Result { + let mut watches = self.watches.lock().unwrap_or_else(|p| p.into_inner()); + let open = watches.entry(session_id.to_owned()).or_default(); + if *open >= MAX_WATCHES_PER_SESSION { + return Err(Status::resource_exhausted( + "too many open watches for this session", + )); + } + *open += 1; + Ok(WatchSlot { + watches: self.watches.clone(), + session_id: session_id.to_owned(), + }) + } + + fn data_identity(caller: &ResourceCaller) -> Result { + caller + .namespace + .as_ref() + .map(|namespace| namespace.identity().clone()) + .ok_or_else(|| { + Status::permission_denied( + "shared plugin data is available only to authenticated third-party plugins", + ) + }) + } + + fn take_data_cursor( + &self, + token: &str, + session_id: &str, + ) -> Result, Status> { + self.take_scoped_data_cursor(token, session_id, None) + } + + fn take_scoped_data_cursor( + &self, + token: &str, + session_id: &str, + scope_hash: Option<[u8; 32]>, + ) -> Result, Status> { + if token.is_empty() { + return Ok(None); + } + if token.len() != 48 || !token.bytes().all(|byte| byte.is_ascii_hexdigit()) { + return Err(Status::invalid_argument("invalid data cursor")); + } + let mut cursors = self + .data_cursors + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + cursors.retain(|_, entry| entry.expires_at > Instant::now()); + let Some(entry) = cursors.get(token) else { + return Err(Status::failed_precondition( + "data cursor is stale; list again", + )); + }; + if entry.session_id != session_id { + return Err(Status::invalid_argument("invalid data cursor")); + } + if entry.scope_hash != scope_hash { + return Err(Status::invalid_argument( + "data cursor belongs to another query", + )); + } + Ok(Some(entry.cursor.clone())) + } + + fn issue_data_cursor(&self, session_id: &str, cursor: QueryCursor) -> Result { + self.issue_scoped_data_cursor(session_id, cursor, None) + } + + fn issue_scoped_data_cursor( + &self, + session_id: &str, + cursor: QueryCursor, + scope_hash: Option<[u8; 32]>, + ) -> Result { + let mut cursors = self + .data_cursors + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + cursors.retain(|_, entry| entry.expires_at > Instant::now()); + if cursors.len() >= MAX_DATA_CURSORS + && let Some(oldest) = cursors + .iter() + .min_by_key(|(_, entry)| entry.expires_at) + .map(|(token, _)| token.clone()) + { + cursors.remove(&oldest); + } + let mut bytes = [0_u8; 24]; + getrandom::fill(&mut bytes) + .map_err(|_| Status::internal("no source of randomness for data cursor"))?; + let token = bytes + .iter() + .map(|byte| format!("{byte:02x}")) + .collect::(); + cursors.insert( + token.clone(), + DataCursorEntry { + session_id: session_id.to_owned(), + cursor, + scope_hash, + expires_at: Instant::now() + DATA_CURSOR_TTL, + }, + ); + Ok(token) + } +} + +struct WatchSlot { + watches: Arc>>, + session_id: String, +} + +impl Drop for WatchSlot { + fn drop(&mut self) { + let mut watches = self.watches.lock().unwrap_or_else(|p| p.into_inner()); + if let Some(open) = watches.get_mut(&self.session_id) { + *open -= 1; + if *open == 0 { + watches.remove(&self.session_id); + } + } + } +} + +/// Library projections for common-data categories (such as runtime availability) are not part +/// of this build; a query that selects one is refused rather than silently narrowed. +fn no_common_data(selector: Option<&CommonDataSelector>) -> Result<(), Status> { + match selector { + Some(selector) + if !selector.categories.is_empty() || !selector.selected_record_ids.is_empty() => + { + Err(Status::unimplemented( + "common-data projections are not available for Library", + )) + } + _ => Ok(()), + } +} + +/// Projection names a common content-availability reader may see. No path, handle, byte payload +/// or private owner key is part of it. +const LIBRARY_AVAILABILITY_FIELDS: &[&str] = &[ + "content_id", + "content_kind", + "runtime_id", + "runtime_name", + "platform", + "publisher_id", + "revision", +]; + +impl ResourceApi { + /// Returns whether this Library query explicitly selected the content-availability category + /// and is currently granted. An empty selector keeps the query owner-private. + fn shared_content_availability( + &self, + caller: &ResourceCaller, + selector: Option<&CommonDataSelector>, + ) -> Result { + let Some(selector) = selector else { + return Ok(false); + }; + if !selector.selected_record_ids.is_empty() { + return Err(Status::unimplemented( + "selected-record content availability is not available in this build", + )); + } + if selector.categories.is_empty() { + return Ok(false); + } + if selector.categories != [CommonDataCategory::ContentAvailability as i32] { + return Err(Status::unimplemented( + "common-data projections for Library support only content availability", + )); + } + let recipient = caller + .namespace + .as_ref() + .map(|namespace| namespace.identity().clone()) + .ok_or_else(|| { + Status::failed_precondition( + "a third-party plugin identity is required for shared catalog reads", + ) + })?; + let fields = LIBRARY_AVAILABILITY_FIELDS + .iter() + .map(|field| (*field).to_owned()) + .collect::>(); + if !self + .shared_authorizer + .common_category(&recipient, CommonDataCategory::ContentAvailability, &fields) + .allowed + { + return Err(Status::permission_denied( + "common content-availability access is not granted", + )); + } + Ok(true) + } + + /// Loads the safe availability projection for the requested installations and groups it by + /// installation id. `include_shared` requires a previously authorized category query. + async fn runtime_availability_map( + &self, + caller: &ResourceCaller, + include_shared: bool, + installation_ids: Vec, + ) -> Result>, Status> { + if installation_ids.is_empty() { + return Ok(HashMap::new()); + } + let Some(host) = self.library.host() else { + // Private reads keep working without a connected host; availability is additive. + if include_shared { + return Err(mutations::unavailable()); + } + return Ok(HashMap::new()); + }; + let owner = if include_shared { + None + } else { + Some(mutations::mutation_owner(caller)) + }; + let rows = host.runtime_availability(owner, installation_ids).await?; + let mut grouped: HashMap> = HashMap::new(); + for row in rows { + grouped + .entry(row.installation_id) + .or_default() + .push(RuntimeAvailability { + content_id: row.content_id, + content_kind: row.content_kind, + runtime_id: row.runtime_id, + runtime_name: row.runtime_name, + platform: row.platform, + publisher_id: row.publisher_id, + revision: row.revision, + }); + } + Ok(grouped) + } + + async fn library_event( + &self, + caller: &ResourceCaller, + include_shared: bool, + change: &Change, + ) -> Result { + Ok(LibraryEvent { + revision: change.revision, + event_type: change.kind.as_str().to_owned(), + entry: Some( + self.entry_with_availability(caller, include_shared, change.entry.to_proto()) + .await?, + ), + }) + } + + async fn entry_with_availability( + &self, + caller: &ResourceCaller, + include_shared: bool, + mut entry: LibraryEntry, + ) -> Result { + let installation_id = entry.installation_id.clone(); + let mut map = self + .runtime_availability_map(caller, include_shared, vec![installation_id.clone()]) + .await?; + entry.runtime_availability = map.remove(&installation_id).unwrap_or_default(); + Ok(entry) + } +} + +fn stale_cursor() -> Status { + Status::failed_precondition("library cursor is stale; restart the list") +} + +const MAX_DATA_VALUE_DEPTH: usize = 32; +const MAX_DATA_VALUE_ITEMS: usize = 4096; + +fn struct_to_json(value: &prost_types::Struct) -> Result, Status> { + fn convert_struct( + value: &prost_types::Struct, + depth: usize, + items: &mut usize, + ) -> Result, Status> { + if depth > MAX_DATA_VALUE_DEPTH { + return Err(Status::invalid_argument("data value is nested too deeply")); + } + let mut result = JsonMap::new(); + for (key, value) in &value.fields { + *items += 1; + if *items > MAX_DATA_VALUE_ITEMS + || key.is_empty() + || key.len() > 256 + || key.chars().any(char::is_control) + { + return Err(Status::invalid_argument( + "data value has invalid or excessive fields", + )); + } + result.insert(key.clone(), convert_value(value, depth + 1, items)?); + } + Ok(result) + } + + fn convert_value( + value: &prost_types::Value, + depth: usize, + items: &mut usize, + ) -> Result { + let kind = value + .kind + .as_ref() + .ok_or_else(|| Status::invalid_argument("data value contains an unset value"))?; + match kind { + Kind::NullValue(_) => Ok(JsonValue::Null), + Kind::NumberValue(number) => JsonNumber::from_f64(*number) + .map(JsonValue::Number) + .ok_or_else(|| Status::invalid_argument("data value contains a non-finite number")), + Kind::StringValue(value) => Ok(JsonValue::String(value.clone())), + Kind::BoolValue(value) => Ok(JsonValue::Bool(*value)), + Kind::StructValue(value) => Ok(JsonValue::Object(convert_struct(value, depth, items)?)), + Kind::ListValue(value) => { + let mut result = Vec::with_capacity(value.values.len()); + for item in &value.values { + *items += 1; + if *items > MAX_DATA_VALUE_ITEMS { + return Err(Status::invalid_argument("data value has too many items")); + } + result.push(convert_value(item, depth + 1, items)?); + } + Ok(JsonValue::Array(result)) + } + } + } + + let mut items = 0; + convert_struct(value, 1, &mut items) +} + +fn json_to_struct(value: &JsonMap) -> prost_types::Struct { + fn convert(value: &JsonValue) -> prost_types::Value { + let kind = match value { + JsonValue::Null => Kind::NullValue(0), + JsonValue::Bool(value) => Kind::BoolValue(*value), + JsonValue::Number(value) => Kind::NumberValue(value.as_f64().unwrap_or_default()), + JsonValue::String(value) => Kind::StringValue(value.clone()), + JsonValue::Array(values) => Kind::ListValue(prost_types::ListValue { + values: values.iter().map(convert).collect(), + }), + JsonValue::Object(values) => Kind::StructValue(json_to_struct(values)), + }; + prost_types::Value { kind: Some(kind) } + } + + prost_types::Struct { + fields: value + .iter() + .map(|(key, value)| (key.clone(), convert(value))) + .collect(), + } +} + +fn data_record(record: &ProjectedRecord) -> DataRecord { + DataRecord { + record_id: record.record_id().to_owned(), + dataset_id: record.dataset_id().to_owned(), + publisher_id: record.provenance().source.plugin_id.clone(), + revision: record.revision(), + value: (!record.fields().is_empty()).then(|| json_to_struct(record.fields())), + schema_id: record.schema().0.to_owned(), + schema_version: record.schema().1, + opaque_payload: record.opaque_payload().to_vec(), + provenance: Some(DataProvenance { + producer_plugin_id: record.provenance().source.plugin_id.clone(), + declared_developer: record.provenance().declared_developer.clone(), + origin: record.provenance().origin.clone(), + publisher_fingerprint: record.provenance().source.publisher_fingerprint.clone(), + package_version: record.provenance().package_version.clone(), + package_digest: record.provenance().package_digest.clone(), + resource_id: record.resource_id().to_owned(), + observed_at: record.observed_at(), + received_at: record.received_at(), + source_record_ids: record.provenance().source_record_ids.clone(), + }), + resource_id: record.resource_id().to_owned(), + observed_at: record.observed_at(), + received_at: record.received_at(), + expires_at: record.expires_at().unwrap_or_default(), + sequence: record.sequence(), + source_observation_id: record.source_observation_id().to_owned(), + durability: if record.is_durable() { + StorageDurability::Persistent as i32 + } else { + StorageDurability::SessionOnly as i32 + }, + } +} + +fn unix_now() -> Result { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_err(|_| Status::internal("system clock is before the Unix epoch"))? + .as_secs() + .try_into() + .map_err(|_| Status::internal("system clock exceeds the supported range")) +} + +fn data_broker_status(error: BrokerError) -> Status { + match &error { + BrokerError::InvalidSelector + | BrokerError::InvalidPublication + | BrokerError::ReservedField => Status::invalid_argument(error.to_string()), + BrokerError::RecordTooLarge | BrokerError::QuotaExceeded => { + Status::resource_exhausted(error.to_string()) + } + BrokerError::StaleCursor + | BrokerError::AuthorizationChanged + | BrokerError::StaleSubscription + | BrokerError::SequenceConflict(_) => Status::failed_precondition(error.to_string()), + BrokerError::WrongRecipient | BrokerError::Expired => { + Status::permission_denied(error.to_string()) + } + } +} + +#[tonic::async_trait] +impl resource_host_server::ResourceHost for ResourceApi { + type LibraryWatchStream = BoxStream; + type LibrariesWatchStream = BoxStream; + type RuntimesWatchStream = BoxStream; + type DataWatchStream = BoxStream; + type JobsWatchStream = BoxStream; + + async fn library_list( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + let page = request + .page + .ok_or_else(|| Status::invalid_argument("page is required"))?; + let caller = self + .providers + .authorize_resource(page.context.as_ref(), cap::LIBRARY_READ)?; + let include_shared = + self.shared_content_availability(&caller, page.common_data_categories.as_ref())?; + let scope = Self::scope(&caller, &request.provider_id)?; + let search = request.search.trim(); + if search.len() > MAX_SEARCH_BYTES { + return Err(Status::invalid_argument("search is too long")); + } + let search = (!search.is_empty()).then(|| search.to_owned()); + let limit = match page.page_size as usize { + 0 => DEFAULT_PAGE_SIZE, + size => size.min(MAX_PAGE_SIZE), + }; + let binding = CursorBinding { + route: "library", + session_id: caller.session_id.clone(), + profile_epoch: caller.profile_epoch, + grant_revision: caller.grant_revision, + scope, + search, + }; + let resumed = + if page.cursor.is_empty() { + None + } else { + Some(self.library.open_cursor(&page.cursor, &binding).map_err( + |error| match error { + CursorError::Malformed => { + Status::invalid_argument("invalid library cursor") + } + CursorError::Stale => stale_cursor(), + }, + )?) + }; + let (revision, entries, more) = self.library.page( + &binding.scope, + binding.search.as_deref(), + resumed.as_ref().map(|(after, _)| after.as_str()), + limit, + ); + // The page must come from the revision the cursor was issued for. + if resumed + .as_ref() + .is_some_and(|(_, issued)| *issued != revision) + { + return Err(stale_cursor()); + } + let next_cursor = match entries.last() { + Some(last) if more => { + self.library + .issue_cursor(&binding, revision, &last.installation_id) + } + _ => String::new(), + }; + let installation_ids = entries + .iter() + .map(|entry| entry.installation_id.clone()) + .collect::>(); + let mut availability = self + .runtime_availability_map(&caller, include_shared, installation_ids) + .await?; + let mut projected = Vec::with_capacity(entries.len()); + for entry in &entries { + let mut proto = entry.to_proto(); + proto.runtime_availability = availability + .remove(&entry.installation_id) + .unwrap_or_default(); + projected.push(proto); + } + Ok(Response::new(LibraryListReply { + entries: projected, + next_cursor, + revision, + })) + } + + async fn library_get( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + let caller = self + .providers + .authorize_resource(request.context.as_ref(), cap::LIBRARY_READ)?; + let include_shared = + self.shared_content_availability(&caller, request.common_data_categories.as_ref())?; + let scope = Self::scope(&caller, "")?; + let game_id = match request.game_id.as_str() { + "" => None, + text => Some( + text.parse::() + .map_err(|_| Status::invalid_argument("invalid game_id"))?, + ), + }; + let not_found = || Status::not_found("library entry not found"); + let (revision, entry) = if !request.installation_id.is_empty() { + let (revision, entry) = self.library.get(&scope, &request.installation_id); + // Naming both requires them to agree. + let entry = entry.filter(|entry| game_id.is_none() || entry.game_id == game_id); + (revision, entry.ok_or_else(not_found)?) + } else if let Some(game_id) = game_id { + let (revision, mut entries) = self.library.by_game(&scope, game_id); + match entries.len() { + 0 => return Err(not_found()), + 1 => (revision, entries.remove(0)), + _ => { + return Err(Status::failed_precondition( + "several installations match this game; name an installation_id", + )); + } + } + } else { + return Err(Status::invalid_argument( + "installation_id or game_id is required", + )); + }; + let entry = self + .entry_with_availability(&caller, include_shared, entry.to_proto()) + .await?; + Ok(Response::new(LibraryGetReply { + entry: Some(entry), + revision, + })) + } + + async fn library_watch( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + let context = request.context.clone(); + let caller = self + .providers + .authorize_resource(context.as_ref(), cap::LIBRARY_READ)?; + let include_shared = + self.shared_content_availability(&caller, request.common_data_categories.as_ref())?; + Self::scope(&caller, &request.provider_id)?; + let slot = self.watch_slot(&caller.session_id)?; + let (_, backlog, mut live) = self.library.subscribe(request.after_revision).map_err( + |error| match error { + ResumeError::Resync => Status::failed_precondition( + "watch position is no longer retained; list again and watch from its revision", + ), + ResumeError::Future => Status::out_of_range("watch position is in the future"), + }, + )?; + let (tx, rx) = mpsc::channel(WATCH_QUEUE); + let providers = self.providers.clone(); + let resource = self.clone(); + let provider_filter = request.provider_id; + let selector = request.common_data_categories; + tokio::spawn(async move { + let _slot = slot; + // Every delivery rechecks the session, profile and grants; a grant change ends the + // stream so the client lists again under its new scope. + let check = || -> Result { + let current = providers.authorize_resource(context.as_ref(), cap::LIBRARY_READ)?; + if current.grant_revision != caller.grant_revision { + return Err(Status::failed_precondition( + "plugin permissions changed; list again", + )); + } + if resource.shared_content_availability(¤t, selector.as_ref())? + != include_shared + { + return Err(Status::failed_precondition( + "common-data permissions changed; list again", + )); + } + Self::scope(¤t, &provider_filter) + }; + for change in &backlog { + let scope = match check() { + Ok(scope) => scope, + Err(status) => { + let _ = tx.send(Err(status)).await; + return; + } + }; + if !scope.admits(&change.entry) { + continue; + } + let item = resource + .library_event(&caller, include_shared, change) + .await; + if tx.send(item).await.is_err() { + return; + } + } + let mut recheck = tokio::time::interval(WATCH_RECHECK); + recheck.tick().await; + loop { + let change = tokio::select! { + received = live.recv() => match received { + Ok(change) => Some(change), + Err(broadcast::error::RecvError::Lagged(_)) => { + let _ = tx + .send(Err(Status::failed_precondition( + "library watch fell behind; list again", + ))) + .await; + return; + } + Err(broadcast::error::RecvError::Closed) => return, + }, + _ = recheck.tick() => None, + () = tx.closed() => return, + }; + let scope = match check() { + Ok(scope) => scope, + Err(status) => { + let _ = tx.send(Err(status)).await; + return; + } + }; + if let Some(change) = change.as_ref() + && scope.admits(&change.entry) + { + let item = resource + .library_event(&caller, include_shared, change) + .await; + if tx.send(item).await.is_err() { + return; + } + } + } + }); + Ok(Response::new(Box::pin(ReceiverStream::new(rx)))) + } + + async fn data_publish( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + let mutation = request + .mutation + .as_ref() + .ok_or_else(|| Status::invalid_argument("mutation is required"))?; + let context = mutation + .context + .clone() + .ok_or_else(|| Status::unauthenticated("resource context required"))?; + let (caller, _session_commit) = self + .providers + .authorize_resource_commit(&context, cap::DATA_PUBLISH) + .await?; + let owner = Self::data_identity(&caller)?; + let key = mutation_key(mutation)?; + // Published records end with this authenticated producer session, so a later session + // must not replay a receipt whose record was already purged at disconnect. + let session_key = format!("{}:{key}", caller.session_id); + if mutation.expected_revision != 0 { + return Err(Status::invalid_argument( + "data publication is append-only; expected_revision must be 0", + )); + } + let durability = StorageDurability::try_from(request.durability) + .map_err(|_| Status::invalid_argument("unknown data durability"))?; + if durability == StorageDurability::Unspecified { + return Err(Status::invalid_argument( + "data durability must be session-only or persistent", + )); + } + // A durable publication needs both grants. A missing one is an explicit failure, never + // a session-only fallback. + let persistent = durability == StorageDurability::Persistent; + if persistent && !caller.has(cap::STORAGE_PERSIST) { + return Err(Status::permission_denied( + "durable shared-data publication requires storage.persist", + )); + } + let has_opaque_payload = !request.opaque_payload.is_empty(); + if request.value.is_some() == has_opaque_payload { + return Err(Status::invalid_argument( + "provide exactly one of value or opaque_payload", + )); + } + if request + .value + .as_ref() + .is_some_and(|value| value.fields.is_empty()) + { + return Err(Status::invalid_argument( + "value must be a non-empty Struct; use opaque_payload for opaque bytes", + )); + } + let fields = request + .value + .as_ref() + .map(struct_to_json) + .transpose()? + .unwrap_or_default(); + let payload_json = if request.value.is_some() { + JsonValue::Object(fields.clone()).to_string() + } else { + String::new() + }; + let now = unix_now()?; + if request.ttl_seconds > super::shared_data::MAX_TTL_SECONDS { + return Err(Status::invalid_argument( + "ttl_seconds is outside the supported range", + )); + } + let expires_at = if request.ttl_seconds == 0 { + None + } else { + let seconds = i64::try_from(request.ttl_seconds) + .map_err(|_| Status::invalid_argument("ttl_seconds is too large"))?; + Some( + now.checked_add(seconds) + .ok_or_else(|| Status::invalid_argument("ttl_seconds is too large"))?, + ) + }; + let hash = mutations::request_hash_with_bytes( + &[ + "data.publish", + if request.value.is_some() { + "struct" + } else { + "opaque" + }, + &request.dataset_id, + &request.schema_id, + &request.schema_version.to_string(), + &request.ttl_seconds.to_string(), + &payload_json, + &request.resource_id, + &request.observed_at.to_string(), + &request.sequence.to_string(), + &request.source_observation_id, + &request.durability.to_string(), + &mutation.expected_revision.to_string(), + ], + &request.opaque_payload, + ); + + let _serial = self.mutations.lock.lock().await; + if let Some((original, expires_at)) = + self.mutations.replay_with(&caller, &session_key, hash)? + { + return Ok(Response::new(DataMutationReply { + record_id: original.resource_id, + revision: original.revision, + expires_at, + outcome: original.outcome, + durability: durability as i32, + })); + } + let current = self + .providers + .authorize_resource(Some(&context), cap::DATA_PUBLISH)?; + if current.grant_revision != caller.grant_revision { + return Err(Status::failed_precondition( + "plugin permissions changed; retry the publication", + )); + } + let publication = super::shared_data::Publication { + owner, + dataset_id: request.dataset_id, + category: None, + class: super::sharing_policy::SharingClass::Custom, + schema_id: request.schema_id, + schema_version: request.schema_version, + fields, + opaque_payload: request.opaque_payload, + resource_id: request.resource_id, + observed_at: request.observed_at, + sequence: request.sequence, + source_observation_id: request.source_observation_id, + session_id: Some(caller.session_id.clone()), + publisher: Some(super::shared_data::PublisherMetadata { + declared_developer: caller.declared_developer.clone(), + origin: caller.origin.clone(), + package_version: caller.package_version.clone(), + package_digest: caller.package_digest.clone(), + }), + expires_at, + }; + // Both modes accept the same payload, provenance and expiry. + DataBroker::validate(&publication, now).map_err(data_broker_status)?; + + let (record_id, revision, duplicate, expiry) = if persistent { + let namespace = caller.namespace.as_ref().ok_or_else(|| { + Status::permission_denied( + "shared plugin data is available only to authenticated third-party plugins", + ) + })?; + let scope = OwnerScope::new(*namespace.storage_owner().key(), caller.profile_epoch) + .map_err(|_| Status::failed_precondition("resource context is stale"))?; + let provenance = RecordProvenance { + source_plugin_id: publication.owner.plugin_id.clone(), + source_publisher_fingerprint: publication.owner.publisher_fingerprint.clone(), + source_profile_id: publication.owner.profile_id.clone(), + declared_developer: caller.declared_developer.clone(), + origin: caller.origin.clone(), + package_version: caller.package_version.clone(), + package_digest: caller.package_digest.clone(), + }; + let record = self + .shared_pool + .persist(DurableWrite { + owner: scope, + dataset_id: publication.dataset_id.clone(), + schema_id: publication.schema_id.clone(), + schema_version: publication.schema_version, + fields_json: payload_json, + opaque_payload: publication.opaque_payload.clone(), + resource_id: (!publication.resource_id.is_empty()) + .then(|| publication.resource_id.clone()), + observed_at: publication.observed_at, + sequence: publication.sequence, + source_observation_id: publication.source_observation_id.clone(), + expires_at, + now, + provenance, + }) + .await?; + let (record_id, revision, expiry) = ( + record.record_id.clone(), + record.revision, + record.expires_at.unwrap_or_default(), + ); + // The pool is the source of truth; the broker only advances its revision and tells + // current watchers, so a list revision hands off to a watch across both sources. + self.data.note_durable(record, now); + (record_id, revision, false, expiry) + } else { + let receipt = match self.data.publish(publication, now) { + Ok(receipt) => receipt, + Err(BrokerError::SequenceConflict(revision)) => { + return Ok(Response::new(DataMutationReply { + revision, + outcome: MutationOutcome::RevisionConflict as i32, + durability: durability as i32, + ..Default::default() + })); + } + Err(error) => return Err(data_broker_status(error)), + }; + ( + receipt.record_id, + receipt.revision, + receipt.duplicate, + expires_at.unwrap_or_default(), + ) + }; + let outcome = if duplicate { + MutationOutcome::AlreadyApplied + } else { + MutationOutcome::Applied + }; + let generic_reply = mutations::reply(&record_id, revision, outcome); + self.mutations + .remember_with(&caller, &session_key, hash, &generic_reply, expiry); + Ok(Response::new(DataMutationReply { + record_id, + revision, + expires_at: expiry, + outcome: outcome as i32, + durability: durability as i32, + })) + } + + async fn data_get( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + if request.dataset_id.trim().is_empty() + || request.record_id.trim().is_empty() + || request.record_id.len() > 256 + { + return Err(Status::invalid_argument( + "dataset_id and record_id are required", + )); + } + let caller = self + .providers + .authorize_resource_session(request.context.as_ref())?; + let identity = Self::data_identity(&caller)?; + // The producer may be offline: a durable record is read from the pool, while a session + // record still comes from the broker. Both pass the same grant and projection checks. + let now = unix_now()?; + let durable = self + .shared_pool + .get_any(request.record_id.clone(), now) + .await?; + let result = self + .data + .query_data_with_durable( + QueryRequest { + caller: identity, + dataset_id: request.dataset_id, + record_id: Some(request.record_id.clone()), + category: None, + selector: request.common_data_categories, + delivery: Delivery::Query, + page_size: 1, + cursor: None, + }, + durable.into_iter().collect(), + self.shared_authorizer.as_ref(), + now, + ) + .map_err(data_broker_status)?; + let record = result + .records + .into_iter() + .find(|record| record.record_id() == request.record_id) + .ok_or_else(|| Status::not_found("data record not found"))?; + Ok(Response::new(DataGetReply { + record: Some(data_record(&record)), + })) + } + + async fn data_list( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + let page = request + .page + .ok_or_else(|| Status::invalid_argument("page is required"))?; + if request.dataset_id.trim().is_empty() || request.dataset_id.len() > 256 { + return Err(Status::invalid_argument("dataset_id is invalid")); + } + if !request.filter.trim().is_empty() { + return Err(Status::invalid_argument( + "Data.List filter is not available for this schema", + )); + } + let caller = self + .providers + .authorize_resource_session(page.context.as_ref())?; + let identity = Self::data_identity(&caller)?; + let selector = match (request.common_data_categories, page.common_data_categories) { + (Some(outer), Some(inner)) if outer != inner => { + return Err(Status::invalid_argument("Data.List selectors disagree")); + } + (Some(outer), _) => Some(outer), + (_, Some(inner)) => Some(inner), + _ => None, + }; + let cursor = self.take_data_cursor(&page.cursor, &caller.session_id)?; + let page_size = match page.page_size as usize { + 0 => DEFAULT_PAGE_SIZE, + size => size.min(MAX_PAGE_SIZE), + }; + let now = unix_now()?; + // One page spans both sources, in the same receipt order, whether or not the producer is + // still connected. The persisted pool sequence seeds the broker first, so a restarted + // host hands the durable revision to a subsequent watch instead of restarting at zero. + let (durable, pool_revision) = self + .shared_pool + .list_dataset_any(request.dataset_id.clone(), now) + .await?; + self.data.observe_pool_revision(pool_revision); + let result = self + .data + .query_data_with_durable( + QueryRequest { + caller: identity, + dataset_id: request.dataset_id, + record_id: None, + category: None, + selector, + delivery: Delivery::History, + page_size, + cursor, + }, + durable, + self.shared_authorizer.as_ref(), + now, + ) + .map_err(data_broker_status)?; + let next_cursor = match result.next_cursor { + Some(cursor) => self.issue_data_cursor(&caller.session_id, cursor)?, + None => String::new(), + }; + Ok(Response::new(DataListReply { + records: result.records.iter().map(data_record).collect(), + next_cursor, + revision: result.revision, + })) + } + + async fn data_watch( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + if request.dataset_id.trim().is_empty() || request.dataset_id.len() > 256 { + return Err(Status::invalid_argument("dataset_id is invalid")); + } + let context = request.context.clone(); + let caller = self + .providers + .authorize_resource_session(context.as_ref())?; + let identity = Self::data_identity(&caller)?; + self.data.expire(unix_now()?); + // A watch positions against the persisted durable sequence, so the revision a `DataList` + // returned after a restart is accepted and an older position is rejected as stale even + // though the in-memory broker started empty. + let pool_revision = self.shared_pool.pool_revision().await?; + self.data.observe_pool_revision(pool_revision); + let subscription = self + .data + .subscribe( + QueryRequest { + caller: identity, + dataset_id: request.dataset_id, + record_id: None, + category: None, + selector: request.common_data_categories, + delivery: Delivery::Live, + page_size: DEFAULT_PAGE_SIZE, + cursor: None, + }, + request.after_revision, + WATCH_QUEUE, + self.shared_authorizer.clone(), + ) + .map_err(data_broker_status)?; + let slot = self.watch_slot(&caller.session_id)?; + let providers = self.providers.clone(); + let grant_revision = caller.grant_revision; + // Keep pending records in the broker queue until the response stream polls them. + // The broker rechecks the sharing revision when releasing each queued projection. + let stream = futures_util::stream::unfold( + Some((subscription, slot, providers, context)), + move |state| async move { + let (subscription, slot, providers, context) = state?; + loop { + let received = tokio::time::timeout( + WATCH_RECHECK, + subscription.recv(unix_now().unwrap_or(0)), + ) + .await; + match providers.authorize_resource_session(context.as_ref()) { + Ok(active) if active.grant_revision == grant_revision => {} + Ok(_) => { + return Some(( + Err(Status::failed_precondition( + "plugin permissions changed; list and watch again", + )), + None, + )); + } + Err(status) => return Some((Err(status), None)), + } + let record = match received { + Ok(Ok(Some(record))) => record, + Ok(Ok(None)) | Err(_) => continue, + Ok(Err(ended)) => { + let status = match ended { + SubscriptionEnd::Revoked => Status::failed_precondition( + "data sharing permissions changed; list and watch again", + ), + SubscriptionEnd::FellBehind => Status::resource_exhausted( + "data watch fell behind; list and watch again", + ), + }; + return Some((Err(status), None)); + } + }; + let event = DataEvent { + revision: record.revision(), + event_type: "published".into(), + record: Some(data_record(&record)), + }; + return Some((Ok(event), Some((subscription, slot, providers, context)))); + } + }, + ); + Ok(Response::new(Box::pin(stream))) + } + + async fn metadata_update( + &self, + request: Request, + ) -> Result, Status> { + self.update_metadata(request).await + } + + async fn favorites_list( + &self, + request: Request, + ) -> Result, Status> { + self.list_favorites(request).await + } + + async fn favorites_set( + &self, + request: Request, + ) -> Result, Status> { + self.set_favorite(request).await + } + + async fn matching_search( + &self, + request: Request, + ) -> Result, Status> { + self.search_catalog(request).await + } + + async fn matching_assign( + &self, + request: Request, + ) -> Result, Status> { + self.assign_match(request).await + } + + async fn artwork_read( + &self, + request: Request, + ) -> Result, Status> { + self.read_artwork(request).await + } + + async fn artwork_set( + &self, + request: Request, + ) -> Result, Status> { + self.set_artwork(request).await + } + + async fn storage_get( + &self, + request: Request, + ) -> Result, Status> { + self.get_stored(request).await + } + + async fn storage_put( + &self, + request: Request, + ) -> Result, Status> { + self.put_stored(request).await + } + + async fn storage_delete( + &self, + request: Request, + ) -> Result, Status> { + self.delete_stored(request).await + } + + async fn files_request_access( + &self, + request: Request, + ) -> Result, Status> { + self.request_files_access(request).await + } + + async fn files_list( + &self, + request: Request, + ) -> Result, Status> { + self.list_files(request).await + } + + async fn files_read( + &self, + request: Request, + ) -> Result, Status> { + self.read_file(request).await + } + + async fn files_write( + &self, + request: Request, + ) -> Result, Status> { + self.write_file(request).await + } + + async fn files_delete( + &self, + request: Request, + ) -> Result, Status> { + self.delete_file(request).await + } + + async fn network_fetch( + &self, + request: Request, + ) -> Result, Status> { + self.fetch_url(request).await + } + + async fn notifications_publish( + &self, + request: Request, + ) -> Result, Status> { + self.publish_notification(request).await + } + + async fn games_request_launch( + &self, + request: Request, + ) -> Result, Status> { + self.request_launch(request).await + } + + async fn games_propose_custom_launch( + &self, + request: Request, + ) -> Result, Status> { + self.propose_custom_launch(request).await + } + + async fn games_request_custom_launch( + &self, + request: Request, + ) -> Result, Status> { + self.request_custom_launch(request).await + } + + async fn games_remove_custom_launch( + &self, + request: Request, + ) -> Result, Status> { + self.remove_custom_launch(request).await + } + + async fn games_request_install( + &self, + request: Request, + ) -> Result, Status> { + self.request_install(request).await + } + + async fn jobs_get( + &self, + request: Request, + ) -> Result, Status> { + self.get_job(request).await + } + + async fn jobs_watch( + &self, + request: Request, + ) -> Result, Status> { + self.watch_job(request).await + } + + async fn jobs_cancel( + &self, + request: Request, + ) -> Result, Status> { + self.cancel_job(request).await + } + + async fn libraries_list( + &self, + request: Request, + ) -> Result, Status> { + self.list_libraries(request).await + } + + async fn libraries_get( + &self, + request: Request, + ) -> Result, Status> { + self.get_library(request).await + } + + async fn libraries_watch( + &self, + request: Request, + ) -> Result, Status> { + self.watch_libraries(request).await + } + + async fn libraries_create( + &self, + request: Request, + ) -> Result, Status> { + let r = request.into_inner(); + let reply = self + .edit_library(r.mutation, libraries::Edit::Create(r.name, r.description)) + .await?; + Ok(Response::new(LibraryMutationReply { + resource_id: reply.resource_id, + revision: reply.revision, + outcome: reply.outcome, + })) + } + + async fn libraries_update( + &self, + request: Request, + ) -> Result, Status> { + let r = request.into_inner(); + let reply = self + .edit_library( + r.mutation, + libraries::Edit::Update(r.library_id, r.name, r.description, r.field_mask), + ) + .await?; + Ok(Response::new(LibraryMutationReply { + resource_id: reply.resource_id, + revision: reply.revision, + outcome: reply.outcome, + })) + } + + async fn libraries_remove( + &self, + request: Request, + ) -> Result, Status> { + let r = request.into_inner(); + let reply = self + .edit_library(r.mutation, libraries::Edit::Remove(r.resource_id)) + .await?; + Ok(Response::new(reply)) + } + + async fn libraries_add_root( + &self, + request: Request, + ) -> Result, Status> { + let r = request.into_inner(); + let reply = self + .edit_library( + r.mutation, + libraries::Edit::Add( + r.library_id, + r.approved_root_handle, + r.display_name, + r.declared_locations, + ), + ) + .await?; + Ok(Response::new(LibraryMutationReply { + resource_id: reply.resource_id, + revision: reply.revision, + outcome: reply.outcome, + })) + } + + async fn libraries_update_root( + &self, + request: Request, + ) -> Result, Status> { + let r = request.into_inner(); + let reply = self + .edit_library( + r.mutation, + libraries::Edit::Root( + r.library_id, + r.root_id, + r.approved_root_handle, + r.display_name, + r.declared_locations, + r.field_mask, + r.watching, + ), + ) + .await?; + Ok(Response::new(LibraryMutationReply { + resource_id: reply.resource_id, + revision: reply.revision, + outcome: reply.outcome, + })) + } + + async fn libraries_remove_root( + &self, + request: Request, + ) -> Result, Status> { + let r = request.into_inner(); + let reply = self + .edit_library( + r.mutation, + libraries::Edit::RemoveRoot(r.library_id, r.root_id), + ) + .await?; + Ok(Response::new(reply)) + } + + async fn backups_list( + &self, + request: Request, + ) -> Result, Status> { + self.list_backups(request).await + } + async fn backups_request_create( + &self, + request: Request, + ) -> Result, Status> { + self.create_backup(request).await + } + async fn backups_request_restore( + &self, + request: Request, + ) -> Result, Status> { + self.restore_backup(request).await + } + + async fn tools_list( + &self, + request: Request, + ) -> Result, Status> { + self.list_tools(request).await + } + async fn tools_request_apply( + &self, + request: Request, + ) -> Result, Status> { + let r = request.into_inner(); + self.request_tool_action(r.mutation, r.tool_id, r.game_id, r.user_intent_id, false) + .await + } + async fn tools_request_remove( + &self, + request: Request, + ) -> Result, Status> { + let r = request.into_inner(); + self.request_tool_action(r.mutation, r.tool_id, r.game_id, r.user_intent_id, true) + .await + } + async fn ports_list( + &self, + request: Request, + ) -> Result, Status> { + self.list_ports(request).await + } + async fn ports_detail( + &self, + request: Request, + ) -> Result, Status> { + self.detail_port(request).await + } + async fn ports_request_install( + &self, + request: Request, + ) -> Result, Status> { + self.install_port(request).await + } + async fn runtimes_list( + &self, + request: Request, + ) -> Result, Status> { + self.list_runtimes(request).await + } + async fn runtimes_get( + &self, + request: Request, + ) -> Result, Status> { + self.get_runtime(request).await + } + async fn runtimes_watch( + &self, + request: Request, + ) -> Result, Status> { + self.watch_runtimes(request).await + } + async fn runtimes_register( + &self, + request: Request, + ) -> Result, Status> { + self.register_runtime(request).await + } + async fn runtimes_request_access( + &self, + request: Request, + ) -> Result, Status> { + self.request_runtime_access(request).await + } + async fn runtimes_update( + &self, + request: Request, + ) -> Result, Status> { + self.update_runtime(request).await + } + async fn runtimes_remove( + &self, + request: Request, + ) -> Result, Status> { + self.remove_runtime(request).await + } + async fn games_register_content( + &self, + request: Request, + ) -> Result, Status> { + self.register_content(request).await + } + async fn storage_diagnostics_publish_benchmark( + &self, + request: Request, + ) -> Result, Status> { + self.publish_benchmark(request).await + } + async fn storage_diagnostics_publish_smart( + &self, + request: Request, + ) -> Result, Status> { + self.publish_smart(request).await + } + async fn computer_publish_hardware( + &self, + request: Request, + ) -> Result, Status> { + self.publish_hardware(request).await + } + async fn game_presence_publish( + &self, + request: Request, + ) -> Result, Status> { + self.publish_presence(request).await + } + async fn game_presence_clear( + &self, + request: Request, + ) -> Result, Status> { + self.clear_presence(request).await + } + async fn game_performance_publish_samples( + &self, + request: Request, + ) -> Result, Status> { + self.publish_performance_samples(request).await + } + async fn game_performance_end_series( + &self, + request: Request, + ) -> Result, Status> { + self.end_performance_series(request).await + } + async fn persistence_get_usage( + &self, + request: Request, + ) -> Result, Status> { + self.persistence_usage(request).await + } + async fn persistence_list_entries( + &self, + request: Request, + ) -> Result, Status> { + self.persistence_list(request).await + } + async fn persistence_delete_entries( + &self, + request: Request, + ) -> Result, Status> { + self.persistence_delete(request).await + } + async fn persistence_clear( + &self, + request: Request, + ) -> Result, Status> { + self.persistence_clear_entries(request).await + } + async fn persistence_set_retention_policy( + &self, + request: Request, + ) -> Result, Status> { + self.persistence_set_policy(request).await + } +} + +#[cfg(all(test, unix))] +mod tests; diff --git a/crates/app/src/plugin_host/resources/artwork.rs b/crates/app/src/plugin_host/resources/artwork.rs new file mode 100644 index 000000000..78a04cae3 --- /dev/null +++ b/crates/app/src/plugin_host/resources/artwork.rs @@ -0,0 +1,254 @@ +//! Cover read and set of `ResourceHost`. +//! +//! A plugin may set the cover of one of its own library entries, never anyone else's and never +//! the matched game's shared cover: the host keeps the image as an override for that entry +//! (`LibraryEntry.artwork_revision` counts its writes) and an empty `encoded_image` restores the +//! game's cover. The bytes are untrusted, so they are bounded before anything touches them and +//! then decoded, shrunk and re-encoded on a blocking worker (`gamenode_platform::plugin_artwork`): +//! the host stores its own re-encoded picture, never the plugin's file. Reads return the cover +//! the entry shows, already on this device, within the caller's byte budget. + +use std::sync::Arc; + +use gamenode_core::library::ArtworkWrite; +use gamenode_platform::plugin_artwork::{self, ArtworkError, Prepared}; +use gamenode_plugin_protocol::{capability as cap, proto::*}; +use sha2::{Digest, Sha256}; +use tonic::{Request, Response, Status}; + +use super::mutations::{game_id, mutation_key, reply, request_hash, unavailable}; +use super::{ResourceApi, Scope}; +use crate::plugin_host::library::Projected; +use crate::plugin_host::provider::ResourceCaller; + +/// The only artwork kind: the cover shown for a library entry. +pub const COVER: &str = "cover"; +/// The most a read returns. The covers the host downloads are capped at 5 MiB. +pub(super) const MAX_READ_BYTES: u64 = 5 * 1024 * 1024; +const MAX_INSTALLATION_ID_BYTES: usize = 128; +/// Images decoded at once. A decode may hold ~128 MiB, so two is the most memory the host +/// will spend on plugin pictures at any moment. +pub(super) const DECODE_SLOTS: usize = 2; + +fn kind(artwork_kind: &str) -> Result<(), Status> { + if artwork_kind.is_empty() || artwork_kind == COVER { + Ok(()) + } else { + Err(Status::invalid_argument( + "artwork_kind must be \"cover\" (or empty)", + )) + } +} + +fn installation(id: &str) -> Result<(), Status> { + if id.is_empty() { + return Err(Status::invalid_argument("installation_id is required")); + } + if id.len() > MAX_INSTALLATION_ID_BYTES { + return Err(Status::invalid_argument("installation_id is too long")); + } + Ok(()) +} + +fn refused(error: ArtworkError) -> Status { + Status::invalid_argument(error.to_string()) +} + +impl ResourceApi { + /// The caller's own entry named by `installation_id`, optionally also required to be + /// matched to `expected_game`. Foreign and unknown entries are the same `NOT_FOUND`. + pub(super) fn own_entry( + &self, + caller: &ResourceCaller, + installation_id: &str, + expected_game: Option, + ) -> Result<(String, Projected), Status> { + let own = Scope { + own_provider: caller.provider_id.clone(), + read_all: false, + provider_filter: None, + }; + self.library + .target(&own, installation_id) + .filter(|(_, entry)| expected_game.is_none() || entry.game_id == expected_game) + .ok_or_else(|| Status::not_found("library entry not found")) + } + + pub(super) async fn read_artwork( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + let caller = self + .providers + .authorize_resource(request.context.as_ref(), cap::ARTWORK_READ)?; + kind(&request.artwork_kind)?; + installation(&request.installation_id)?; + let expected_game = game_id(&request.game_id)?; + let budget = match request.max_bytes { + 0 => MAX_READ_BYTES, + bytes => bytes.min(MAX_READ_BYTES), + }; + let (entry_key, _) = self.own_entry(&caller, &request.installation_id, expected_game)?; + let host = self.library.host().ok_or_else(unavailable)?; + let cover = host.read_artwork(entry_key, budget).await?; + // The bytes were read for a call that may since have lost its permission. + self.providers + .authorize_resource(request.context.as_ref(), cap::ARTWORK_READ)?; + Ok(Response::new(ArtworkReadReply { + byte_length: cover.bytes.len() as u64, + encoded_image: cover.bytes, + media_type: cover.media_type.to_owned(), + revision: cover.revision, + })) + } + + pub(super) async fn set_artwork( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + let mutation = request + .mutation + .as_ref() + .ok_or_else(|| Status::invalid_argument("mutation is required"))?; + let caller = self + .providers + .authorize_resource(mutation.context.as_ref(), cap::ARTWORK_WRITE)?; + let key = mutation_key(mutation)?; + kind(&request.artwork_kind)?; + installation(&request.installation_id)?; + let expected_game = game_id(&request.game_id)?; + let by_handle = !request.file_handle.is_empty(); + if by_handle && !request.encoded_image.is_empty() { + return Err(Status::invalid_argument( + "give either encoded_image or file_handle, not both", + )); + } + if by_handle && request.media_type.trim().is_empty() { + return Err(Status::invalid_argument( + "media_type is required with a file_handle", + )); + } + // A picture read from a file needs the right to read files besides the right to write + // covers; without it nothing is looked at. + if by_handle { + self.providers + .authorize_resource(mutation.context.as_ref(), cap::FILES_READ)?; + } + let clearing = request.encoded_image.is_empty() && !by_handle; + if clearing && !request.media_type.is_empty() { + return Err(Status::invalid_argument( + "media_type must be empty when encoded_image is empty (restoring the game's cover)", + )); + } + if request.encoded_image.len() > plugin_artwork::MAX_INPUT_BYTES { + return Err(refused(ArtworkError::TooLarge)); + } + let content = if clearing { + "\u{0}".to_owned() + } else if by_handle { + // The bytes are not known until the file is read, and a retry must be answered before + // that: the request is the handle and the declared type. + format!( + "handle|{}|{}", + request.file_handle, + request.media_type.trim().to_ascii_lowercase() + ) + } else { + format!( + "{:x}|{}", + Sha256::digest(&request.encoded_image), + request.media_type.trim().to_ascii_lowercase() + ) + }; + let hash = request_hash(&[ + "artwork", + &request.installation_id, + &request.game_id, + &mutation.expected_revision.to_string(), + &content, + ]); + + // A retried call is answered before spending any work on its bytes. + if let Some(original) = self.mutations.replay(&caller, key, hash)? { + return Ok(Response::new(original)); + } + // Nothing is decoded for an entry the caller does not own. + self.own_entry(&caller, &request.installation_id, expected_game)?; + let prepared = if clearing { + None + } else { + let bytes = if by_handle { + let bytes = self + .read_handle_image( + &caller, + &request.file_handle, + &request.installation_id, + plugin_artwork::MAX_INPUT_BYTES, + ) + .await?; + if bytes.len() > plugin_artwork::MAX_INPUT_BYTES { + return Err(refused(ArtworkError::TooLarge)); + } + // The file was read for a call that may since have lost its permission. + self.providers + .authorize_resource(mutation.context.as_ref(), cap::FILES_READ)?; + bytes + } else { + request.encoded_image + }; + Some(self.prepare_image(bytes, request.media_type).await?) + }; + + let _serial = self.mutations.lock.lock().await; + if let Some(original) = self.mutations.replay(&caller, key, hash)? { + return Ok(Response::new(original)); + } + let (entry_key, entry) = + self.own_entry(&caller, &request.installation_id, expected_game)?; + let host = self.library.host().ok_or_else(unavailable)?; + let context = mutation.context.clone().unwrap_or_default(); + let write_guard = self.guard(context.clone(), cap::ARTWORK_WRITE, caller.grant_revision); + let guard: crate::plugin_host::library::CommitGuard = if by_handle { + // The permission that was lost is named first, rather than "permissions changed". + let read_guard = self.guard(context, cap::FILES_READ, caller.grant_revision); + Box::new(move || { + read_guard()?; + write_guard() + }) + } else { + write_guard + }; + let (outcome, revision, commit) = match host + .set_artwork(entry_key, mutation.expected_revision, prepared, guard) + .await? + { + ArtworkWrite::Applied { revision, .. } => (MutationOutcome::Applied, revision, true), + ArtworkWrite::Unchanged { revision } => { + (MutationOutcome::AlreadyApplied, revision, true) + } + ArtworkWrite::Conflict { current } => { + (MutationOutcome::RevisionConflict, current, false) + } + }; + let answer = reply(&entry.installation_id, revision, outcome); + if commit { + self.mutations.remember(&caller, key, hash, &answer); + } + Ok(Response::new(answer)) + } + + /// Decodes, shrinks and re-encodes `bytes` on a blocking worker, at most + /// [`DECODE_SLOTS`] at a time. + async fn prepare_image(&self, bytes: Vec, media_type: String) -> Result { + let _slot = Arc::clone(&self.decoders) + .acquire_owned() + .await + .map_err(|_| unavailable())?; + tokio::task::spawn_blocking(move || plugin_artwork::prepare(&bytes, &media_type)) + .await + .map_err(|_| Status::internal("the image could not be processed"))? + .map_err(refused) + } +} diff --git a/crates/app/src/plugin_host/resources/backups.rs b/crates/app/src/plugin_host/resources/backups.rs new file mode 100644 index 000000000..b059ecb4b --- /dev/null +++ b/crates/app/src/plugin_host/resources/backups.rs @@ -0,0 +1,1183 @@ +//! Approved-profile backups. Paths and archive selectors are resolved by Core, never plugins. +use super::files::{open_approval_inspect, root_of}; +use super::mutations::{mutation_key, request_hash}; +use super::*; +use crate::plugin_host::intents::{Binding, ConfirmationRequest, Operation, Verdict}; +use crate::plugin_host::jobs::{Fence, JobOwner, Outcome, work}; +use crate::plugin_host::resource_leases::ResourceLease; +use crate::plugin_host::saves::{self, Directory}; +use crate::plugin_host::shared_resources::{self, ExternalUse, RuntimeUseCheck}; +use gamenode_core::drm_free::{self as domain, BackupAuthority, BackupOperation}; +use gamenode_platform::plugin_files::{ApprovedRoot, Budget, Confined}; +use gamenode_platform::plugin_storage::SaveProfileRow; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use std::collections::BTreeSet; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::Instant; + +const MAX_FILES: usize = 1000; +const MAX_VISITED: usize = 10_000; + +#[derive(Clone, PartialEq, Eq)] +struct Folder { + directory: Directory, + root: ApprovedRoot, + volume_token: String, +} +#[derive(Clone, PartialEq, Eq)] +struct Frozen { + profile: SaveProfileRow, + folders: Vec, + entry_key: String, + entry_revision: u64, + game_name: String, +} +#[derive(Clone, Serialize, Deserialize)] +struct Archive { + destination: String, + backup: String, +} + +struct CancelWorker(Option>); +impl Drop for CancelWorker { + fn drop(&mut self) { + if let Some(cancelled) = &self.0 { + cancelled.store(true, Ordering::Relaxed); + } + } +} + +async fn decode_report(json: String) -> Result { + tokio::task::spawn_blocking(move || { + serde_json::from_str(&json).map_err(|_| Status::unavailable("invalid backup engine report")) + }) + .await + .map_err(|_| Status::unavailable("backup report worker failed"))? +} + +fn unavailable() -> Status { + Status::unavailable("backups are unavailable for this context or platform") +} +fn not_found() -> Status { + Status::not_found("backup profile or snapshot not found") +} +fn local(_: impl std::fmt::Display) -> domain::LocalError { + domain::LocalError::Failed("backup scope is no longer available".into()) +} +fn status(error: domain::LocalError) -> Status { + match error { + domain::LocalError::Unsupported => unavailable(), + domain::LocalError::Busy => Status::failed_precondition("backup engine is busy"), + domain::LocalError::Cancelled => Status::cancelled("backup cancelled"), + domain::LocalError::InvalidTarget => Status::failed_precondition("invalid backup target"), + domain::LocalError::Failed(_) => { + Status::failed_precondition("backup engine failed; no successful result is claimed") + } + } +} +fn hex(bytes: impl AsRef<[u8]>) -> String { + bytes.as_ref().iter().map(|b| format!("{b:02x}")).collect() +} +fn identifier(id: &str) -> Result<(), Status> { + if id.is_empty() || id.len() > 128 || id.chars().any(char::is_control) { + return Err(Status::invalid_argument( + "profile_id is required: 1 to 128 bytes", + )); + } + Ok(()) +} + +impl Folder { + fn open( + &self, + reserved: &gamenode_platform::plugin_files::Reserved, + ) -> Result { + let info = gamenode_platform::volume::volume_info(&self.root.path) + .ok_or_else(|| local("volume"))?; + if self.volume_token.is_empty() || info.volume_identity_token != self.volume_token { + return Err(local("volume changed")); + } + let confined = Confined::open(&self.root, reserved).map_err(local)?; + if !confined + .stat(&self.directory.path) + .map_err(local)? + .directory + { + return Err(local("not a folder")); + } + Ok(confined) + } + fn base(&self) -> PathBuf { + self.directory + .path + .iter() + .fold(self.root.path.clone(), |p, name| p.join(name)) + } +} + +struct Authority { + api: ResourceApi, + caller: ResourceCaller, + context: ServiceContext, + permission: &'static str, + frozen: Frozen, + checkpoint: Fence, + reviewed_targets: Option>, + /// Rechecks the approved runtime's externally observed process state before file access. + runtime_check: Option, +} +impl BackupAuthority for Authority { + fn check(&self) -> Result<(), domain::LocalError> { + if let Some(check) = &self.runtime_check { + match check.inspect() { + ExternalUse::Idle => {} + ExternalUse::Active => return Err(domain::LocalError::Busy), + ExternalUse::Unknown => { + return Err(domain::LocalError::Failed( + "external runtime use cannot be verified".into(), + )); + } + } + } + (self.checkpoint)().map_err(|e| { + if e.code() == tonic::Code::Cancelled { + domain::LocalError::Cancelled + } else { + local(e) + } + })?; + let current = self + .api + .providers + .authorize_resource(Some(&self.context), self.permission) + .map_err(local)?; + if current.grant_revision != self.caller.grant_revision { + return Err(local("grants changed")); + } + let actual = self + .api + .storage + .on_backup_worker(&self.caller, |namespace| { + self.api.freeze_in( + namespace, + &self.frozen.profile.id, + &self.frozen.entry_key, + self.frozen.entry_revision, + ) + }) + .map_err(local)?; + if actual != self.frozen { + return Err(local("profile or approval changed")); + } + if self.api.library.revision_of(&self.frozen.entry_key) != Some(self.frozen.entry_revision) + { + return Err(local("installation changed")); + } + Ok(()) + } + fn validate_targets( + &self, + files: &[String], + registry: &[String], + ) -> Result<(), domain::LocalError> { + self.check()?; + if !registry.is_empty() || files.len() > MAX_FILES { + return Err(domain::LocalError::InvalidTarget); + } + if let Some(reviewed) = &self.reviewed_targets { + let mut actual = files.to_vec(); + actual.sort(); + let mut expected = reviewed.clone(); + expected.sort(); + if actual.iter().any(|path| !expected.contains(path)) { + return Err(domain::LocalError::InvalidTarget); + } + } + for file in files { + let path = Path::new(file); + let mut accepted = false; + for folder in &self.frozen.folders { + let Ok(relative) = path.strip_prefix(folder.base()) else { + continue; + }; + let components = relative + .components() + .map(|c| match c { + std::path::Component::Normal(name) => name.to_str().map(str::to_owned), + _ => None, + }) + .collect::>>() + .ok_or(domain::LocalError::InvalidTarget)?; + if components.is_empty() + || !saves::selected(&folder.directory.naming_patterns, &components) + { + continue; + } + // Check existing ancestors without following links. A missing leaf can be restored, + // but an unavailable/replaced approval or a symlink cannot become a destination. + let confined = folder.open(&self.api.files.reserved)?; + let mut current = folder.directory.path.clone(); + for (index, component) in components.iter().enumerate() { + if !gamenode_platform::plugin_files::valid_component(component) { + return Err(domain::LocalError::InvalidTarget); + } + current.push(component.clone()); + match confined.stat(¤t) { + Ok(entry) if index + 1 < components.len() && !entry.directory => { + return Err(domain::LocalError::InvalidTarget); + } + Ok(_) => {} + Err(gamenode_platform::plugin_files::FileError::NotFound) => break, + Err(error) => return Err(local(error)), + } + } + accepted = true; + break; + } + if !accepted { + return Err(domain::LocalError::InvalidTarget); + } + } + Ok(()) + } +} + +impl ResourceApi { + fn freeze_in( + &self, + namespace: &mut crate::plugin_host::storage::Namespace<'_>, + profile_id: &str, + entry_key: &str, + entry_revision: u64, + ) -> Result { + let profile = namespace.save_profile(profile_id)?.ok_or_else(not_found)?; + let (_, entry) = self + .library + .target( + &Scope { + own_provider: String::new(), + read_all: true, + provider_filter: None, + }, + &profile.installation_id, + ) + .filter(|(key, entry)| key == entry_key && entry.revision == entry_revision) + .ok_or_else(|| Status::aborted("backup installation changed"))?; + let game_name = entry.display_name.unwrap_or(entry.name); + let directories = saves::directories_from_json(&profile.directories); + if directories.is_empty() { + return Err(Status::failed_precondition( + "profile has no approved folders", + )); + } + let mut folders = vec![]; + for directory in directories { + let opened = open_approval_inspect( + &self.files, + &self.library, + namespace, + &directory.approval_id, + directory.path.clone(), + )? + .map_err(|_| Status::failed_precondition("approved save folder unavailable"))?; + if opened.approval.installation_id != profile.installation_id { + return Err(not_found()); + } + if !opened + .confined + .stat(&directory.path) + .map_err(|_| not_found())? + .directory + { + return Err(not_found()); + } + folders.push(Folder { + root: root_of(&opened.approval), + volume_token: opened.approval.volume_token, + directory, + }); + } + Ok(Frozen { + profile, + folders, + entry_key: entry_key.into(), + entry_revision, + game_name, + }) + } + + async fn backup_scope( + &self, + context: &ServiceContext, + permission: &'static str, + profile: &str, + game: &str, + ) -> Result<(ResourceCaller, Frozen), Status> { + let caller = self + .providers + .authorize_resource(Some(context), permission)?; + identifier(profile)?; + let id = profile.to_owned(); + let row = self + .in_namespace(&caller, move |n| n.save_profile(&id)?.ok_or_else(not_found)) + .await?; + let wanted = super::mutations::game_id(game)?; + if wanted.is_some_and(|id| row.game_id != id.to_string()) { + return Err(not_found()); + } + let (entry_key, entry) = self.action_target(&caller, context, "", &row.installation_id)?; + let api = self.clone(); + let frozen = self + .in_namespace(&caller, move |n| { + api.freeze_in(n, &row.id, &entry_key, entry.revision) + }) + .await?; + Ok((caller, frozen)) + } + + /// Resolves the approved runtime identity and shared-resource leases for an operation that + /// writes or restores files. Unknown external process state fails closed. + async fn shared_use( + &self, + caller: &ResourceCaller, + frozen: &Frozen, + ) -> Result<(Option>, Option), Status> { + let declarations = shared_resources::resources_from_json(&frozen.profile.shared_resources); + if frozen.profile.runtime_id.is_empty() { + if !declarations.is_empty() { + return Err(Status::failed_precondition( + "the shared resource has no approved runtime binding", + )); + } + return Ok((None, None)); + } + let executable = self + .resolve_runtime_executable(caller, &frozen.profile.runtime_id) + .await?; + let check = RuntimeUseCheck { + executable, + processes: self.processes.clone(), + }; + match check.inspect() { + ExternalUse::Idle => {} + ExternalUse::Active => { + return Err(Status::failed_precondition( + "the approved runtime is running; stop it before backing up or restoring", + )); + } + ExternalUse::Unknown => { + return Err(Status::unavailable( + "external runtime use cannot be verified; the operation is refused", + )); + } + } + let files = self.files.clone(); + let feed = self.library.clone(); + let profile = frozen.profile.clone(); + let prepared = self + .in_namespace(caller, move |namespace| { + shared_resources::prepare_for_use(&files, &feed, namespace, &profile) + }) + .await?; + let keys = prepared + .iter() + .map(|resource| resource.lease_key) + .collect::>(); + let lease = if keys.is_empty() { + None + } else { + Some( + self.leases + .lease_exclusive(&keys) + .map_err(|error| match error { + crate::plugin_host::resource_leases::ResourceLeaseError::Busy => { + Status::failed_precondition("a shared save resource is in use") + } + crate::plugin_host::resource_leases::ResourceLeaseError::Unknown => { + Status::unavailable("shared save resource use cannot be confirmed") + } + })?, + ) + }; + Ok((lease, Some(check))) + } + + async fn backup_request( + &self, + frozen: &Frozen, + caller: &ResourceCaller, + operation: BackupOperation, + destination: Option, + exclusive: bool, + ) -> Result< + ( + Arc, + domain::ScopedBackupRequest, + Option>, + Option, + ), + Status, + > { + let host = self.library.host().ok_or_else(unavailable)?; + let mut context = host.backup_context(frozen.entry_key.clone()).await?; + if !context.engine.scoped_available() { + return Err(unavailable()); + } + let (lease, runtime_check) = if exclusive { + self.shared_use(caller, frozen).await? + } else { + (None, None) + }; + context.target.installation_id = + hex(Sha256::digest(frozen.profile.installation_id.as_bytes())); + let owner = hex(caller + .namespace + .as_ref() + .ok_or_else(unavailable)? + .storage_owner() + .key()); + let profile = domain::SaveProfile { + id: frozen.profile.id.clone(), + installation: frozen.profile.installation_id.clone(), + revision: frozen.profile.revision, + title: frozen.profile.id.clone(), + manifest_hash: frozen.profile.revision.to_string(), + definition: "{files: {}}".into(), + files: vec![], + registry: vec![], + support: domain::SaveSupport::Supported, + automatic: Some(false), + retention: None, + }; + let destination = destination.unwrap_or(context.destination); + let protected = frozen + .folders + .iter() + .map(Folder::base) + .chain(std::iter::once(PathBuf::from(&context.target.root))) + .collect::>(); + let chosen = destination.clone(); + tokio::task::spawn_blocking(move || { + gamenode_platform::backups::validate_destination(Path::new(&chosen), &protected) + }) + .await + .map_err(|_| unavailable())? + .map_err(status)?; + Ok(( + context.engine, + domain::ScopedBackupRequest { + owner, + target: context.target, + profile, + job_id: None, + destination, + operation, + }, + lease, + runtime_check, + )) + } + + async fn execute_backup( + &self, + engine: Arc, + mut request: domain::ScopedBackupRequest, + authority: Authority, + cancelled: Arc, + ) -> Result { + let slot = + self.backup_slots.clone().try_acquire_owned().map_err(|_| { + Status::resource_exhausted("backup workers are busy; try again later") + })?; + let mut cancel_on_drop = CancelWorker(Some(cancelled.clone())); + let result = tokio::task::spawn_blocking(move || { + let _slot = slot; + authority.check().map_err(status)?; + let protected = authority + .frozen + .folders + .iter() + .map(Folder::base) + .chain(std::iter::once(PathBuf::from(&request.target.root))) + .collect::>(); + gamenode_platform::backups::validate_destination( + Path::new(&request.destination), + &protected, + ) + .map_err(status)?; + if matches!(request.operation, BackupOperation::Backup) { + let mut selected = BTreeSet::new(); + let deadline = Instant::now() + Duration::from_secs(5); + let mut visited = 0; + for folder in &authority.frozen.folders { + let confined = folder.open(&authority.api.files.reserved).map_err(status)?; + let budget = Budget { + max_entries: MAX_VISITED.saturating_sub(visited), + deadline, + cancel: &cancelled, + }; + let mut too_many = false; + let walk = confined + .walk_tree(&folder.directory.path, &budget, &mut |path, entry| { + visited += 1; + if (authority.checkpoint)().is_err() { + cancelled.store(true, Ordering::Relaxed); + return; + } + if !entry.directory + && saves::selected( + &folder.directory.naming_patterns, + &path[folder.directory.path.len()..], + ) + { + let path = path + .iter() + .fold(folder.root.path.clone(), |p, part| p.join(part)); + let path = path.to_string_lossy().into_owned(); + if selected.len() >= MAX_FILES && !selected.contains(&path) { + too_many = true; + return; + } + selected.insert(path); + } + }) + .map_err(|_| Status::failed_precondition("save enumeration failed"))?; + if cancelled.load(Ordering::Relaxed) { + return Err(Status::cancelled("backup cancelled")); + } + if too_many || !walk.complete { + return Err(Status::resource_exhausted( + "save selection exceeded its file, entry or time budget", + )); + } + } + let files = selected.into_iter().collect::>(); + authority.validate_targets(&files, &[]).map_err(status)?; + let definitions = files + .iter() + .map(|p| { + ( + gamenode_platform::backups::glob_literal(p), + serde_json::json!({}), + ) + }) + .collect::>(); + request.profile.files = files; + request.profile.definition = + serde_json::json!({"files":definitions,"registry":{}}).to_string(); + } + engine + .execute_scoped(&request, &cancelled, &authority) + .map_err(status) + }) + .await + .map_err(|_| Status::unavailable("backup worker failed"))?; + cancel_on_drop.0 = None; + result + } + + fn backup_authority( + &self, + caller: &ResourceCaller, + context: &ServiceContext, + permission: &'static str, + frozen: &Frozen, + checkpoint: Fence, + ) -> Authority { + Authority { + api: self.clone(), + caller: caller.clone(), + context: context.clone(), + permission, + frozen: frozen.clone(), + checkpoint, + reviewed_targets: None, + runtime_check: None, + } + } + + pub(super) async fn list_backups( + &self, + request: Request, + ) -> Result, Status> { + tokio::time::timeout(Duration::from_secs(30), self.list_backup_history(request)) + .await + .map_err(|_| Status::deadline_exceeded("backup history deadline exceeded"))? + } + + async fn list_backup_history( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + let page = request.page.unwrap_or_default(); + let context = page.context.clone().unwrap_or_default(); + let (caller, frozen) = self + .backup_scope( + &context, + cap::BACKUPS_READ, + &request.profile_id, + &request.game_id, + ) + .await?; + no_common_data(page.common_data_categories.as_ref())?; + let (engine, template, _, _) = self + .backup_request(&frozen, &caller, BackupOperation::History, None, false) + .await?; + let id = frozen.profile.id.clone(); + let mut sources = self + .in_namespace(&caller, move |n| n.backup_sources(&id)) + .await?; + if !sources.contains(&template.destination) { + sources.push(template.destination.clone()); + } + let mut records = vec![]; + let mut history_binding = vec![]; + let check: Fence = Arc::new(|| Ok(())); + for destination in sources { + let mut operation = template.clone(); + operation.destination = destination.clone(); + let authority = + self.backup_authority(&caller, &context, cap::BACKUPS_READ, &frozen, check.clone()); + let report = self + .execute_backup( + engine.clone(), + operation, + authority, + Arc::new(AtomicBool::new(false)), + ) + .await?; + if report.state == domain::JobState::Partial { + return Err(Status::failed_precondition("backup history is incomplete")); + } + let json = decode_report(report.json).await?; + let backups = json + .get("games") + .and_then(|g| g.get(&template.profile.title)) + .and_then(|g| g.get("backups")) + .and_then(serde_json::Value::as_array); + if let Some(backups) = backups { + if backups.len() > 100 { + return Err(Status::resource_exhausted("backup history limit exceeded")); + } + for item in backups { + let backup = item + .get("name") + .and_then(serde_json::Value::as_str) + .filter(|s| !s.is_empty() && s.len() <= 256) + .ok_or_else(|| Status::unavailable("invalid snapshot identity"))?; + let archive = Archive { + destination: destination.clone(), + backup: backup.into(), + }; + history_binding.push(format!( + "{}:{}", + serde_json::to_string(&archive).map_err(|_| unavailable())?, + item.get("when") + .and_then(serde_json::Value::as_str) + .unwrap_or("") + )); + let binding = + format!("backup:{}:{}", frozen.profile.id, frozen.profile.revision); + let backup_id = self.files.seal_cursor( + &caller.session_id, + &binding, + &serde_json::to_string(&archive).map_err(|_| unavailable())?, + ); + let mut preview_request = template.clone(); + preview_request.destination = destination.clone(); + preview_request.operation = BackupOperation::RestorePreview { + backup: backup.into(), + }; + let authority = self.backup_authority( + &caller, + &context, + cap::BACKUPS_READ, + &frozen, + check.clone(), + ); + let preview = self + .execute_backup( + engine.clone(), + preview_request, + authority, + Arc::new(AtomicBool::new(false)), + ) + .await?; + let preview_json = decode_report(preview.json).await?; + let size_bytes = item + .get("size_bytes") + .and_then(serde_json::Value::as_u64) + .or_else(|| { + preview_json + .pointer("/overall/totalBytes") + .and_then(serde_json::Value::as_u64) + }) + .unwrap_or(0); + history_binding.push(format!("{size_bytes}:{:?}", preview.state)); + records.push(BackupRecord { + backup_id, + game_id: frozen.profile.game_id.clone(), + created_at: item + .get("created_at") + .and_then(serde_json::Value::as_i64) + .or_else(|| { + item.get("when") + .and_then(serde_json::Value::as_str) + .and_then(timestamp) + }) + .unwrap_or(0), + size_bytes, + state: if preview.state == domain::JobState::Partial { + "partial" + } else { + "available" + } + .into(), + }); + } + } + } + let binding = format!( + "backup-page:{}:{}:{}:{}", + frozen.profile.id, + frozen.profile.revision, + caller.grant_revision, + hex(request_hash( + &history_binding + .iter() + .map(String::as_str) + .collect::>() + )) + ); + let after = if page.cursor.is_empty() { + 0 + } else { + self.files + .open_cursor(&caller.session_id, &binding, &page.cursor) + .and_then(|p| p.parse::().ok()) + .filter(|p| *p <= records.len()) + .ok_or_else(|| Status::failed_precondition("backup history changed; list again"))? + }; + let count = if page.page_size == 0 { + DEFAULT_PAGE_SIZE + } else { + (page.page_size as usize).min(MAX_PAGE_SIZE) + }; + let end = (after + count).min(records.len()); + let next_cursor = if end < records.len() { + self.files + .seal_cursor(&caller.session_id, &binding, &end.to_string()) + } else { + String::new() + }; + let (current, current_scope) = self + .backup_scope( + &context, + cap::BACKUPS_READ, + &request.profile_id, + &request.game_id, + ) + .await?; + if current.grant_revision != caller.grant_revision || current_scope != frozen { + return Err(Status::failed_precondition( + "backup scope changed; list again", + )); + } + Ok(Response::new(BackupsListReply { + backups: records[after..end].to_vec(), + next_cursor, + })) + } + + pub(super) async fn create_backup( + &self, + request: Request, + ) -> Result, Status> { + let r = request.into_inner(); + if r.reason.len() > 512 || r.reason.chars().any(char::is_control) { + return Err(Status::invalid_argument("invalid backup reason")); + } + self.request_backup( + r.mutation, + r.game_id, + r.profile_id, + None, + String::new(), + r.reason, + ) + .await + .map(Response::new) + } + pub(super) async fn restore_backup( + &self, + request: Request, + ) -> Result, Status> { + let r = request.into_inner(); + self.request_backup( + r.mutation, + r.game_id, + r.profile_id, + Some(r.backup_id), + r.user_intent_id, + String::new(), + ) + .await + .map(Response::new) + } + + async fn request_backup( + &self, + mutation: Option, + game: String, + profile: String, + backup: Option, + intent: String, + reason: String, + ) -> Result { + let mutation = mutation.ok_or_else(|| Status::invalid_argument("mutation required"))?; + let context = mutation.context.clone().unwrap_or_default(); + let permission = if backup.is_some() { + cap::BACKUPS_RESTORE + } else { + cap::BACKUPS_CREATE + }; + let (caller, frozen) = self + .backup_scope(&context, permission, &profile, &game) + .await?; + if frozen.profile.revision != mutation.expected_revision { + return Err(Status::aborted("save profile changed; read it again")); + } + let key = mutation_key(&mutation)?.to_owned(); + let hash = request_hash(&[ + "backup", + permission, + &game, + &profile, + backup.as_deref().unwrap_or(""), + &intent, + &reason, + &mutation.expected_revision.to_string(), + ]); + let owner = JobOwner::of(&caller)?; + let _serial = self.mutations.lock.lock().await; + if let Some(original) = self.jobs.replay(&owner, &key, hash)? { + return Ok(original); + } + let archive = if let Some(id) = backup { + let binding = format!("backup:{}:{}", frozen.profile.id, frozen.profile.revision); + let value = self + .files + .open_cursor(&caller.session_id, &binding, &id) + .ok_or_else(not_found)?; + Some(serde_json::from_str::(&value).map_err(|_| not_found())?) + } else { + None + }; + let operation = archive + .as_ref() + .map(|a| BackupOperation::RestorePreview { + backup: a.backup.clone(), + }) + .unwrap_or(BackupOperation::Backup); + let (engine, request, lease, runtime_check) = self + .backup_request( + &frozen, + &caller, + operation, + archive.as_ref().map(|a| a.destination.clone()), + true, + ) + .await?; + if archive.is_some() && !self.intents.can_confirm() { + return Err(Status::failed_precondition( + "restore confirmation dialog unavailable", + )); + } + let binding = Binding { + plugin_id: caller + .namespace + .as_ref() + .unwrap() + .identity() + .plugin_id + .clone(), + publisher_fingerprint: caller + .namespace + .as_ref() + .unwrap() + .identity() + .publisher_fingerprint + .clone(), + profile_epoch: caller.profile_epoch, + game_id: frozen.profile.game_id.clone(), + installation_id: frozen.profile.installation_id.clone(), + operation: Operation::BackupRestore, + target_revision: frozen.profile.revision, + recipe_id: String::new(), + recipe_revision: 0, + plan_fingerprint: String::new(), + }; + // The restore snapshot is not part of a legacy intent binding. Always ask for this exact + // preview; do not let a launch/install intent authorize a restore. + if !intent.is_empty() { + return Err(Status::failed_precondition( + "restore requires confirmation of its exact snapshot", + )); + } + let pending = if archive.is_some() { + Some(self.intents.begin_pending(&binding)?) + } else { + None + }; + let api = self.clone(); + let c = caller.clone(); + let cx = context.clone(); + let run = work(move |mut ctx| async move { + // Held until the job ends, including a restore confirmation dialog. + let _lease = lease; + let _pending = pending; + let cancelled = Arc::new(AtomicBool::new(false)); + let mut request = request; + request.job_id = Some(ctx.id().into()); + let mut reviewed_targets = None; + let checkpoint = ctx.checkpoint(); + if let Some(archive) = archive { + let mut authority = + api.backup_authority(&c, &cx, permission, &frozen, checkpoint.clone()); + authority.runtime_check = runtime_check.clone(); + let preview = match api + .execute_backup( + engine.clone(), + request.clone(), + authority, + cancelled.clone(), + ) + .await + { + Ok(p) => p, + Err(e) => return Outcome::stopped(&e), + }; + if preview.state == domain::JobState::Partial { + return Outcome::failed("preview_failed", "restore preview failed"); + } + let json = match decode_report(preview.json).await { + Ok(json) => json, + Err(e) => return Outcome::stopped(&e), + }; + let Some(target) = json + .get("games") + .and_then(|g| g.get(&request.profile.title)) + else { + return Outcome::failed("preview_failed", "snapshot unavailable"); + }; + let files = target + .get("files") + .and_then(serde_json::Value::as_object) + .map(|m| m.keys().cloned().collect::>()) + .unwrap_or_default(); + let registry = target + .get("registry") + .and_then(serde_json::Value::as_object) + .map(|m| m.keys().cloned().collect::>()) + .unwrap_or_default(); + let mut authority = + api.backup_authority(&c, &cx, permission, &frozen, checkpoint.clone()); + authority.runtime_check = runtime_check.clone(); + let validation = tokio::task::spawn_blocking(move || { + authority + .validate_targets(&files, ®istry) + .map(|()| files) + }) + .await; + let files = match validation { + Ok(Ok(files)) => files, + _ => { + return Outcome::failed( + "scope_denied", + "restore targets are outside the approved profile", + ); + } + }; + reviewed_targets = Some(files.clone()); + let mut details = vec![frozen.profile.name.clone(), archive.backup.clone()]; + details.extend(files); + let confirmation = ConfirmationRequest { + plugin_id: binding.plugin_id, + publisher_fingerprint: binding.publisher_fingerprint, + game_name: frozen.game_name.clone(), + operation: Operation::BackupRestore, + details, + launch_plan: None, + }; + let answer = tokio::select! { + answer = api.intents.confirm(confirmation) => answer, + () = ctx.cancelled() => return Outcome::cancelled("restore cancelled"), + }; + match answer { + Ok(Verdict::Approved { .. }) => {} + Ok(Verdict::Declined) => { + return Outcome::failed("declined", "restore declined"); + } + Ok(Verdict::TimedOut) => { + return Outcome::failed( + "confirmation_timeout", + "restore confirmation timed out", + ); + } + Err(e) => return Outcome::stopped(&e), + } + if let Err(e) = ctx.start().and_then(|()| ctx.check()) { + return Outcome::stopped(&e); + } + request.operation = BackupOperation::Restore { + backup: archive.backup, + }; + } else { + let id = frozen.profile.id.clone(); + let destination = request.destination.clone(); + let guard = api.guard(cx.clone(), permission, c.grant_revision); + if let Err(e) = api + .in_namespace(&c, move |n| { + n.remember_backup_source(&id, &destination, &guard) + }) + .await + { + return Outcome::stopped(&e); + } + } + let mut authority = api.backup_authority(&c, &cx, permission, &frozen, checkpoint); + authority.reviewed_targets = reviewed_targets; + authority.runtime_check = runtime_check; + match api + .execute_backup(engine, request, authority, cancelled) + .await + { + Ok(report) + if matches!( + report.state, + domain::JobState::Successful | domain::JobState::Unchanged + ) => + { + Outcome::succeeded("backup_complete", "backup operation completed") + } + Ok(_) => Outcome::failed( + "partial_failure", + "backup operation was incomplete; recovery data is retained", + ), + Err(e) => Outcome::stopped(&e), + } + }); + let (job, _) = self.start_job( + &caller, + context, + permission, + &key, + hash, + if pending_restore(permission) { + Some("awaiting restore confirmation") + } else { + None + }, + run, + )?; + Ok(job) + } +} +fn pending_restore(permission: &str) -> bool { + permission == cap::BACKUPS_RESTORE +} + +fn timestamp(text: &str) -> Option { + let number = |a, b| text.get(a..b)?.parse::().ok(); + if text.get(4..5)? != "-" + || text.get(7..8)? != "-" + || text.get(10..11)? != "T" + || text.get(13..14)? != ":" + || text.get(16..17)? != ":" + { + return None; + } + let (year, month, day, hour, minute, second) = ( + number(0, 4)?, + number(5, 7)?, + number(8, 10)?, + number(11, 13)?, + number(14, 16)?, + number(17, 19)?, + ); + let leap = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0); + let days = match month { + 2 => { + if leap { + 29 + } else { + 28 + } + } + 4 | 6 | 9 | 11 => 30, + 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31, + _ => return None, + }; + if !(1..=9999).contains(&year) + || !(1..=days).contains(&day) + || !(0..24).contains(&hour) + || !(0..60).contains(&minute) + || !(0..60).contains(&second) + { + return None; + } + let mut suffix = text.get(19..)?; + if let Some(fraction) = suffix.strip_prefix('.') { + let digits = fraction.bytes().take_while(u8::is_ascii_digit).count(); + if digits == 0 { + return None; + } + suffix = &fraction[digits..]; + } + let offset = if suffix == "Z" { + 0 + } else { + if suffix.len() != 6 || !matches!(suffix.get(..1)?, "+" | "-") || suffix.get(3..4)? != ":" { + return None; + } + let h = suffix.get(1..3)?.parse::().ok()?; + let m = suffix.get(4..6)?.parse::().ok()?; + if h > 23 || m > 59 { + return None; + } + (h * 3600 + m * 60) * if suffix.starts_with('-') { -1 } else { 1 } + }; + let y = year - i64::from(month <= 2); + let era = y.div_euclid(400); + let yoe = y - era * 400; + let mp = month + if month > 2 { -3 } else { 9 }; + let doy = (153 * mp + 2) / 5 + day - 1; + let days = era * 146097 + yoe * 365 + yoe / 4 - yoe / 100 + doy - 719468; + Some(days * 86400 + hour * 3600 + minute * 60 + second - offset) +} +#[cfg(test)] +mod timestamp_tests { + #[test] + fn helper_dates_have_explicit_offsets_and_valid_gregorian_components() { + assert_eq!(super::timestamp("1970-01-01T00:00:00Z"), Some(0)); + assert_eq!( + super::timestamp("2024-02-29T00:00:00.123Z"), + Some(1709164800) + ); + assert_eq!( + super::timestamp("2024-02-28T21:00:00-03:00"), + Some(1709164800) + ); + for bad in [ + "2023-02-29T00:00:00Z", + "2024-02-29T24:00:00Z", + "2024-02-29T00:00:00", + "2024-02-29T00:00:00+24:00", + ] { + assert_eq!(super::timestamp(bad), None); + } + } +} diff --git a/crates/app/src/plugin_host/resources/custom_launch.rs b/crates/app/src/plugin_host/resources/custom_launch.rs new file mode 100644 index 000000000..1c928bb19 --- /dev/null +++ b/crates/app/src/plugin_host/resources/custom_launch.rs @@ -0,0 +1,1294 @@ +//! Plugin-owned custom launch recipe lifecycle. +//! +//! Permission is checked before inspecting the requested game or recipe. In particular, a custom +//! launch request never falls through to the standard `game.launch` route. + +use gamenode_core::library::{CustomLaunchMutation, CustomLaunchRecipe}; +use gamenode_plugin_protocol::{capability as cap, proto::*}; +use tonic::{Request, Response, Status}; + +use super::mutations::{game_id, mutation_owner, request_hash}; +use super::{ResourceApi, Scope}; + +const MAX_KEY_BYTES: usize = 128; +const MAX_RECIPE_ID_BYTES: usize = 128; + +fn proposal_hash(request: &CustomLaunchRequest) -> [u8; 32] { + let mut fields = vec![ + "custom-launch-propose".to_owned(), + request.game_id.clone(), + request.installation_id.clone(), + request.expected_revision.to_string(), + request.executable_handle.clone(), + request.uri.clone(), + format!("argv:{}", request.argv.len()), + ]; + fields.extend(request.argv.iter().cloned()); + fields.extend([ + request.working_directory_handle.clone(), + request.runtime_handle.clone(), + request.content_id.clone(), + ]); + let mut environment_set = request.environment_set.iter().collect::>(); + environment_set.sort_by(|left, right| left.0.cmp(right.0)); + fields.push(format!("environment_set:{}", environment_set.len())); + for (key, value) in environment_set { + fields.push(key.clone()); + fields.push(value.clone()); + } + let mut environment_unset = request.environment_unset.clone(); + environment_unset.sort(); + fields.push(format!("environment_unset:{}", environment_unset.len())); + fields.extend(environment_unset); + fields.push(format!("mod_layers:{}", request.mod_layers.len())); + for layer in &request.mod_layers { + fields.push(layer.id.clone()); + fields.push(layer.name.clone()); + fields.push(layer.version.clone()); + fields.push(layer.revision.to_string()); + fields.push(format!("argv:{}", layer.argv.len())); + fields.extend(layer.argv.iter().cloned()); + let mut set = layer.environment_set.iter().collect::>(); + set.sort_by(|left, right| left.0.cmp(right.0)); + fields.push(format!("environment_set:{}", set.len())); + for (key, value) in set { + fields.push(key.clone()); + fields.push(value.clone()); + } + let mut unset = layer.environment_unset.clone(); + unset.sort(); + fields.push(format!("environment_unset:{}", unset.len())); + fields.extend(unset); + } + let parts = fields.iter().map(String::as_str).collect::>(); + request_hash(&parts) +} + +fn proposed_reply(recipe_id: String, revision: u64) -> CustomLaunchReply { + CustomLaunchReply { + recipe_id, + recipe_revision: revision, + job_id: String::new(), + state: JobState::Unspecified as i32, + refusal_code: String::new(), + message: "recipe saved; execution requires a separately approved request".into(), + } +} + +fn recipe_mod_layer(layer: CustomLaunchModLayer) -> gamenode_core::library::CustomLaunchModLayer { + gamenode_core::library::CustomLaunchModLayer { + id: layer.id, + name: layer.name, + version: layer.version, + revision: layer.revision, + arguments: layer.argv, + environment_set: layer.environment_set.into_iter().collect(), + environment_unset: layer.environment_unset.into_iter().collect(), + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(super) struct ResolvedLaunchPath { + pub path: String, + pub resource: gamenode_core::library::LaunchPlanResource, +} + +struct ResolvedSelectedRecipe { + dispatch: crate::plugin_host::library::CustomLaunchDispatch, + authority: crate::plugin_host::library::UserLaunchAuthority, + fingerprint: String, + review: super::super::launch_plan::LaunchPlanReview, + game_name: String, +} + +pub(super) fn resolve_handle_path( + files: std::sync::Arc, + feed: std::sync::Arc, + session: String, + handle: String, + installation_id: String, + directory: bool, +) -> impl FnOnce(&mut crate::plugin_host::storage::Namespace<'_>) -> Result ++ Send ++ 'static { + move |namespace| { + let opened = super::files::open_handle( + &files, + &feed, + namespace, + &session, + &handle, + gamenode_platform::plugin_storage::operation::READ, + )?; + if opened.approval.installation_id != installation_id + || !matches!(opened.approval.kind.as_str(), "installation" | "prefix") + { + return Err(Status::permission_denied( + "the handle is not approved for this game installation", + )); + } + let root = std::path::PathBuf::from(&opened.approval.root); + let mut requested = root.clone(); + for part in opened.path { + requested.push(part); + } + let canonical = std::fs::canonicalize(&requested) + .map_err(|_| Status::failed_precondition("approved launch handle changed"))?; + if !canonical.starts_with(&root) + || (directory && !canonical.is_dir()) + || (!directory && !canonical.is_file()) + { + return Err(Status::permission_denied( + "the handle is outside its approved game folder", + )); + } + let path = canonical + .to_str() + .map(str::to_owned) + .ok_or_else(|| Status::failed_precondition("launch path is not valid Unicode"))?; + Ok(ResolvedLaunchPath { + path, + resource: gamenode_core::library::LaunchPlanResource { + id: format!("file-approval:{}", opened.approval.id), + revision: opened.approval.approved_at.max(1) as u64, + }, + }) + } +} + +async fn capture_recipe_file( + api: &ResourceApi, + caller: &crate::plugin_host::provider::ResourceCaller, + handle: String, + installation_id: String, + directory: bool, +) -> Result { + let files = api.files.clone(); + let feed = api.library.clone(); + let session = caller.session_id.clone(); + api.in_namespace(caller, move |namespace| { + let opened = super::files::open_handle( + &files, + &feed, + namespace, + &session, + &handle, + gamenode_platform::plugin_storage::operation::READ, + )?; + if opened.approval.installation_id != installation_id + || !matches!(opened.approval.kind.as_str(), "installation" | "prefix") + { + return Err(Status::permission_denied( + "the handle is not approved for this game installation", + )); + } + let entry = opened + .confined + .stat(&opened.path) + .map_err(super::files::file_status)?; + if opened.path.is_empty() || entry.directory != directory { + return Err(Status::failed_precondition( + "the approved launch file changed type", + )); + } + let reference = gamenode_core::library::ApprovedFileReference { + approval_id: opened.approval.id, + relative_path: opened.path, + }; + if reference.validate() { + Ok(reference) + } else { + Err(Status::invalid_argument( + "invalid approved launch reference", + )) + } + }) + .await +} + +async fn resolve_recipe_file( + api: &ResourceApi, + caller: &crate::plugin_host::provider::ResourceCaller, + handle: &str, + reference: Option<&gamenode_core::library::ApprovedFileReference>, + installation_id: &str, + directory: bool, +) -> Result { + let handle = if handle.is_empty() { + let reference = reference + .filter(|reference| reference.validate()) + .ok_or_else(|| Status::failed_precondition("approved launch reference is missing"))?; + api.files.seal_handle( + &caller.session_id, + &reference.approval_id, + &reference.relative_path, + ) + } else { + handle.to_owned() + }; + let resolve = resolve_handle_path( + api.files.clone(), + api.library.clone(), + caller.session_id.clone(), + handle, + installation_id.to_owned(), + directory, + ); + api.in_namespace(caller, resolve).await +} + +async fn resolve_recipe_reference_for_host( + api: &ResourceApi, + caller: &crate::plugin_host::provider::ResourceCaller, + reference: &gamenode_core::library::ApprovedFileReference, + installation_id: &str, + directory: bool, +) -> Result { + if !reference.validate() { + return Err(Status::failed_precondition( + "approved launch reference is invalid", + )); + } + let files = api.files.clone(); + let feed = api.library.clone(); + let reference = reference.clone(); + let installation_id = installation_id.to_owned(); + api.in_host_namespace(caller, move |namespace| { + let opened = super::files::open_approval( + &files, + &feed, + namespace, + &reference.approval_id, + reference.relative_path.clone(), + gamenode_platform::plugin_storage::operation::READ, + )?; + if opened.approval.installation_id != installation_id + || !matches!(opened.approval.kind.as_str(), "installation" | "prefix") + { + return Err(Status::permission_denied( + "the approved file no longer matches this game installation", + )); + } + let root = std::fs::canonicalize(&opened.approval.root) + .map_err(|_| Status::failed_precondition("approved launch root changed"))?; + let mut requested = root.clone(); + for part in &opened.path { + requested.push(part); + } + let canonical = std::fs::canonicalize(&requested) + .map_err(|_| Status::failed_precondition("approved launch file changed"))?; + if !canonical.starts_with(&root) + || (directory && !canonical.is_dir()) + || (!directory && !canonical.is_file()) + { + return Err(Status::permission_denied( + "the approved launch file is outside its game folder", + )); + } + let path = canonical + .to_str() + .ok_or_else(|| Status::failed_precondition("launch path is not valid Unicode"))? + .to_owned(); + Ok(ResolvedLaunchPath { + path, + resource: gamenode_core::library::LaunchPlanResource { + id: format!("file-approval:{}", opened.approval.id), + revision: opened.approval.approved_at.max(1) as u64, + }, + }) + }) + .await +} + +fn recipe_id() -> Result { + let mut bytes = [0u8; 16]; + getrandom::fill(&mut bytes).map_err(|_| Status::internal("no source of randomness"))?; + Ok(bytes.iter().map(|byte| format!("{byte:02x}")).collect()) +} + +fn outcome(mutation: CustomLaunchMutation, id: &str) -> MutationReply { + match mutation { + CustomLaunchMutation::Applied { revision } => MutationReply { + resource_id: id.to_owned(), + revision, + outcome: MutationOutcome::Applied as i32, + }, + CustomLaunchMutation::Conflict { current } => MutationReply { + resource_id: id.to_owned(), + revision: current, + outcome: MutationOutcome::RevisionConflict as i32, + }, + CustomLaunchMutation::Missing => MutationReply { + resource_id: id.to_owned(), + revision: 0, + outcome: MutationOutcome::RevisionConflict as i32, + }, + } +} + +/// The revision a custom-launch action is bound to. An extension session uses the host-issued +/// target revision, exactly like `request_action`; a provider session uses its library entry. +fn action_revision( + context: &ServiceContext, + entry: &crate::plugin_host::library::Projected, +) -> Option { + if context.session_kind() == SessionKind::Extension { + context + .target_game + .as_ref() + .and_then(|target| target.revision.parse::().ok()) + } else { + Some(entry.revision) + } +} + +impl ResourceApi { + /// Whether the recipe keeps the entry's detected target and only overlays reviewed parameters + /// or declared mod layers. + fn is_parameter_overlay(recipe: &CustomLaunchRecipe) -> bool { + recipe.uri.is_empty() + && recipe.runtime_handle.is_empty() + && recipe.executable.is_none() + && recipe.executable_handle.is_empty() + } + + /// Resolves the detected executable target and applies only the recipe's reviewed parameters. + /// A URI target fails explicitly because an OS URI handler cannot honor these fields. + async fn prepare_detected_overlay( + &self, + entry_key: &str, + recipe: &CustomLaunchRecipe, + working_directory_path: Option, + ) -> Result { + let host = self + .library + .host() + .ok_or_else(|| Status::unavailable("custom launch recipes are unavailable"))?; + let mut command = host + .detected_launch(entry_key.to_owned(), recipe.base_target_revision) + .await?; + command.arguments.extend(recipe.effective_arguments()); + command.environment = recipe.effective_environment(); + if let Some(path) = working_directory_path { + command.working_directory = path; + } + Ok(crate::plugin_host::library::CustomLaunchDispatch::Detected { command }) + } + + async fn prepare_recipe_dispatch( + &self, + entry_key: &str, + recipe: &CustomLaunchRecipe, + executable_path: Option, + working_directory_path: Option, + runtime: Option, + ) -> Result { + if Self::is_parameter_overlay(recipe) { + return self + .prepare_detected_overlay(entry_key, recipe, working_directory_path) + .await; + } + self.library + .host() + .ok_or_else(|| Status::unavailable("custom launch recipes are unavailable"))? + .prepare_custom_launch( + recipe.clone(), + executable_path, + working_directory_path, + runtime, + ) + .await + } + + /// Executes the recipe selected for a user-initiated Play. A stored selection never falls + /// through to the detected default: stale identity, permissions, files, runtime bindings or + /// recipe revisions fail closed and leave the selector available for repair. + pub async fn launch_selected_recipe(&self, entry_key: String) -> Result { + use crate::plugin_host::intents::{ConfirmationRequest, Operation, Verdict}; + + let store = self + .library + .host() + .ok_or_else(|| Status::unavailable("custom launch recipes are unavailable"))?; + let selected = store.launch_recipe_selection(entry_key.clone()).await?; + let Some(selected) = selected else { + return Ok(false); + }; + + let plan = self + .resolve_selected_recipe_plan(&entry_key, &selected) + .await?; + let already_approved = !selected.approved_plan_fingerprint.is_empty() + && selected.approved_plan_fingerprint == plan.fingerprint; + let remember = if already_approved { + false + } else { + match self + .intents + .confirm(ConfirmationRequest { + plugin_id: selected.plugin_id.clone(), + publisher_fingerprint: selected.publisher_fingerprint.clone(), + game_name: plan.game_name.clone(), + operation: Operation::CustomLaunch, + details: vec![], + launch_plan: Some(plan.review.clone()), + }) + .await? + { + Verdict::Approved { remember } => remember, + Verdict::Declined => return Ok(false), + Verdict::TimedOut => { + return Err(Status::deadline_exceeded("launch review timed out")); + } + } + }; + + // Consent can take minutes. Rebuild everything from current grants, recipe records, + // target and file approvals before dispatch, and require the same canonical plan. + let current = self + .resolve_selected_recipe_plan(&entry_key, &selected) + .await?; + if current.fingerprint != plan.fingerprint { + return Err(Status::failed_precondition( + "the launch plan changed during review; review the updated plan", + )); + } + if remember { + let library = self + .library + .host() + .ok_or_else(|| Status::unavailable("custom launch recipes are unavailable"))?; + match library + .approve_launch_recipe_plan( + entry_key.clone(), + selected.recipe_id.clone(), + selected.recipe_revision, + selected.base_target_revision, + current.fingerprint.clone(), + ) + .await? + { + gamenode_core::library::LaunchRecipeSelectionWrite::Applied => {} + _ => { + return Err(Status::failed_precondition( + "the selected recipe changed before its approval could be remembered", + )); + } + } + } + self.library + .host() + .ok_or_else(|| Status::unavailable("custom launch recipes are unavailable"))? + .launch_custom_for_entry_authorized(current.dispatch, entry_key, current.authority) + .await?; + Ok(true) + } + + async fn resolve_selected_recipe_plan( + &self, + entry_key: &str, + selected: &gamenode_core::library::LaunchRecipeSelection, + ) -> Result { + use gamenode_plugin_protocol::capability as cap; + + let recipe_store = self + .library + .host() + .ok_or_else(|| Status::unavailable("custom launch recipes are unavailable"))?; + if recipe_store + .launch_recipe_selection(entry_key.to_owned()) + .await? + .as_ref() + != Some(selected) + { + return Err(Status::failed_precondition( + "the launch selection changed; review the current selection", + )); + } + let profiles = self.providers.profiles(); + let identity = profiles + .identities()? + .into_iter() + .find(|identity| { + identity.plugin_id == selected.plugin_id + && identity.publisher_fingerprint == selected.publisher_fingerprint + }) + .ok_or_else(|| Status::failed_precondition("the recipe owner is unavailable"))?; + if !profiles.is_enabled(&identity.plugin_id)? { + return Err(Status::permission_denied("the recipe owner is disabled")); + } + let (grant_revision, grants) = + profiles.granted_permissions(&identity.plugin_id, &identity.publisher_fingerprint)?; + if !grants.contains(cap::GAME_CUSTOM_LAUNCH) { + return Err(Status::permission_denied( + "custom launch permission is no longer granted", + )); + } + let resolver = + profiles.resolver(&identity.plugin_id, &identity.publisher_fingerprint, None)?; + if resolver.library_recipe_owner_key() != selected.owner_key { + return Err(Status::permission_denied("the recipe owner changed")); + } + let recipe = recipe_store + .custom_launch_recipe(selected.owner_key.clone(), selected.recipe_id.clone()) + .await? + .ok_or_else(|| Status::failed_precondition("the selected recipe was removed"))?; + if recipe.recipe_id != selected.recipe_id + || recipe.revision != selected.recipe_revision + || recipe.base_target_revision != selected.base_target_revision + || recipe.game_id == 0 + || recipe.installation_id.is_empty() + || !recipe.validate() + { + return Err(Status::failed_precondition( + "the selected recipe changed; choose it again or use the detected default", + )); + } + if !recipe.executable_handle.is_empty() || !recipe.working_directory_handle.is_empty() { + return Err(Status::failed_precondition( + "the recipe needs to be saved again with current file approvals before Play", + )); + } + let projection = self + .library + .target( + &Scope { + own_provider: String::new(), + read_all: true, + provider_filter: None, + }, + &recipe.installation_id, + ) + .filter(|(_, entry)| entry.game_id == Some(recipe.game_id)) + .map(|(_, entry)| entry) + .ok_or_else(|| Status::failed_precondition("the selected game is unavailable"))?; + let launch_fingerprint = recipe_store + .launch_fingerprint(entry_key.to_owned()) + .await?; + let target_revision = recipe_store + .launch_target_revision(entry_key.to_owned()) + .await?; + if target_revision != selected.base_target_revision + || recipe.base_launch_fingerprint != launch_fingerprint + { + return Err(Status::failed_precondition( + "the detected target changed; choose another recipe or use the detected default", + )); + } + let caller = crate::plugin_host::provider::ResourceCaller { + session_id: "host-user-play".into(), + provider_id: String::new(), + declared_developer: String::new(), + origin: String::new(), + package_digest: Vec::new(), + package_version: recipe.requester_package_version.clone(), + grants, + grant_revision, + profile_epoch: profiles.epoch(), + namespace: Some(resolver), + }; + let needs_files = recipe.executable.is_some() + || recipe.working_directory.is_some() + || !recipe.runtime_handle.is_empty(); + if needs_files && !caller.has(cap::FILES_READ) { + return Err(Status::permission_denied( + "file read permission is no longer granted", + )); + } + let runtime = if recipe.runtime_handle.is_empty() { + None + } else { + Some( + self.resolve_runtime_launch( + &caller, + None, + recipe.game_id, + &recipe.installation_id, + &recipe.runtime_handle, + &recipe.content_id, + ) + .await?, + ) + }; + let mut resources = runtime + .as_ref() + .map(|runtime| runtime.resources.clone()) + .unwrap_or_default(); + let executable = if let Some(reference) = recipe.executable.as_ref() { + let resolved = resolve_recipe_reference_for_host( + self, + &caller, + reference, + &recipe.installation_id, + false, + ) + .await?; + resources.push(resolved.resource); + Some(resolved.path) + } else { + None + }; + let working_directory = if let Some(reference) = recipe.working_directory.as_ref() { + let resolved = resolve_recipe_reference_for_host( + self, + &caller, + reference, + &recipe.installation_id, + true, + ) + .await?; + resources.push(resolved.resource); + Some(resolved.path) + } else { + None + }; + let dispatch = self + .prepare_recipe_dispatch(entry_key, &recipe, executable, working_directory, runtime) + .await?; + let plan = super::super::launch_plan::resolve( + &caller, + &projection, + target_revision, + Some(&recipe), + Some(&dispatch), + &resources, + )?; + let (fingerprint, review) = tokio::task::spawn_blocking(move || { + let fingerprint = plan + .fingerprint() + .map_err(|_| Status::failed_precondition("the launch plan is invalid"))?; + let review = super::super::launch_plan::review(&plan, fingerprint.clone()); + Ok::<_, Status>((fingerprint, review)) + }) + .await + .map_err(|_| Status::unavailable("launch plan worker stopped"))??; + Ok(ResolvedSelectedRecipe { + dispatch, + authority: crate::plugin_host::library::UserLaunchAuthority { + plugin_id: identity.plugin_id, + publisher_fingerprint: identity.publisher_fingerprint, + profile_id: identity.profile_id, + profile_epoch: caller.profile_epoch, + grant_revision: Some(grant_revision), + requires_files: needs_files, + }, + fingerprint, + review, + game_name: projection.display_name.unwrap_or(projection.name), + }) + } + + pub(super) async fn revalidate_custom_handles( + &self, + caller: &crate::plugin_host::provider::ResourceCaller, + context: &ServiceContext, + entry_key: &str, + recipe: &CustomLaunchRecipe, + dispatch: &crate::plugin_host::library::CustomLaunchDispatch, + ) -> Result, Status> { + if Self::is_parameter_overlay(recipe) { + let working_directory = if recipe.working_directory_handle.is_empty() + && recipe.working_directory.is_none() + { + None + } else { + self.providers + .authorize_resource(Some(context), cap::FILES_READ)?; + let working = resolve_recipe_file( + self, + caller, + &recipe.working_directory_handle, + recipe.working_directory.as_ref(), + &recipe.installation_id, + true, + ) + .await?; + Some(working) + }; + self.providers + .authorize_resource(Some(context), cap::GAME_CUSTOM_LAUNCH)?; + let current = self + .prepare_detected_overlay( + entry_key, + recipe, + working_directory + .as_ref() + .map(|working| working.path.clone()), + ) + .await?; + let crate::plugin_host::library::CustomLaunchDispatch::Detected { command: current } = + current + else { + return Err(Status::failed_precondition( + "the detected target no longer matches the reviewed plan", + )); + }; + let crate::plugin_host::library::CustomLaunchDispatch::Detected { command } = dispatch + else { + return Err(Status::failed_precondition( + "the approved detected target changed before launch", + )); + }; + if current != *command { + return Err(Status::failed_precondition( + "the approved detected launch plan changed before launch", + )); + } + return Ok(working_directory + .map(|working| vec![working.resource]) + .unwrap_or_default()); + } + if !recipe.runtime_handle.is_empty() { + let crate::plugin_host::library::CustomLaunchDispatch::Runtime { + command, + runtime_id, + runtime_version, + runtime_revision, + content_id, + binding_revision, + lease_keys, + } = dispatch + else { + return Err(Status::failed_precondition( + "the approved runtime dispatch changed before launch", + )); + }; + if recipe.runtime_handle != *runtime_id || recipe.content_id != *content_id { + return Err(Status::failed_precondition( + "the approved runtime or content selection changed before launch", + )); + } + let resolved = self + .resolve_runtime_launch( + caller, + Some(context), + recipe.game_id, + &recipe.installation_id, + &recipe.runtime_handle, + &recipe.content_id, + ) + .await?; + let mut resources = resolved.resources.clone(); + if resolved.runtime_revision != *runtime_revision + || resolved.binding_revision != *binding_revision + || resolved.lease_keys != *lease_keys + { + return Err(Status::failed_precondition( + "the approved runtime or content binding changed before launch", + )); + } + let working_directory = if recipe.working_directory_handle.is_empty() + && recipe.working_directory.is_none() + { + None + } else { + self.providers + .authorize_resource(Some(context), cap::FILES_READ)?; + let working = resolve_recipe_file( + self, + caller, + &recipe.working_directory_handle, + recipe.working_directory.as_ref(), + &recipe.installation_id, + true, + ) + .await?; + resources.push(working.resource); + Some(working.path) + }; + let host = self + .library + .host() + .ok_or_else(|| Status::unavailable("the library is not available"))?; + let current = host + .prepare_custom_launch(recipe.clone(), None, working_directory, Some(resolved)) + .await?; + match current { + crate::plugin_host::library::CustomLaunchDispatch::Runtime { + command: current, + runtime_id: current_runtime, + runtime_version: current_version, + runtime_revision: current_revision, + content_id: current_content, + binding_revision: current_binding, + lease_keys: current_lease_keys, + } if ¤t == command + && current_runtime == *runtime_id + && current_version == *runtime_version + && current_revision == *runtime_revision + && current_content == *content_id + && current_binding == *binding_revision + && current_lease_keys == *lease_keys => + { + return Ok(resources); + } + _ => { + return Err(Status::failed_precondition( + "the approved runtime launch plan changed before launch", + )); + } + } + } + let is_uri = !recipe.uri.is_empty(); + if recipe.executable_handle.is_empty() + && recipe.executable.is_none() + && recipe.working_directory_handle.is_empty() + && recipe.working_directory.is_none() + { + return Ok(Vec::new()); + } + let mut resources = Vec::new(); + self.providers + .authorize_resource(Some(context), cap::FILES_READ)?; + if !is_uri { + let command = match dispatch { + crate::plugin_host::library::CustomLaunchDispatch::Executable(command) + | crate::plugin_host::library::CustomLaunchDispatch::Detected { command } => { + command + } + crate::plugin_host::library::CustomLaunchDispatch::Runtime { command, .. } => { + command + } + crate::plugin_host::library::CustomLaunchDispatch::Uri { .. } => { + return Err(Status::failed_precondition( + "custom executable dispatch no longer matches its recipe", + )); + } + }; + let executable = resolve_recipe_file( + self, + caller, + &recipe.executable_handle, + recipe.executable.as_ref(), + &recipe.installation_id, + false, + ) + .await?; + if executable.path != command.executable { + return Err(Status::failed_precondition( + "approved executable handle changed during confirmation", + )); + } + resources.push(executable.resource); + } + if !recipe.working_directory_handle.is_empty() || recipe.working_directory.is_some() { + let working_directory = resolve_recipe_file( + self, + caller, + &recipe.working_directory_handle, + recipe.working_directory.as_ref(), + &recipe.installation_id, + true, + ) + .await?; + let approved_working_directory = match dispatch { + crate::plugin_host::library::CustomLaunchDispatch::Executable(command) + | crate::plugin_host::library::CustomLaunchDispatch::Detected { command } + | crate::plugin_host::library::CustomLaunchDispatch::Runtime { command, .. } => { + &command.working_directory + } + crate::plugin_host::library::CustomLaunchDispatch::Uri { + working_directory, + .. + } => working_directory, + }; + if &working_directory.path != approved_working_directory { + return Err(Status::failed_precondition( + "approved working directory changed during confirmation", + )); + } + resources.push(working_directory.resource); + } + Ok(resources) + } + + pub(super) async fn propose_custom_launch( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + // Keep this first: an ungranted custom request is always an explicit permission denial. + let caller = self + .providers + .authorize_resource(request.context.as_ref(), cap::GAME_CUSTOM_LAUNCH)?; + if request.idempotency_key.is_empty() + || request.idempotency_key.len() > MAX_KEY_BYTES + || request.idempotency_key.chars().any(char::is_control) + { + return Err(Status::invalid_argument("invalid idempotency key")); + } + let context = request + .context + .as_ref() + .ok_or_else(|| Status::unauthenticated("resource context required"))?; + let hash = proposal_hash(&request); + let lock = self.mutations.lock.lock().await; + if let Some(replay) = self + .mutations + .replay(&caller, &request.idempotency_key, hash)? + { + return Ok(Response::new(proposed_reply( + replay.resource_id, + replay.revision, + ))); + } + let (_entry_key, entry) = + self.action_target(&caller, context, &request.game_id, &request.installation_id)?; + if action_revision(context, &entry) != Some(request.expected_revision) { + return Err(Status::failed_precondition("library entry changed")); + } + let game_id = game_id(&request.game_id)? + .ok_or_else(|| Status::invalid_argument("custom launch requires a matched game"))?; + let host = self + .library + .host() + .ok_or_else(|| Status::unavailable("custom launch recipes are unavailable"))?; + let base_target_revision = host.launch_target_revision(_entry_key.clone()).await?; + let base_launch_fingerprint = host.launch_fingerprint(_entry_key.clone()).await?; + let executable = if request.executable_handle.is_empty() { + None + } else { + self.providers + .authorize_resource(request.context.as_ref(), cap::FILES_READ)?; + Some( + capture_recipe_file( + self, + &caller, + request.executable_handle.clone(), + entry.installation_id.clone(), + false, + ) + .await?, + ) + }; + let working_directory = if request.working_directory_handle.is_empty() { + None + } else { + self.providers + .authorize_resource(request.context.as_ref(), cap::FILES_READ)?; + Some( + capture_recipe_file( + self, + &caller, + request.working_directory_handle.clone(), + entry.installation_id.clone(), + true, + ) + .await?, + ) + }; + let recipe = CustomLaunchRecipe { + recipe_id: recipe_id()?, + revision: 1, + requester_package_version: caller.package_version.clone(), + game_id, + installation_id: entry.installation_id, + base_target_revision, + base_launch_fingerprint, + executable_handle: String::new(), + executable, + content_id: request.content_id, + uri: request.uri, + arguments: request.argv, + working_directory_handle: String::new(), + working_directory, + runtime_handle: request.runtime_handle, + environment_set: request.environment_set.into_iter().collect(), + environment_unset: request.environment_unset.into_iter().collect(), + mod_layers: request + .mod_layers + .into_iter() + .map(recipe_mod_layer) + .collect(), + }; + if !recipe.validate() || (!recipe.runtime_handle.is_empty() && recipe.executable.is_some()) + { + return Err(Status::invalid_argument("invalid custom launch recipe")); + } + self.authorize_commit(context, cap::GAME_CUSTOM_LAUNCH, caller.grant_revision)?; + let saved = host + .save_custom_launch_recipe(mutation_owner(&caller), recipe.clone()) + .await?; + match saved { + CustomLaunchMutation::Applied { revision } => { + self.mutations.remember( + &caller, + &request.idempotency_key, + hash, + &MutationReply { + resource_id: recipe.recipe_id.clone(), + revision, + outcome: MutationOutcome::Applied as i32, + }, + ); + drop(lock); + Ok(Response::new(proposed_reply(recipe.recipe_id, revision))) + } + CustomLaunchMutation::Conflict { .. } => { + Err(Status::aborted("recipe revision conflict")) + } + CustomLaunchMutation::Missing => { + Err(Status::not_found("custom launch recipe not found")) + } + } + } + + pub(super) async fn request_custom_launch( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + // A custom recipe cannot be downgraded to standard launch when this grant is absent. + let caller = self + .providers + .authorize_resource(request.context.as_ref(), cap::GAME_CUSTOM_LAUNCH)?; + if !request.executable_handle.is_empty() + || !request.content_id.is_empty() + || !request.uri.is_empty() + || !request.argv.is_empty() + || !request.working_directory_handle.is_empty() + || !request.runtime_handle.is_empty() + || !request.environment_set.is_empty() + || !request.environment_unset.is_empty() + || !request.mod_layers.is_empty() + { + return Err(Status::invalid_argument( + "custom execution must reference an approved recipe revision", + )); + } + if request.recipe_id.is_empty() || request.recipe_id.len() > MAX_RECIPE_ID_BYTES { + return Err(Status::invalid_argument("invalid recipe id")); + } + let context = request + .context + .as_ref() + .ok_or_else(|| Status::unauthenticated("resource context required"))?; + let (entry_key, entry) = + self.action_target(&caller, context, &request.game_id, &request.installation_id)?; + if action_revision(context, &entry) != Some(request.expected_revision) { + return Err(Status::failed_precondition("library entry changed")); + } + let host = self + .library + .host() + .ok_or_else(|| Status::unavailable("custom launch recipes are unavailable"))?; + let recipe = host + .custom_launch_recipe(mutation_owner(&caller), request.recipe_id.clone()) + .await? + .ok_or_else(|| Status::not_found("custom launch recipe not found"))?; + let launch_fingerprint = host.launch_fingerprint(entry_key.clone()).await?; + let target_revision = host.launch_target_revision(entry_key.clone()).await?; + if recipe.revision != request.recipe_revision + || recipe.game_id.to_string() != request.game_id + || recipe.installation_id != request.installation_id + || recipe.base_target_revision != target_revision + || recipe.base_launch_fingerprint != launch_fingerprint + { + return Err(Status::aborted("custom launch recipe revision changed")); + } + let runtime_launch = if recipe.runtime_handle.is_empty() { + None + } else { + Some( + self.resolve_runtime_launch( + &caller, + Some(context), + recipe.game_id, + &recipe.installation_id, + &recipe.runtime_handle, + &recipe.content_id, + ) + .await?, + ) + }; + let mut plan_resources = runtime_launch + .as_ref() + .map(|runtime| runtime.resources.clone()) + .unwrap_or_default(); + let has_executable = recipe.executable.is_some() || !recipe.executable_handle.is_empty(); + let (executable_path, working_directory_path) = if has_executable { + // A custom recipe grant authorizes asking for the launch; file handles remain subject + // to their separate read grant and approval. + self.providers + .authorize_resource(request.context.as_ref(), cap::FILES_READ)?; + let executable = resolve_recipe_file( + self, + &caller, + &recipe.executable_handle, + recipe.executable.as_ref(), + &recipe.installation_id, + false, + ) + .await?; + plan_resources.push(executable.resource.clone()); + let working = if recipe.working_directory_handle.is_empty() + && recipe.working_directory.is_none() + { + None + } else { + let resolved = resolve_recipe_file( + self, + &caller, + &recipe.working_directory_handle, + recipe.working_directory.as_ref(), + &recipe.installation_id, + true, + ) + .await?; + plan_resources.push(resolved.resource.clone()); + Some(resolved) + }; + (Some(executable.path), working.map(|path| path.path)) + } else { + let working = if recipe.working_directory_handle.is_empty() + && recipe.working_directory.is_none() + { + None + } else { + self.providers + .authorize_resource(request.context.as_ref(), cap::FILES_READ)?; + let resolved = resolve_recipe_file( + self, + &caller, + &recipe.working_directory_handle, + recipe.working_directory.as_ref(), + &recipe.installation_id, + true, + ) + .await?; + plan_resources.push(resolved.resource.clone()); + Some(resolved) + }; + (None, working.map(|path| path.path)) + }; + let dispatch = self + .prepare_recipe_dispatch( + &entry_key, + &recipe, + executable_path, + working_directory_path, + runtime_launch, + ) + .await?; + self.request_custom_action(request, recipe.clone(), dispatch, plan_resources) + .await + .map(|job| { + Response::new(CustomLaunchReply { + recipe_id: recipe.recipe_id, + recipe_revision: recipe.revision, + job_id: job.job_id, + state: job.state, + refusal_code: String::new(), + message: job.message, + }) + }) + } + + pub(super) async fn remove_custom_launch( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + let mutation = request + .mutation + .ok_or_else(|| Status::invalid_argument("mutation context is required"))?; + let context = mutation + .context + .as_ref() + .ok_or_else(|| Status::unauthenticated("resource context required"))?; + let caller = self + .providers + .authorize_resource(Some(context), cap::GAME_CUSTOM_LAUNCH)?; + if request.recipe_id.is_empty() || request.recipe_id.len() > MAX_RECIPE_ID_BYTES { + return Err(Status::invalid_argument("invalid recipe id")); + } + let key = mutation.idempotency_key.as_str(); + if key.is_empty() || key.len() > MAX_KEY_BYTES || key.chars().any(char::is_control) { + return Err(Status::invalid_argument("invalid idempotency key")); + } + let lock = self.mutations.lock.lock().await; + let hash = request_hash(&[ + "custom-launch-remove", + &request.game_id, + &request.recipe_id, + &mutation.expected_revision.to_string(), + ]); + if let Some(reply) = self.mutations.replay(&caller, key, hash)? { + return Ok(Response::new(reply)); + } + let id = game_id(&request.game_id)? + .ok_or_else(|| Status::invalid_argument("game_id is required"))?; + let scope = Scope { + own_provider: caller.provider_id.clone(), + read_all: false, + provider_filter: None, + }; + if self.library.by_game(&scope, id).1.is_empty() { + return Err(Status::not_found("library entry not found")); + } + let host = self + .library + .host() + .ok_or_else(|| Status::unavailable("custom launch recipes are unavailable"))?; + let owner = mutation_owner(&caller); + let recipe = host + .custom_launch_recipe(owner.clone(), request.recipe_id.clone()) + .await? + .ok_or_else(|| Status::not_found("custom launch recipe not found"))?; + if recipe.game_id != id { + return Err(Status::not_found("custom launch recipe not found")); + } + self.authorize_commit(context, cap::GAME_CUSTOM_LAUNCH, caller.grant_revision)?; + let result = host + .remove_custom_launch_recipe( + owner, + request.recipe_id.clone(), + mutation.expected_revision, + ) + .await?; + let reply = outcome(result, &request.recipe_id); + self.mutations.remember(&caller, key, hash, &reply); + drop(lock); + Ok(Response::new(reply)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::plugin_host::library::{InstallState, Projected}; + + fn entry() -> Projected { + Projected { + installation_id: "steam:3".into(), + provider_id: "steam".into(), + game_id: Some(3), + name: "Game".into(), + install_state: InstallState::Installed, + display_name: None, + metadata_revision: 0, + artwork_revision: 0, + revision: 7, + } + } + + #[test] + fn an_extension_custom_launch_uses_the_session_target_revision() { + let mut context = ServiceContext { + session_kind: SessionKind::Extension as i32, + ..Default::default() + }; + context.target_game = Some(TargetGameContext { + game_id: "3".into(), + installation_id: "steam:3".into(), + profile_id: "profile-1".into(), + revision: "100".into(), + }); + // The library entry revision and the host-issued target revision differ on a real + // extension; Propose/Request must use the same value as request_action. + assert_eq!(action_revision(&context, &entry()), Some(100)); + + context.session_kind = SessionKind::Provider as i32; + assert_eq!(action_revision(&context, &entry()), Some(7)); + } +} diff --git a/crates/app/src/plugin_host/resources/diagnostics.rs b/crates/app/src/plugin_host/resources/diagnostics.rs new file mode 100644 index 000000000..1f1599a2c --- /dev/null +++ b/crates/app/src/plugin_host/resources/diagnostics.rs @@ -0,0 +1,1052 @@ +//! Plugin-produced storage diagnostics. Core validates and routes reports but never runs a +//! benchmark or SMART utility. Reports are session-retained by the common data broker and every +//! cross-plugin read is projected by the existing sensitive-data policy. + +use super::super::shared_data::{MAX_PAGE_SIZE, Publication, QueryRequest}; +use super::super::sharing_policy::{Delivery, SharingClass}; +use super::*; +use futures_util::Stream; +use std::collections::BTreeMap; +use std::path::Path; +use std::pin::Pin; +use std::time::Duration; +use tonic::{Request, Response, Status}; + +const BENCHMARK_DATASET: &str = "storage.diagnostics.benchmark.v1"; +const SMART_DATASET: &str = "storage.diagnostics.smart.v1"; +const MAX_DIAGNOSTIC_FIELDS: usize = 256; +const MAX_DIAGNOSTIC_TEXT: usize = 512; +const MAX_PAGE: usize = 200; +const WATCH_QUEUE: usize = 32; +const WATCH_RECHECK: Duration = Duration::from_secs(5); + +pub const SERVED: &[Served] = &[ + Served::new( + "List", + cap::STORAGE_DIAGNOSTICS_READ, + true, + "sensitive report projection", + ), + Served::new( + "Get", + cap::STORAGE_DIAGNOSTICS_READ, + false, + "sensitive report projection", + ), + Served::new( + "Watch", + cap::STORAGE_DIAGNOSTICS_READ, + false, + "sensitive report projection", + ), +]; + +type WatchStream = Pin> + Send + 'static>>; + +fn dataset(projection: &str) -> Result<(&'static str, &'static str), Status> { + match projection { + "benchmark.v1" => Ok((BENCHMARK_DATASET, "benchmark")), + "smart.v1" => Ok((SMART_DATASET, "smart")), + _ => Err(Status::invalid_argument("unknown diagnostics projection")), + } +} + +fn plain(value: &str, max: usize, required: bool) -> Result<(), Status> { + if value.len() > max + || (required && value.trim().is_empty()) + || value.chars().any(char::is_control) + { + return Err(Status::invalid_argument("invalid diagnostic text field")); + } + Ok(()) +} + +fn field_name(value: &str) -> bool { + !value.is_empty() + && value.len() <= 128 + && value + .bytes() + .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-' | b'.')) + && !value.starts_with('.') + && !value.ends_with('.') + && !value.contains("..") +} + +fn state_name(value: i32) -> Result<&'static str, Status> { + match DiagnosticValueState::try_from(value) { + Ok(DiagnosticValueState::Available) => Ok("available"), + Ok(DiagnosticValueState::Unavailable) => Ok("unavailable"), + Ok(DiagnosticValueState::Unsupported) => Ok("unsupported"), + Ok(DiagnosticValueState::AccessDenied) => Ok("access_denied"), + Ok(DiagnosticValueState::Error) => Ok("error"), + _ => Err(Status::invalid_argument( + "diagnostic value state is required", + )), + } +} + +fn flatten_struct( + prefix: &str, + value: &prost_types::Struct, + fields: &mut serde_json::Map, + depth: usize, +) -> Result<(), Status> { + if depth > 8 { + return Err(Status::invalid_argument( + "diagnostic conditions are too deep", + )); + } + for (key, value) in &value.fields { + if !field_name(key) || fields.len() >= MAX_DIAGNOSTIC_FIELDS { + return Err(Status::invalid_argument( + "invalid diagnostic condition field", + )); + } + let name = if prefix.is_empty() { + key.clone() + } else { + format!("{prefix}.{key}") + }; + match value.kind.as_ref() { + Some(prost_types::value::Kind::StructValue(nested)) => { + flatten_struct(&name, nested, fields, depth + 1)?; + } + Some(prost_types::value::Kind::ListValue(_)) => { + let one = BTreeMap::from([(key.clone(), value.clone())]); + let mut converted = super::struct_to_json(&prost_types::Struct { fields: one })?; + fields.insert(name, converted.remove(key).unwrap_or(JsonValue::Null)); + } + _ => { + let one = BTreeMap::from([(key.clone(), value.clone())]); + let mut converted = super::struct_to_json(&prost_types::Struct { fields: one })?; + fields.insert(name, converted.remove(key).unwrap_or(JsonValue::Null)); + } + } + } + Ok(()) +} + +fn checked_time(observed_at: i64, now: i64) -> Result<(), Status> { + if observed_at <= 0 || observed_at > now.saturating_add(300) { + return Err(Status::invalid_argument( + "diagnostic observation time is outside the supported range", + )); + } + Ok(()) +} + +fn benchmark_fields( + request: &BenchmarkReportRequest, + now: i64, +) -> Result, Status> { + plain(&request.tool_name, MAX_DIAGNOSTIC_TEXT, true)?; + plain(&request.tool_version, MAX_DIAGNOSTIC_TEXT, true)?; + plain(&request.units, 128, true)?; + checked_time(request.observed_at, now)?; + if request.measurements.len() > MAX_DIAGNOSTIC_FIELDS + || request.measurement_states.len() > MAX_DIAGNOSTIC_FIELDS + || request.measurement_units.len() > MAX_DIAGNOSTIC_FIELDS + { + return Err(Status::resource_exhausted( + "diagnostic field limit exceeded", + )); + } + let mut fields = serde_json::Map::new(); + fields.insert( + "tool_name".into(), + JsonValue::String(request.tool_name.clone()), + ); + fields.insert( + "tool_version".into(), + JsonValue::String(request.tool_version.clone()), + ); + fields.insert("units".into(), JsonValue::String(request.units.clone())); + for (key, value) in &request.measurements { + if !field_name(key) || !value.is_finite() || *value < 0.0 { + return Err(Status::invalid_argument("invalid benchmark measurement")); + } + let state = request + .measurement_states + .get(key) + .copied() + .unwrap_or(DiagnosticValueState::Available as i32); + if state != DiagnosticValueState::Available as i32 { + return Err(Status::invalid_argument( + "available measurement has a non-available state", + )); + } + let unit = request.measurement_units.get(key).unwrap_or(&request.units); + plain(unit, 128, true)?; + fields.insert(format!("measurements.{key}"), JsonValue::from(*value)); + fields.insert( + format!("measurement_units.{key}"), + JsonValue::String(unit.clone()), + ); + fields.insert( + format!("measurement_states.{key}"), + JsonValue::String("available".into()), + ); + } + for (key, raw_state) in &request.measurement_states { + if !field_name(key) { + return Err(Status::invalid_argument("invalid measurement state field")); + } + if request.measurements.contains_key(key) { + if *raw_state != DiagnosticValueState::Available as i32 { + return Err(Status::invalid_argument( + "available measurement has a non-available state", + )); + } + continue; + } + if *raw_state == DiagnosticValueState::Available as i32 { + return Err(Status::invalid_argument( + "available measurement state requires a value", + )); + } + let state = state_name(*raw_state)?; + fields.insert( + format!("measurement_states.{key}"), + JsonValue::String(state.into()), + ); + } + if request.measurement_units.keys().any(|key| { + !field_name(key) + || (!request.measurements.contains_key(key) + && !request.measurement_states.contains_key(key)) + }) { + return Err(Status::invalid_argument( + "measurement units do not match a reported measurement", + )); + } + if let Some(conditions) = request.conditions.as_ref() { + flatten_struct("conditions", conditions, &mut fields, 0)?; + } + if fields.len() > MAX_DIAGNOSTIC_FIELDS { + return Err(Status::resource_exhausted( + "diagnostic field limit exceeded", + )); + } + Ok(fields) +} + +fn smart_fields( + request: &SmartReportRequest, + now: i64, +) -> Result, Status> { + plain(&request.device_model, MAX_DIAGNOSTIC_TEXT, false)?; + plain(&request.firmware, MAX_DIAGNOSTIC_TEXT, false)?; + checked_time(request.observed_at, now)?; + if request.attributes.len() > MAX_DIAGNOSTIC_FIELDS + || request.attribute_states.len() > MAX_DIAGNOSTIC_FIELDS + || request.attribute_units.len() > MAX_DIAGNOSTIC_FIELDS + { + return Err(Status::resource_exhausted( + "diagnostic field limit exceeded", + )); + } + let mut fields = serde_json::Map::new(); + fields.insert( + "device_model".into(), + JsonValue::String(request.device_model.clone()), + ); + fields.insert( + "firmware".into(), + JsonValue::String(request.firmware.clone()), + ); + for (key, value) in &request.attributes { + if !field_name(key) + || value.len() > MAX_DIAGNOSTIC_TEXT + || value.chars().any(char::is_control) + { + return Err(Status::invalid_argument("invalid SMART attribute")); + } + let state = request + .attribute_states + .get(key) + .copied() + .unwrap_or(DiagnosticValueState::Available as i32); + if state != DiagnosticValueState::Available as i32 { + return Err(Status::invalid_argument( + "available attribute has a non-available state", + )); + } + let unit = request + .attribute_units + .get(key) + .map(String::as_str) + .unwrap_or(""); + plain(unit, 128, false)?; + fields.insert( + format!("attributes.{key}"), + JsonValue::String(value.clone()), + ); + fields.insert( + format!("attribute_units.{key}"), + JsonValue::String(unit.into()), + ); + fields.insert( + format!("attribute_states.{key}"), + JsonValue::String("available".into()), + ); + } + for (key, raw_state) in &request.attribute_states { + if !field_name(key) { + return Err(Status::invalid_argument( + "invalid SMART attribute state field", + )); + } + if request.attributes.contains_key(key) { + if *raw_state != DiagnosticValueState::Available as i32 { + return Err(Status::invalid_argument( + "available attribute has a non-available state", + )); + } + continue; + } + if *raw_state == DiagnosticValueState::Available as i32 { + return Err(Status::invalid_argument( + "available attribute state requires a value", + )); + } + fields.insert( + format!("attribute_states.{key}"), + JsonValue::String(state_name(*raw_state)?.into()), + ); + if let Some(unit) = request.attribute_units.get(key) { + plain(unit, 128, false)?; + fields.insert( + format!("attribute_units.{key}"), + JsonValue::String(unit.clone()), + ); + } + } + if request.attribute_units.keys().any(|key| { + !field_name(key) + || (!request.attributes.contains_key(key) + && !request.attribute_states.contains_key(key)) + }) { + return Err(Status::invalid_argument( + "SMART attribute units do not match a reported attribute", + )); + } + if let Some(conditions) = request.conditions.as_ref() { + flatten_struct("conditions", conditions, &mut fields, 0)?; + } + if fields.len() > MAX_DIAGNOSTIC_FIELDS { + return Err(Status::resource_exhausted( + "diagnostic field limit exceeded", + )); + } + Ok(fields) +} + +fn report(record: &super::super::shared_data::ProjectedRecord, kind: &str) -> DiagnosticReport { + let mut fields = record.fields().clone(); + let volume_identity_token = fields + .remove("volume_identity_token") + .and_then(|value| value.as_str().map(str::to_owned)) + .unwrap_or_default(); + DiagnosticReport { + report_id: record.record_id().to_owned(), + report_kind: kind.to_owned(), + owner_plugin_id: record.provenance().source.plugin_id.clone(), + volume_identity_token, + schema_id: record.schema().0.to_owned(), + schema_version: record.schema().1, + typed_measurements: Some(super::json_to_struct(&fields)), + approved_extension: None, + observed_at: record.observed_at(), + revision: record.revision(), + } +} + +fn report_matches( + record: &super::super::shared_data::ProjectedRecord, + owner: &str, + volume: &str, +) -> bool { + (owner.is_empty() || record.provenance().source.plugin_id == owner) + && (volume.is_empty() || record.resource_id() == volume) +} + +fn broker_status(error: super::super::shared_data::BrokerError) -> Status { + match error { + super::super::shared_data::BrokerError::InvalidSelector => { + Status::invalid_argument("invalid diagnostics query") + } + super::super::shared_data::BrokerError::StaleCursor + | super::super::shared_data::BrokerError::StaleSubscription => { + Status::failed_precondition("diagnostics changed; query again") + } + super::super::shared_data::BrokerError::AuthorizationChanged + | super::super::shared_data::BrokerError::Expired => { + Status::failed_precondition("diagnostics authorization changed") + } + super::super::shared_data::BrokerError::RecordTooLarge + | super::super::shared_data::BrokerError::QuotaExceeded => { + Status::resource_exhausted("diagnostics capacity exceeded") + } + _ => Status::invalid_argument("invalid diagnostics report"), + } +} + +impl ResourceApi { + async fn volume_token( + &self, + caller: &ResourceCaller, + handle: String, + ) -> Result { + if handle.is_empty() || handle.len() > 16 * 1024 { + return Err(Status::invalid_argument("volume_handle is required")); + } + let files = self.files.clone(); + let feed = self.library.clone(); + let session = caller.session_id.clone(); + self.in_namespace(caller, move |namespace| { + let opened = super::files::open_handle(&files, &feed, namespace, &session, &handle, 0)?; + let info = gamenode_platform::volume::volume_info(Path::new(&opened.approval.root)) + .ok_or_else(|| Status::failed_precondition("volume identity is unavailable"))?; + if info.volume_identity_token.is_empty() { + return Err(Status::failed_precondition( + "volume identity is unavailable", + )); + } + Ok(info.volume_identity_token) + }) + .await + } + + async fn publish_diagnostic( + &self, + mutation: Option, + volume_handle: String, + projection: &'static str, + fields: serde_json::Map, + observed_at: i64, + hash_material: String, + ) -> Result, Status> { + let mutation = mutation.ok_or_else(|| Status::invalid_argument("mutation is required"))?; + let context = mutation + .context + .clone() + .ok_or_else(|| Status::invalid_argument("context is required"))?; + let caller = self + .providers + .authorize_resource(Some(&context), cap::STORAGE_DIAGNOSTICS_PUBLISH)?; + let owner = ResourceApi::data_identity(&caller)?; + let (dataset_id, _) = dataset(projection)?; + let key = super::mutations::mutation_key(&mutation)?.to_owned(); + let expected_revision = mutation.expected_revision.to_string(); + let hash = super::mutations::request_hash(&[ + "storage-diagnostics", + projection, + &volume_handle, + &observed_at.to_string(), + &expected_revision, + &hash_material, + ]); + let _serial = self.mutations.lock.lock().await; + if let Some(original) = self.mutations.replay(&caller, &key, hash)? { + return Ok(Response::new(ReportMutationReply { + report_id: original.resource_id, + revision: original.revision, + outcome: original.outcome, + ..Default::default() + })); + } + let fresh = self + .providers + .authorize_resource(Some(&context), cap::STORAGE_DIAGNOSTICS_PUBLISH)?; + if fresh.grant_revision != caller.grant_revision { + return Err(Status::failed_precondition( + "permissions changed; retry the report", + )); + } + let volume = self.volume_token(&caller, volume_handle).await?; + let mut fields = fields; + fields.insert( + "volume_identity_token".into(), + JsonValue::String(volume.clone()), + ); + let receipt = self + .data + .publish( + Publication { + owner, + dataset_id: dataset_id.into(), + category: None, + class: SharingClass::Sensitive, + schema_id: dataset_id.into(), + schema_version: 1, + fields, + opaque_payload: Vec::new(), + resource_id: volume, + observed_at, + sequence: 0, + source_observation_id: String::new(), + session_id: Some(caller.session_id.clone()), + // The broker's package provenance is reserved for sequenced source-observation + // streams. Diagnostics reports use the authenticated owner plus their typed + // tool/version fields; they do not claim an observation sequence. + publisher: None, + expires_at: None, + }, + super::unix_now()?, + ) + .map_err(broker_status)?; + let outcome = if receipt.duplicate { + MutationOutcome::AlreadyApplied + } else { + MutationOutcome::Applied + }; + let stored = super::mutations::reply(&receipt.record_id, receipt.revision, outcome); + self.mutations.remember(&caller, &key, hash, &stored); + Ok(Response::new(ReportMutationReply { + report_id: receipt.record_id, + revision: receipt.revision, + outcome: outcome as i32, + ..Default::default() + })) + } + + pub(super) async fn publish_benchmark( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + let now = super::unix_now()?; + let fields = benchmark_fields(&request, now)?; + let material = serde_json::to_string(&fields) + .map_err(|_| Status::invalid_argument("invalid benchmark report"))?; + self.publish_diagnostic( + request.mutation, + request.volume_handle, + "benchmark.v1", + fields, + request.observed_at, + material, + ) + .await + } + + pub(super) async fn publish_smart( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + let now = super::unix_now()?; + let fields = smart_fields(&request, now)?; + let material = serde_json::to_string(&fields) + .map_err(|_| Status::invalid_argument("invalid SMART report"))?; + self.publish_diagnostic( + request.mutation, + request.volume_handle, + "smart.v1", + fields, + request.observed_at, + material, + ) + .await + } + + async fn list_diagnostics( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + let page = request + .page + .ok_or_else(|| Status::invalid_argument("page is required"))?; + let context = page + .context + .clone() + .ok_or_else(|| Status::invalid_argument("context is required"))?; + let caller = self + .providers + .authorize_resource(Some(&context), cap::STORAGE_DIAGNOSTICS_READ)?; + let identity = ResourceApi::data_identity(&caller)?; + if request.volume_identity_token.len() > 512 || request.owner_plugin_id.len() > 128 { + return Err(Status::invalid_argument("invalid diagnostics selector")); + } + let (dataset_id, kind) = dataset(&request.projection_id)?; + let cursor = self.take_data_cursor(&page.cursor, &caller.session_id)?; + let size = if page.page_size == 0 { + DEFAULT_PAGE_SIZE + } else { + (page.page_size as usize).min(MAX_PAGE) + }; + let result = self + .data + .query_data( + QueryRequest { + caller: identity, + dataset_id: dataset_id.into(), + record_id: None, + category: None, + selector: None, + delivery: Delivery::History, + page_size: size.min(MAX_PAGE_SIZE), + cursor, + }, + self.shared_authorizer.as_ref(), + super::unix_now()?, + ) + .map_err(broker_status)?; + let reports = result + .records + .iter() + .filter(|record| { + report_matches( + record, + &request.owner_plugin_id, + &request.volume_identity_token, + ) + }) + .map(|record| report(record, kind)) + .collect(); + let next_cursor = match result.next_cursor { + Some(cursor) => self.issue_data_cursor(&caller.session_id, cursor)?, + None => String::new(), + }; + Ok(Response::new(DiagnosticListReply { + reports, + next_cursor, + revision: result.revision, + })) + } + + async fn get_diagnostic( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + if request.report_id.is_empty() || request.report_id.len() > 256 { + return Err(Status::invalid_argument("report_id is required")); + } + let context = request + .context + .clone() + .ok_or_else(|| Status::invalid_argument("context is required"))?; + let caller = self + .providers + .authorize_resource(Some(&context), cap::STORAGE_DIAGNOSTICS_READ)?; + let identity = ResourceApi::data_identity(&caller)?; + let (dataset_id, kind) = dataset(&request.projection_id)?; + let result = self + .data + .query_data( + QueryRequest { + caller: identity, + dataset_id: dataset_id.into(), + record_id: Some(request.report_id.clone()), + category: None, + selector: None, + delivery: Delivery::Query, + page_size: 1, + cursor: None, + }, + self.shared_authorizer.as_ref(), + super::unix_now()?, + ) + .map_err(broker_status)?; + let record = result + .records + .iter() + .find(|record| record.record_id() == request.report_id) + .ok_or_else(|| Status::not_found("diagnostic report not found"))?; + Ok(Response::new(DiagnosticGetReply { + report: Some(report(record, kind)), + })) + } + + async fn watch_diagnostics( + &self, + request: Request, + ) -> Result>, Status> { + let request = request.into_inner(); + let context = request + .context + .clone() + .ok_or_else(|| Status::invalid_argument("context is required"))?; + if request.owner_plugin_id.len() > 128 || request.volume_identity_token.len() > 512 { + return Err(Status::invalid_argument("invalid diagnostics selector")); + } + let caller = self + .providers + .authorize_resource(Some(&context), cap::STORAGE_DIAGNOSTICS_READ)?; + let identity = ResourceApi::data_identity(&caller)?; + let (dataset_id, kind) = dataset(&request.projection_id)?; + let subscription = self + .data + .subscribe( + QueryRequest { + caller: identity, + dataset_id: dataset_id.into(), + record_id: None, + category: None, + selector: None, + delivery: Delivery::Live, + page_size: DEFAULT_PAGE_SIZE, + cursor: None, + }, + request.after_revision, + WATCH_QUEUE, + self.shared_authorizer.clone(), + ) + .map_err(broker_status)?; + let slot = self.watch_slot(&caller.session_id)?; + let providers = self.providers.clone(); + let grant_revision = caller.grant_revision; + let owner = request.owner_plugin_id; + let volume = request.volume_identity_token; + let stream = futures_util::stream::unfold( + Some((subscription, slot, providers, context, owner, volume)), + move |state| async move { + let (subscription, slot, providers, context, owner, volume) = state?; + loop { + let received = tokio::time::timeout( + WATCH_RECHECK, + subscription.recv(super::unix_now().unwrap_or(0)), + ) + .await; + match providers + .authorize_resource(Some(&context), cap::STORAGE_DIAGNOSTICS_READ) + { + Ok(active) if active.grant_revision == grant_revision => {} + Ok(_) => { + return Some(( + Err(Status::failed_precondition( + "permissions changed; watch again", + )), + None, + )); + } + Err(error) => return Some((Err(error), None)), + } + let event = match received { + Ok(Ok(Some(record))) => record, + Ok(Ok(None)) | Err(_) => continue, + Ok(Err(SubscriptionEnd::Revoked)) => { + return Some(( + Err(Status::failed_precondition( + "diagnostics sharing changed; watch again", + )), + None, + )); + } + Ok(Err(SubscriptionEnd::FellBehind)) => { + return Some(( + Err(Status::resource_exhausted( + "diagnostics watch fell behind; list again", + )), + None, + )); + } + }; + if !report_matches(&event, &owner, &volume) { + continue; + } + let value = DiagnosticEvent { + revision: event.revision(), + event_type: "published".into(), + report: Some(report(&event, kind)), + }; + return Some(( + Ok(value), + Some((subscription, slot, providers, context, owner, volume)), + )); + } + }, + ); + Ok(Response::new(Box::pin(stream))) + } +} + +#[tonic::async_trait] +impl storage_diagnostics_server::StorageDiagnostics for ResourceApi { + type WatchStream = WatchStream; + async fn list( + &self, + request: Request, + ) -> Result, Status> { + self.list_diagnostics(request).await + } + async fn get( + &self, + request: Request, + ) -> Result, Status> { + self.get_diagnostic(request).await + } + async fn watch( + &self, + request: Request, + ) -> Result, Status> { + self.watch_diagnostics(request).await + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::plugin_host::sharing_policy::{AccessDecision, AccessRequest, Authorizer}; + use std::collections::HashMap; + + struct ToolNameOnly; + + impl Authorizer for ToolNameOnly { + fn revision(&self, _recipient: &crate::plugin_host::grants::PluginIdentity) -> u64 { + 3 + } + + fn decide(&self, request: &AccessRequest<'_>) -> AccessDecision { + let allowed = + request.dataset_id == BENCHMARK_DATASET && request.fields.contains("tool_name"); + AccessDecision { + allowed, + fields: if allowed { + ["tool_name".to_owned()].into_iter().collect() + } else { + Default::default() + }, + history: allowed && request.delivery == Delivery::History, + live: allowed && request.delivery == Delivery::Live, + revision: 3, + } + } + } + + fn benchmark() -> BenchmarkReportRequest { + BenchmarkReportRequest { + tool_name: "FixtureBench".into(), + tool_version: "2.1".into(), + units: "bytes_per_second".into(), + measurements: HashMap::from([("sequential_read".into(), 10_000.0)]), + measurement_units: HashMap::new(), + measurement_states: HashMap::from([ + ( + "random_read_iops".into(), + DiagnosticValueState::Unsupported as i32, + ), + ( + "sequential_read".into(), + DiagnosticValueState::Available as i32, + ), + ]), + observed_at: 1_000_000, + ..Default::default() + } + } + + #[test] + fn benchmark_ingestion_keeps_units_conditions_and_explicit_unavailable_state() { + let mut value = benchmark(); + value.conditions = Some(prost_types::Struct { + fields: BTreeMap::from([( + "test_size_bytes".into(), + prost_types::Value { + kind: Some(prost_types::value::Kind::NumberValue(4096.0)), + }, + )]), + }); + let fields = benchmark_fields(&value, 1_000_001).unwrap(); + assert_eq!(fields["tool_name"], "FixtureBench"); + assert_eq!( + fields["measurement_units.sequential_read"], + "bytes_per_second" + ); + assert_eq!(fields["measurement_states.random_read_iops"], "unsupported"); + assert_eq!(fields["conditions.test_size_bytes"], 4096.0); + assert!(!fields.contains_key("measurements.random_read_iops")); + } + + #[test] + fn benchmark_rejects_non_finite_values_and_conflicting_availability() { + let mut value = benchmark(); + value.measurements.insert("latency".into(), f64::NAN); + assert_eq!( + benchmark_fields(&value, 1_000_001).unwrap_err().code(), + tonic::Code::InvalidArgument + ); + + let mut value = benchmark(); + value + .measurement_states + .insert("sequential_read".into(), DiagnosticValueState::Error as i32); + assert_eq!( + benchmark_fields(&value, 1_000_001).unwrap_err().code(), + tonic::Code::InvalidArgument + ); + + let mut value = benchmark(); + value.measurement_states.insert( + "missing_value".into(), + DiagnosticValueState::Available as i32, + ); + assert_eq!( + benchmark_fields(&value, 1_000_001).unwrap_err().code(), + tonic::Code::InvalidArgument + ); + } + + #[test] + fn smart_report_retains_per_attribute_units_and_access_denied_state() { + let value = SmartReportRequest { + device_model: "Example SSD".into(), + firmware: "1.0".into(), + attributes: HashMap::from([("temperature_celsius".into(), "42".into())]), + attribute_units: HashMap::from([("temperature_celsius".into(), "celsius".into())]), + attribute_states: HashMap::from([( + "wear_level".into(), + DiagnosticValueState::AccessDenied as i32, + )]), + observed_at: 1_000_000, + ..Default::default() + }; + let fields = smart_fields(&value, 1_000_001).unwrap(); + assert_eq!(fields["attributes.temperature_celsius"], "42"); + assert_eq!(fields["attribute_units.temperature_celsius"], "celsius"); + assert_eq!(fields["attribute_states.wear_level"], "access_denied"); + } + + #[test] + fn a_replacement_volume_has_a_distinct_report_binding() { + let mut first = benchmark(); + first.observed_at = 1_000_000; + let fields = benchmark_fields(&first, 1_000_001).unwrap(); + let owner = super::super::super::grants::PluginIdentity { + plugin_id: "fixture.plugin".into(), + publisher_fingerprint: "ab".repeat(32), + profile_id: "profile-a".into(), + }; + let broker = super::super::super::shared_data::DataBroker::new(); + let publish = |volume: &str, observed_at| Publication { + owner: owner.clone(), + dataset_id: BENCHMARK_DATASET.into(), + category: None, + class: SharingClass::Sensitive, + schema_id: BENCHMARK_DATASET.into(), + schema_version: 1, + fields: fields.clone(), + opaque_payload: Vec::new(), + resource_id: volume.into(), + observed_at, + sequence: 0, + source_observation_id: String::new(), + session_id: Some("session".into()), + publisher: None, + expires_at: None, + }; + broker + .publish(publish("volume-old", 1_000_000), 1_000_001) + .unwrap(); + broker + .publish(publish("volume-replacement", 1_000_001), 1_000_001) + .unwrap(); + let result = broker + .query_data( + QueryRequest { + caller: owner.clone(), + dataset_id: BENCHMARK_DATASET.into(), + record_id: None, + category: None, + selector: None, + delivery: Delivery::History, + page_size: 10, + cursor: None, + }, + &super::super::super::resources::DenySharedData, + 1_000_001, + ) + .unwrap(); + let replacement = result + .records + .iter() + .filter(|record| report_matches(record, "fixture.plugin", "volume-replacement")) + .count(); + assert_eq!(replacement, 1); + assert!( + result + .records + .iter() + .filter(|record| report_matches(record, "fixture.plugin", "volume-replacement")) + .all(|record| record.provenance().source == owner) + ); + assert_eq!( + result + .records + .iter() + .filter(|record| report_matches(record, "fixture.plugin", "volume-old")) + .count(), + 1 + ); + } + + #[test] + fn sensitive_report_read_returns_only_the_approved_projection() { + let owner = super::super::super::grants::PluginIdentity { + plugin_id: "producer.plugin".into(), + publisher_fingerprint: "aa".repeat(32), + profile_id: "profile-a".into(), + }; + let recipient = super::super::super::grants::PluginIdentity { + plugin_id: "consumer.plugin".into(), + publisher_fingerprint: "bb".repeat(32), + profile_id: "profile-a".into(), + }; + let mut fields = serde_json::Map::new(); + fields.insert("tool_name".into(), JsonValue::String("FixtureBench".into())); + fields.insert( + "measurements.sequential_read".into(), + JsonValue::from(1000.0), + ); + let broker = super::super::super::shared_data::DataBroker::new(); + broker + .publish( + Publication { + owner, + dataset_id: BENCHMARK_DATASET.into(), + category: None, + class: SharingClass::Sensitive, + schema_id: BENCHMARK_DATASET.into(), + schema_version: 1, + fields, + opaque_payload: Vec::new(), + resource_id: "volume-token".into(), + observed_at: 1_000_000, + sequence: 0, + source_observation_id: String::new(), + session_id: Some("producer-session".into()), + publisher: None, + expires_at: None, + }, + 1_000_001, + ) + .unwrap(); + let result = broker + .query_data( + QueryRequest { + caller: recipient, + dataset_id: BENCHMARK_DATASET.into(), + record_id: None, + category: None, + selector: None, + delivery: Delivery::History, + page_size: 10, + cursor: None, + }, + &ToolNameOnly, + 1_000_001, + ) + .unwrap(); + assert_eq!(result.records.len(), 1); + assert_eq!( + result.records[0] + .fields() + .keys() + .cloned() + .collect::>(), + vec!["tool_name"] + ); + } +} diff --git a/crates/app/src/plugin_host/resources/files.rs b/crates/app/src/plugin_host/resources/files.rs new file mode 100644 index 000000000..0a07986eb --- /dev/null +++ b/crates/app/src/plugin_host/resources/files.rs @@ -0,0 +1,976 @@ +//! File access of `ResourceHost`: `FilesRequestAccess`, `FilesList`, `FilesRead`, `FilesWrite` +//! and `FilesDelete`. +//! +//! Nothing is reachable at installation: `files.read`, `files.write` and `files.delete` are +//! separate grants the user gives, and even with them a plugin touches only a folder the user +//! approved for that plugin and one installation of one game. A plugin asks +//! (`FilesRequestAccess`), the host asks the user ([`RootApprover`]) to choose the folder and to +//! confirm the complete scope, including every other game that shares it, and the plugin gets +//! opaque handles. Each later call re-derives its authority from the stored approval, the grants +//! the session holds now and the folder as it is on disk, and runs under the plugin's namespace +//! lock, so a revocation cannot slip between the check and the change. +//! +//! The approval is per plugin, installation and kind (`installation`, `save`, `prefix`); the +//! plugin names no path. Write and delete are independent of each other and of read, in the +//! grants and in what the user approved. + +use std::path::{Path, PathBuf}; + +use gamenode_platform::plugin_files::{ + self as confined, ApprovedRoot, Confined, FileError, Identity, Reserved, Target, +}; +use gamenode_platform::plugin_locations::{ + self as locations, Location, MAX_PER_KIND, Os, SystemFolders, +}; +use gamenode_platform::plugin_storage::{FileApproval, ORIGIN_DECLARED, ORIGIN_USER, operation}; +use gamenode_plugin_protocol::{capability as cap, proto::*}; +use sha2::{Digest, Sha256}; +use tonic::{Request, Response, Status}; + +use super::mutations::{mutation_key, reply, request_hash}; +use super::{DEFAULT_PAGE_SIZE, MAX_PAGE_SIZE, ResourceApi}; +use crate::plugin_host::files::{ + APPROVAL_TIMEOUT, AffectedGame, DEFAULT_READ_BYTES, DeclaredFolder, FileAccess, KINDS, + MAX_CHUNK_BYTES, PreviousRootApproval, RootRequest, RootScope, affected_keys, +}; +use crate::plugin_host::library::{CommitGuard, LibraryFeed}; +use crate::plugin_host::notifications::is_plain_line; +use crate::plugin_host::provider::ResourceCaller; +use crate::plugin_host::storage::Namespace; + +const MAX_INSTALLATION_ID_BYTES: usize = 128; +const MAX_HANDLE_BYTES: usize = 16 * 1024; + +fn permission(op: u8) -> &'static str { + match op { + operation::READ => cap::FILES_READ, + operation::WRITE => cap::FILES_WRITE, + _ => cap::FILES_DELETE, + } +} + +fn op_name(op: u8) -> &'static str { + match op { + operation::READ => "read", + operation::WRITE => "write", + _ => "delete", + } +} + +/// How a refusal of the file layer reaches the plugin. None of them carries a path. +pub(crate) fn file_status(error: FileError) -> Status { + match error { + FileError::Denied => Status::permission_denied("the path is outside the approved access"), + FileError::Access => Status::permission_denied("the operating system refused access"), + FileError::NotFound => Status::not_found("not found"), + FileError::NotAFile => Status::failed_precondition("not a regular file"), + FileError::NotADirectory => Status::failed_precondition("not a directory"), + FileError::TooLarge => Status::resource_exhausted("too large"), + FileError::OutOfRange => Status::out_of_range("the offset is beyond the end of the file"), + FileError::RootChanged => Status::failed_precondition( + "the approved folder changed or is unavailable; request access again", + ), + FileError::Io => Status::unavailable("the file operation failed"), + } +} + +pub(crate) fn root_of(approval: &FileApproval) -> ApprovedRoot { + ApprovedRoot { + path: PathBuf::from(&approval.root), + identity: Identity { + volume: approval.root_volume, + node: approval.root_node, + }, + } +} + +fn handle_text(handle: &str) -> Result<(), Status> { + if handle.is_empty() || handle.len() > MAX_HANDLE_BYTES { + return Err(Status::invalid_argument("a file handle is required")); + } + Ok(()) +} + +/// The operations asked for, as approval bits in a fixed order. +fn parse_operations(requested: &[String]) -> Result, Status> { + let mut ops = Vec::new(); + for name in requested { + let op = match name.as_str() { + "read" => operation::READ, + "write" => operation::WRITE, + "delete" => operation::DELETE, + _ => { + return Err(Status::invalid_argument( + "requested_operations holds only \"read\", \"write\" and \"delete\"", + )); + } + }; + if !ops.contains(&op) { + ops.push(op); + } + } + if ops.is_empty() { + return Err(Status::invalid_argument("requested_operations is empty")); + } + ops.sort_unstable(); + Ok(ops) +} + +fn parse_kinds(requested: &[String]) -> Result, Status> { + if requested.is_empty() { + return Ok(vec!["installation".to_owned()]); + } + let mut kinds = Vec::new(); + for kind in requested { + if !KINDS.contains(&kind.as_str()) { + return Err(Status::invalid_argument( + "resource_kinds holds only \"installation\", \"save\" and \"prefix\"", + )); + } + if !kinds.contains(kind) { + kinds.push(kind.clone()); + } + } + Ok(kinds) +} + +/// The longest description of a declared folder, in bytes. +const MAX_DESCRIPTION_BYTES: usize = 120; + +/// What a plugin declared for one kind: well-formed locations with their descriptions, in the +/// plugin's priority order. +type Declared = Vec<(Location, String)>; + +/// Checks the declared suggestions of the request and groups them by kind. Only well-formedness +/// is checked here (a refusal is the plugin's mistake and it is told); whether a suggestion +/// applies to this system is decided later, silently. +fn parse_declared( + declared: &[DeclaredLocation], +) -> Result, Status> { + let mut by_kind: std::collections::HashMap = std::collections::HashMap::new(); + for entry in declared { + match entry.kind.as_str() { + "save" | "prefix" => {} + "installation" => { + return Err(Status::invalid_argument( + "declared_locations are for \"save\" and \"prefix\"; the host knows where an installation is", + )); + } + _ => { + return Err(Status::invalid_argument( + "declared_locations hold only the kinds \"save\" and \"prefix\"", + )); + } + } + let location = locations::parse(&entry.location) + .map_err(|error| Status::invalid_argument(error.to_string()))?; + let description = entry.description.trim(); + if description.len() > MAX_DESCRIPTION_BYTES { + return Err(Status::invalid_argument(format!( + "a description is longer than {MAX_DESCRIPTION_BYTES} bytes" + ))); + } + if !is_plain_line(description) { + return Err(Status::invalid_argument( + "a description must be plain text on one line: no control characters, bidirectional overrides or invisible separators", + )); + } + let list = by_kind.entry(entry.kind.clone()).or_default(); + if list.len() >= MAX_PER_KIND { + return Err(Status::invalid_argument(format!( + "at most {MAX_PER_KIND} declared locations per kind" + ))); + } + list.push((location, description.to_owned())); + } + Ok(by_kind) +} + +fn random_id() -> Result { + let mut bytes = [0u8; 16]; + getrandom::fill(&mut bytes).map_err(|_| Status::internal("could not create an approval id"))?; + Ok(bytes.iter().map(|byte| format!("{byte:02x}")).collect()) +} + +/// The folders of `declared` that apply to this system: expanded, without duplicates and +/// without any that lie in a folder GameNode keeps private (those are dropped quietly, like a +/// suggestion for another system). Blocking: it checks which of them exist. +fn declared_folders(declared: &Declared, reserved: &Reserved) -> Vec { + let mut folders: Vec = Vec::new(); + for (location, description) in declared { + let Some(path) = location.expand(Os::current(), &SystemFolders) else { + continue; + }; + if reserved.is_reserved(&path) || folders.iter().any(|folder| folder.path == path) { + continue; + } + let exists = std::fs::metadata(&path).is_ok_and(|meta| meta.is_dir()); + folders.push(DeclaredFolder { + path, + description: description.clone(), + exists, + }); + } + folders +} + +/// What a handle opens, once every check passed. +pub(crate) struct Opened { + pub(crate) approval: FileApproval, + pub(crate) confined: Confined, + pub(crate) path: Vec, +} + +/// Re-derives the authority of `handle` for `op`: it must belong to this session, name an +/// approval of this namespace that is not revoked and allows `op`, the set of games sharing the +/// folder must be what the user confirmed, and the folder must still be the one approved. +/// `op` 0 asks only that the approval stand, for operations that read no content (inspection). +pub(super) fn open_handle( + files: &FileAccess, + feed: &LibraryFeed, + namespace: &mut Namespace<'_>, + session_id: &str, + handle: &str, + op: u8, +) -> Result { + // A malformed handle, another session's, a revoked approval's and an unknown one are the + // same answer. + let (id, path) = files + .open_handle(session_id, handle) + .ok_or_else(|| Status::not_found("file handle not found"))?; + open_approval(files, feed, namespace, &id, path, op) +} + +/// The approval `approval_id` as it stands: this namespace's, not revoked, allowing `op` (0: any), +/// and the set of games sharing its folder still what the user confirmed. +fn standing_approval( + files: &FileAccess, + feed: &LibraryFeed, + namespace: &mut Namespace<'_>, + approval_id: &str, + op: u8, +) -> Result { + if approval_id.starts_with("lroot-") { + if op != 0 && op != operation::READ { + return Err(Status::permission_denied( + "library roots approve discovery reads only", + )); + } + let root = namespace + .plugin_libraries()? + .into_iter() + .filter(|r| !r.removed) + .flat_map(|r| r.roots) + .find(|r| r.handle_id() == approval_id) + .ok_or_else(|| Status::not_found("library-root handle not found"))?; + return Ok(FileApproval { + id: approval_id.into(), + installation_id: String::new(), + game_id: String::new(), + kind: "library".into(), + root: root.path, + root_volume: root.volume, + root_node: root.node, + volume_token: root.volume_token, + operations: operation::READ, + affected: vec![], + approved_at: 0, + revoked_at: None, + origin: if root.declared { + ORIGIN_DECLARED + } else { + ORIGIN_USER + } + .into(), + }); + } + let approval = namespace + .approval(approval_id)? + .filter(|approval| approval.revoked_at.is_none()) + .ok_or_else(|| Status::not_found("file handle not found"))?; + if op != 0 && approval.operations & op == 0 { + return Err(Status::permission_denied(format!( + "this folder was not approved for {}", + op_name(op) + ))); + } + let current = affected_keys(&files.overlapping(feed, Path::new(&approval.root))); + if current != approval.affected { + return Err(Status::failed_precondition( + "the games that share this folder changed; request access again", + )); + } + Ok(approval) +} + +/// [`open_handle`] for an approval and a path below it that the host already holds (a save +/// profile's folder), rather than a handle a plugin presented. +pub(crate) fn open_approval( + files: &FileAccess, + feed: &LibraryFeed, + namespace: &mut Namespace<'_>, + approval_id: &str, + path: Vec, + op: u8, +) -> Result { + let approval = standing_approval(files, feed, namespace, approval_id, op)?; + check_volume(&approval).map_err(file_status)?; + let confined = Confined::open(&root_of(&approval), &files.reserved).map_err(file_status)?; + Ok(Opened { + approval, + confined, + path, + }) +} + +/// The standing approval a handle of this session names, without opening its folder. +pub(super) fn approval_of_handle( + files: &FileAccess, + feed: &LibraryFeed, + namespace: &mut Namespace<'_>, + session_id: &str, + handle: &str, +) -> Result { + let (id, _) = files + .open_handle(session_id, handle) + .ok_or_else(|| Status::not_found("file handle not found"))?; + standing_approval(files, feed, namespace, &id, 0) +} + +/// [`open_handle`] for operations that only describe a place (inspection): the approval must +/// stand and the handle be the session's, as always, but a folder that cannot be opened (gone, +/// moved, replaced, off limits) is an answer the caller reports, not a refusal: the outer error is +/// a refusal, the inner one says what the place is like. +pub(super) fn open_handle_inspect( + files: &FileAccess, + feed: &LibraryFeed, + namespace: &mut Namespace<'_>, + session_id: &str, + handle: &str, +) -> Result, Status> { + let (id, path) = files + .open_handle(session_id, handle) + .ok_or_else(|| Status::not_found("file handle not found"))?; + open_approval_inspect(files, feed, namespace, &id, path) +} + +/// [`open_handle_inspect`] for an approval and a path the host already holds. +pub(crate) fn open_approval_inspect( + files: &FileAccess, + feed: &LibraryFeed, + namespace: &mut Namespace<'_>, + approval_id: &str, + path: Vec, +) -> Result, Status> { + let approval = standing_approval(files, feed, namespace, approval_id, 0)?; + Ok(check_volume(&approval) + .and_then(|()| Confined::open(&root_of(&approval), &files.reserved)) + .map(|confined| Opened { + approval, + confined, + path, + })) +} + +impl ResourceApi { + /// Authorizes every operation in `ops` and returns the caller as of the last check. + fn authorize_files( + &self, + context: &ServiceContext, + ops: &[u8], + ) -> Result { + let mut caller = None; + for op in ops { + caller = Some( + self.providers + .authorize_resource(Some(context), permission(*op))?, + ); + } + caller.ok_or_else(|| Status::invalid_argument("requested_operations is empty")) + } + + /// A commit-time check for every operation in `ops`. + fn guard_files( + &self, + context: &ServiceContext, + ops: &[u8], + grant_revision: u64, + ) -> CommitGuard { + let guards: Vec = ops + .iter() + .map(|op| self.guard(context.clone(), permission(*op), grant_revision)) + .collect(); + Box::new(move || guards.iter().try_for_each(|guard| guard())) + } + + pub(super) async fn request_files_access( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + let mutation = request + .mutation + .as_ref() + .ok_or_else(|| Status::invalid_argument("mutation is required"))?; + let context = mutation.context.clone().unwrap_or_default(); + let ops = parse_operations(&request.requested_operations)?; + let caller = self.authorize_files(&context, &ops)?; + mutation_key(mutation)?; + let kinds = parse_kinds(&request.resource_kinds)?; + let mut declared = parse_declared(&request.declared_locations)?; + if request.installation_id.is_empty() { + return Err(Status::invalid_argument("installation_id is required")); + } + if request.installation_id.len() > MAX_INSTALLATION_ID_BYTES { + return Err(Status::invalid_argument("installation_id is too long")); + } + let (entry_key, entry) = self.action_target( + &caller, + &context, + &request.game_id, + &request.installation_id, + )?; + let name = entry + .display_name + .clone() + .filter(|name| !name.is_empty()) + .unwrap_or_else(|| entry.name.clone()); + + let mut handles = Vec::new(); + for kind in kinds { + let approval = self + .approval_for( + &caller, + &context, + &ops, + &entry_key, + &entry.installation_id, + &name, + &kind, + entry.game_id, + declared.remove(&kind).unwrap_or_default(), + ) + .await?; + handles.push(FileHandle { + handle: self + .files + .seal_handle(&caller.session_id, &approval.id, &[]), + display_name: format!("{name} ({kind})"), + resource_kind: kind, + writable: approval.operations & operation::WRITE != 0, + }); + } + // The call may have waited for the user; its grants may have changed meanwhile. + self.authorize_files(&context, &ops)?; + Ok(Response::new(FileAccessReply { handles })) + } + + /// The approval that covers `ops` for this installation and kind: the stored one if it is + /// still complete and valid, otherwise a new one the user makes. + #[allow(clippy::too_many_arguments)] + async fn approval_for( + &self, + caller: &ResourceCaller, + context: &ServiceContext, + ops: &[u8], + entry_key: &str, + installation_id: &str, + installation_name: &str, + kind: &str, + game: Option, + declared: Declared, + ) -> Result { + let wanted = ops.iter().fold(0, |bits, op| bits | op); + let files = self.files.clone(); + let feed = self.library.clone(); + let (kind_owned, installation_owned) = (kind.to_owned(), installation_id.to_owned()); + let reusable = self + .in_namespace(caller, { + let (files, feed) = (files.clone(), feed.clone()); + move |namespace| { + let Some(approval) = + namespace.approval_for(&installation_owned, &kind_owned)? + else { + return Ok(None); + }; + let complete = approval.revoked_at.is_none() + && approval.operations & wanted == wanted + && affected_keys(&files.overlapping(&feed, Path::new(&approval.root))) + == approval.affected + && check_volume(&approval).is_ok() + && Confined::open(&root_of(&approval), &files.reserved).is_ok(); + Ok(complete.then_some(approval)) + } + }) + .await?; + if let Some(approval) = reusable { + return Ok(approval); + } + + let previous_approval = self + .in_namespace(caller, { + let installation_id = installation_id.to_owned(); + let kind = kind.to_owned(); + move |namespace| { + Ok(namespace + .approval_for(&installation_id, &kind)? + .filter(|approval| { + approval.revoked_at.is_none() && approval.operations & wanted != wanted + }) + .map(|approval| PreviousRootApproval { + root: PathBuf::from(approval.root), + operations: [ + (operation::READ, "read"), + (operation::WRITE, "write"), + (operation::DELETE, "delete"), + ] + .into_iter() + .filter_map(|(bit, name)| { + (approval.operations & bit != 0).then_some(name) + }) + .collect(), + })) + } + }) + .await?; + + let approver = files.approver().ok_or_else(|| { + Status::failed_precondition("file access approval is not available in this build") + })?; + let resolver = caller.namespace.as_ref().ok_or_else(|| { + Status::failed_precondition("official providers use trusted host adapters") + })?; + let identity = resolver.identity().clone(); + let _waiting = files + .begin_approval(*resolver.storage_owner().key()) + .ok_or_else(|| Status::aborted("a file approval is already waiting for the user"))?; + let names: Vec<&'static str> = ops.iter().map(|op| op_name(*op)).collect(); + + // The plugin's suggestions are expanded and checked for existence off the async thread. + // Nothing is listed or read, and none of it goes back to the plugin. + let host_suggestion = (kind == "installation") + .then(|| feed.folder_of(entry_key).map(PathBuf::from)) + .flatten(); + let reserved_files = files.clone(); + let declared_folders = tokio::task::spawn_blocking(move || { + declared_folders(&declared, &reserved_files.reserved) + }) + .await + .map_err(|_| Status::internal("the suggestions could not be checked"))?; + let preselected = declared_folders + .iter() + .find(|folder| folder.exists) + .map(|folder| folder.path.clone()) + .or(host_suggestion.clone()); + + let chosen = tokio::time::timeout( + APPROVAL_TIMEOUT, + approver.choose_root(RootRequest { + plugin_id: identity.plugin_id.clone(), + publisher_fingerprint: identity.publisher_fingerprint.clone(), + installation_name: installation_name.to_owned(), + kind: kind.to_owned(), + operations: names.clone(), + previously_approved: previous_approval, + suggested: host_suggestion, + declared: declared_folders.clone(), + preselected, + }), + ) + .await + .map_err(|_| Status::deadline_exceeded("the user did not answer in time"))?? + .ok_or_else(|| Status::permission_denied("the user declined to approve a folder"))?; + + // The chosen folder is validated, and the games sharing it found, off the async thread. + let (root, overlapping, declared_by_plugin) = { + let (files, feed) = (files.clone(), feed.clone()); + tokio::task::spawn_blocking(move || { + let root = confined::approve_root(&chosen, &files.reserved).map_err(|error| { + match error { + FileError::Denied => Status::failed_precondition( + "that folder cannot be approved: it is, or is inside, a folder GameNode keeps private", + ), + FileError::NotFound | FileError::NotADirectory => { + Status::failed_precondition("the chosen folder does not exist") + } + other => file_status(other), + } + })?; + let overlapping = files.overlapping(&feed, &root.path); + // The folder counts as the plugin's suggestion only if it is the same folder as + // one it declared, by canonical path, and not the one the host suggested. + let declared_by_plugin = declared_folders.iter().any(|folder| { + folder.exists + && std::fs::canonicalize(&folder.path).is_ok_and(|path| path == root.path) + }); + Ok::<_, Status>((root, overlapping, declared_by_plugin)) + }) + .await + .map_err(|_| Status::internal("the folder could not be checked"))?? + }; + + let confirmed = tokio::time::timeout( + APPROVAL_TIMEOUT, + approver.confirm(RootScope { + plugin_id: identity.plugin_id.clone(), + publisher_fingerprint: identity.publisher_fingerprint.clone(), + installation_name: installation_name.to_owned(), + kind: kind.to_owned(), + operations: names, + root: root.path.clone(), + declared_by_plugin, + affected: overlapping + .iter() + .map(|entry| AffectedGame { + name: entry.name.clone(), + game_id: entry.game_id, + }) + .collect(), + }), + ) + .await + .map_err(|_| Status::deadline_exceeded("the user did not answer in time"))??; + if !confirmed { + return Err(Status::permission_denied("the user declined the access")); + } + + // The user took their time: the grants may have changed, so check them again. + let fresh = self.authorize_files(context, ops)?; + let guard = self.guard_files(context, ops, fresh.grant_revision); + let approval = FileApproval { + id: random_id()?, + installation_id: installation_id.to_owned(), + game_id: game.map(|game| game.to_string()).unwrap_or_default(), + kind: kind.to_owned(), + root: root + .path + .to_str() + .ok_or_else(|| Status::failed_precondition("that folder cannot be approved"))? + .to_owned(), + volume_token: String::new(), + root_volume: root.identity.volume, + root_node: root.identity.node, + operations: wanted, + affected: affected_keys(&overlapping), + approved_at: 0, + revoked_at: None, + origin: if declared_by_plugin { + ORIGIN_DECLARED + } else { + ORIGIN_USER + } + .to_owned(), + }; + self.in_namespace(&fresh, move |namespace| { + let token = gamenode_platform::volume::volume_info(Path::new(&approval.root)) + .map(|info| info.volume_identity_token) + .filter(|token| !token.is_empty()) + .ok_or_else(|| { + Status::failed_precondition( + "volume identity is unknown; folder cannot be approved", + ) + })?; + let approval = FileApproval { + volume_token: token, + approved_at: namespace.now(), + ..approval + }; + namespace.save_approval(&approval, &guard)?; + Ok(approval) + }) + .await + } + + pub(super) async fn list_files( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + let context = request.context.clone().unwrap_or_default(); + let caller = self.authorize_files(&context, &[operation::READ])?; + handle_text(&request.directory_handle)?; + let limit = match request.page_size as usize { + 0 => DEFAULT_PAGE_SIZE, + size => size.min(MAX_PAGE_SIZE), + }; + let (files, feed) = (self.files.clone(), self.library.clone()); + let session = caller.session_id.clone(); + let reply = self + .in_namespace(&caller, move |namespace| { + let opened = open_handle( + &files, + &feed, + namespace, + &session, + &request.directory_handle, + operation::READ, + )?; + let after = if request.cursor.is_empty() { + None + } else { + Some( + files + .open_cursor(&session, &request.directory_handle, &request.cursor) + .ok_or_else(|| Status::invalid_argument("invalid files cursor"))?, + ) + }; + let (entries, more) = opened + .confined + .list(&opened.path, after.as_deref(), limit) + .map_err(file_status)?; + let next_cursor = match entries.last() { + Some(last) if more => { + files.seal_cursor(&session, &request.directory_handle, &last.name) + } + _ => String::new(), + }; + let entries = entries + .into_iter() + .filter_map(|entry| { + let mut child = opened.path.clone(); + child.push(entry.name.clone()); + FileAccess::fits_handle(&child).then(|| FileEntry { + handle: files.seal_handle(&session, &opened.approval.id, &child), + name: entry.name, + directory: entry.directory, + size_bytes: entry.size, + modified_at: entry.modified, + }) + }) + .collect(); + Ok(FilesListReply { + entries, + next_cursor, + }) + }) + .await?; + // The listing was made for a call that may since have lost its permission. + self.authorize_files(&context, &[operation::READ])?; + Ok(Response::new(reply)) + } + + pub(super) async fn read_file( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + let context = request.context.clone().unwrap_or_default(); + let caller = self.authorize_files(&context, &[operation::READ])?; + handle_text(&request.file_handle)?; + let budget = match request.max_bytes { + 0 => DEFAULT_READ_BYTES, + bytes => usize::try_from(bytes) + .unwrap_or(usize::MAX) + .min(MAX_CHUNK_BYTES), + }; + let (files, feed) = (self.files.clone(), self.library.clone()); + let session = caller.session_id.clone(); + let reply = self + .in_namespace(&caller, move |namespace| { + let opened = open_handle( + &files, + &feed, + namespace, + &session, + &request.file_handle, + operation::READ, + )?; + let (contents, eof) = opened + .confined + .read(&opened.path, request.offset, budget) + .map_err(file_status)?; + Ok(FileReadReply { + next_offset: request.offset + contents.len() as u64, + contents, + eof, + }) + }) + .await?; + self.authorize_files(&context, &[operation::READ])?; + Ok(Response::new(reply)) + } + + /// The bytes of the file `handle` names, for a picture that is about to become the cover of + /// `installation_id`: at most `limit + 1` bytes, so the caller can tell that the file is over + /// its bound without reading all of it. The handle must be one of this session, from an + /// approval of this same installation that allows reading, and every check of a normal read + /// applies. Runs on a blocking worker under the plugin's namespace lock. + pub(super) async fn read_handle_image( + &self, + caller: &ResourceCaller, + handle: &str, + installation_id: &str, + limit: usize, + ) -> Result, Status> { + handle_text(handle)?; + let (files, feed) = (self.files.clone(), self.library.clone()); + let session = caller.session_id.clone(); + let handle = handle.to_owned(); + let installation_id = installation_id.to_owned(); + self.in_namespace(caller, move |namespace| { + let opened = open_handle(&files, &feed, namespace, &session, &handle, operation::READ)?; + // A file the user approved for another game's folder is not a picture for this one. + if opened.approval.installation_id != installation_id { + return Err(Status::permission_denied( + "this file handle belongs to another library entry", + )); + } + let (bytes, _) = opened + .confined + .read(&opened.path, 0, limit.saturating_add(1)) + .map_err(file_status)?; + Ok(bytes) + }) + .await + } + + pub(super) async fn write_file( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + let mutation = request + .mutation + .as_ref() + .ok_or_else(|| Status::invalid_argument("mutation is required"))?; + let context = mutation.context.clone().unwrap_or_default(); + let caller = self.authorize_files(&context, &[operation::WRITE])?; + let idempotency = mutation_key(mutation)?.to_owned(); + if mutation.expected_revision != 0 { + return Err(Status::invalid_argument( + "files carry no revision; expected_revision must be 0", + )); + } + handle_text(&request.file_handle)?; + if !request.name.is_empty() && !confined::valid_new_name(&request.name) { + return Err(Status::invalid_argument( + "name must be one plain file name: no separators, no `.`/`..`, no \\ : * ? \" < > |, \ + no trailing space or dot and no reserved device name", + )); + } + if request.contents.len() > MAX_CHUNK_BYTES { + return Err(Status::invalid_argument(format!( + "contents are larger than {MAX_CHUNK_BYTES} bytes; write in several calls" + ))); + } + let hash = request_hash(&[ + "files.write", + &request.file_handle, + &request.name, + &request.offset.to_string(), + if request.truncate { "t" } else { "k" }, + &format!("{:x}", Sha256::digest(&request.contents)), + ]); + let guard = self.guard_files(&context, &[operation::WRITE], caller.grant_revision); + let (files, feed) = (self.files.clone(), self.library.clone()); + let mutations = self.mutations.clone(); + let remember_as = caller.clone(); + let session = caller.session_id.clone(); + let answered = self + .in_namespace(&caller, move |namespace| { + if let Some((original, _)) = + mutations.replay_with(&remember_as, &idempotency, hash)? + { + return Ok(original); + } + let opened = open_handle( + &files, + &feed, + namespace, + &session, + &request.file_handle, + operation::WRITE, + )?; + let (target, written) = if request.name.is_empty() { + (Target::Existing(&opened.path), opened.path.clone()) + } else { + let mut child = opened.path.clone(); + child.push(request.name.clone()); + ( + Target::Create { + directory: &opened.path, + name: &request.name, + }, + child, + ) + }; + if !FileAccess::fits_handle(&written) { + return Err(Status::invalid_argument("the path is too long")); + } + guard()?; + opened + .confined + .write(target, request.offset, &request.contents, request.truncate) + .map_err(file_status)?; + let handle = files.seal_handle(&session, &opened.approval.id, &written); + let answer = reply(&handle, 0, MutationOutcome::Applied); + mutations.remember_with(&remember_as, &idempotency, hash, &answer, 0); + Ok(answer) + }) + .await?; + Ok(Response::new(answered)) + } + + pub(super) async fn delete_file( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + let mutation = request + .mutation + .as_ref() + .ok_or_else(|| Status::invalid_argument("mutation is required"))?; + let context = mutation.context.clone().unwrap_or_default(); + let caller = self.authorize_files(&context, &[operation::DELETE])?; + let idempotency = mutation_key(mutation)?.to_owned(); + if mutation.expected_revision != 0 { + return Err(Status::invalid_argument( + "files carry no revision; expected_revision must be 0", + )); + } + handle_text(&request.file_handle)?; + let hash = request_hash(&["files.delete", &request.file_handle]); + let guard = self.guard_files(&context, &[operation::DELETE], caller.grant_revision); + let (files, feed) = (self.files.clone(), self.library.clone()); + let mutations = self.mutations.clone(); + let remember_as = caller.clone(); + let session = caller.session_id.clone(); + let answered = self + .in_namespace(&caller, move |namespace| { + if let Some((original, _)) = + mutations.replay_with(&remember_as, &idempotency, hash)? + { + return Ok(original); + } + let opened = open_handle( + &files, + &feed, + namespace, + &session, + &request.file_handle, + operation::DELETE, + )?; + guard()?; + opened.confined.delete(&opened.path).map_err(file_status)?; + let answer = reply(&request.file_handle, 0, MutationOutcome::Applied); + mutations.remember_with(&remember_as, &idempotency, hash, &answer, 0); + Ok(answer) + }) + .await?; + Ok(Response::new(answered)) + } +} + +// Blocking; callers run in_namespace on a worker. Never refresh approval from observation. +fn check_volume(approval: &FileApproval) -> Result<(), FileError> { + let current = gamenode_platform::volume::volume_info(Path::new(&approval.root)); + if approval.volume_token.is_empty() + || !current.is_some_and(|info| { + !info.volume_identity_token.is_empty() + && info.volume_identity_token == approval.volume_token + }) + { + return Err(FileError::RootChanged); + } + Ok(()) +} diff --git a/crates/app/src/plugin_host/resources/games.rs b/crates/app/src/plugin_host/resources/games.rs new file mode 100644 index 000000000..e9b77d122 --- /dev/null +++ b/crates/app/src/plugin_host/resources/games.rs @@ -0,0 +1,679 @@ +//! `GamesRequestLaunch` and `GamesRequestInstall` of `ResourceHost` (tasks 7.2 and 10.10, +//! design sections 11 and 20). +//! +//! Both start something on the user's computer, so neither runs without the user's intent (see +//! `plugin_host::intents`). The request names a game and carries no parameter of what to start: +//! a launch starts the game's detected target unchanged, an install opens the provider's own +//! install flow. The answer is always a job (task 7.1): with no intent the job waits, queued, +//! while the host asks the user, who can approve, decline, or let it time out, and the plugin +//! can cancel it. + +use gamenode_plugin_protocol::{capability as cap, proto::*}; +use tonic::{Request, Response, Status}; + +use super::mutations::{game_id, request_hash, unavailable}; +use super::{ResourceApi, Scope}; +use crate::plugin_host::intents::{Binding, ConfirmationRequest, Operation, Pending, Verdict}; +use crate::plugin_host::jobs::{JobContext, JobOwner, Outcome, work}; +use crate::plugin_host::library::Projected; +use crate::plugin_host::provider::ResourceCaller; + +const MAX_KEY_BYTES: usize = 128; +const MAX_INSTALLATION_ID_BYTES: usize = 128; +/// What a job says while the user has not answered. +const AWAITING: &str = "awaiting confirmation"; + +/// One request, whatever its operation. +struct Action { + context: Option, + permission: &'static str, + operation: Operation, + game_id: String, + installation_id: String, + /// The entry revision the plugin read; `None` for an install, which has none. + expected_revision: Option, + intent: String, + key: String, + custom_recipe: Option, + custom_dispatch: Option, + custom_resources: Vec, +} + +struct ExtensionActionShutdown { + providers: crate::plugin_host::provider::ProviderApi, + session_id: String, +} + +impl Drop for ExtensionActionShutdown { + fn drop(&mut self) { + self.providers.request_shutdown_session(&self.session_id); + } +} + +/// How the request was authorized before its job started. +enum Authorized { + /// A pre-issued intent was spent, or the user had remembered this plugin and game. + Already, + /// The user must be asked; the slot is held until the answer. + Ask(Pending), +} + +fn text_ok(text: &str, limit: usize) -> bool { + !text.is_empty() && text.len() <= limit && !text.chars().any(char::is_control) +} + +fn code_word(status: &Status) -> &'static str { + match status.code() { + tonic::Code::Unimplemented => "unsupported", + tonic::Code::FailedPrecondition => "unavailable", + tonic::Code::NotFound => "not_found", + _ => "failed", + } +} + +fn not_found() -> Status { + Status::not_found("library entry not found") +} + +impl ResourceApi { + pub(super) async fn request_custom_action( + &self, + request: CustomLaunchRequest, + recipe: gamenode_core::library::CustomLaunchRecipe, + custom_dispatch: crate::plugin_host::library::CustomLaunchDispatch, + custom_resources: Vec, + ) -> Result { + self.request_action(Action { + context: request.context, + permission: cap::GAME_CUSTOM_LAUNCH, + operation: Operation::CustomLaunch, + game_id: request.game_id, + installation_id: request.installation_id, + expected_revision: Some(request.expected_revision), + intent: request.user_intent_id, + key: request.idempotency_key, + custom_recipe: Some(recipe), + custom_dispatch: Some(custom_dispatch), + custom_resources, + }) + .await + } + + pub(super) async fn request_launch( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + let job = self + .request_action(Action { + context: request.context, + permission: cap::GAME_LAUNCH, + operation: Operation::Launch, + game_id: request.game_id, + installation_id: request.installation_id, + expected_revision: Some(request.expected_revision), + intent: request.user_intent_id, + key: request.idempotency_key, + custom_recipe: None, + custom_dispatch: None, + custom_resources: Vec::new(), + }) + .await?; + Ok(Response::new(GameLaunchReply { + job_id: job.job_id, + state: job.state, + refusal_code: String::new(), + message: job.message, + })) + } + + pub(super) async fn request_install( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + self.request_action(Action { + context: request.context, + permission: cap::GAMES_INSTALL, + operation: Operation::Install, + game_id: request.game_id, + installation_id: request.installation_id, + expected_revision: None, + intent: request.user_intent_id, + key: request.idempotency_key, + custom_recipe: None, + custom_dispatch: None, + custom_resources: Vec::new(), + }) + .await + .map(Response::new) + } + + /// The entry a request names, within what the caller may start: a provider session names its + /// own entries; an extension session names only the game the user selected for it. + pub(super) fn action_target( + &self, + caller: &ResourceCaller, + context: &ServiceContext, + game: &str, + installation_id: &str, + ) -> Result<(String, Projected), Status> { + if !text_ok(installation_id, MAX_INSTALLATION_ID_BYTES) { + return Err(Status::invalid_argument( + "installation_id is required: 1 to 128 bytes", + )); + } + let wanted = game_id(game)?; + if context.session_kind() != SessionKind::Extension { + return self.own_entry(caller, installation_id, wanted); + } + let target = context.target_game.as_ref().ok_or_else(not_found)?; + if target.installation_id != installation_id { + return Err(not_found()); + } + // The user chose this game for the extension; reading the whole library is not needed + // and does not widen it. + let everything = Scope { + own_provider: caller.provider_id.clone(), + read_all: true, + provider_filter: None, + }; + self.library + .target(&everything, installation_id) + .filter(|(_, entry)| { + entry.game_id.map(|id| id.to_string()).unwrap_or_default() == target.game_id + && (wanted.is_none() || wanted == entry.game_id) + }) + .ok_or_else(not_found) + } + + async fn request_action(&self, action: Action) -> Result { + let caller = self + .providers + .authorize_resource(action.context.as_ref(), action.permission)?; + let context = action.context.clone().unwrap_or_default(); + if !text_ok(&action.key, MAX_KEY_BYTES) { + return Err(Status::invalid_argument( + "idempotency_key is required: 1 to 128 bytes without control characters", + )); + } + if !action.intent.is_empty() && !text_ok(&action.intent, MAX_KEY_BYTES) { + return Err(Status::invalid_argument( + "user_intent_id is at most 128 bytes without control characters", + )); + } + let owner = JobOwner::of(&caller)?; + let identity = caller + .namespace + .as_ref() + .ok_or_else(|| Status::failed_precondition("official providers launch through Core"))? + .identity() + .clone(); + let (entry_key, entry) = + self.action_target(&caller, &context, &action.game_id, &action.installation_id)?; + let current_revision = if context.session_kind() == SessionKind::Extension { + context + .target_game + .as_ref() + .and_then(|target| target.revision.parse::().ok()) + } else { + Some(entry.revision) + }; + if action + .expected_revision + .is_some_and(|expected| current_revision != Some(expected)) + { + return Err(Status::failed_precondition( + "the game changed since it was read; read it again", + )); + } + let host = self.library.host().ok_or_else(unavailable)?; + let launching = matches!( + action.operation, + Operation::Launch | Operation::CustomLaunch + ); + let fingerprint = if launching { + host.launch_fingerprint(entry_key.clone()).await? + } else { + 0 + }; + let (plan_fingerprint, launch_plan_review) = if launching { + let plan = super::super::launch_plan::resolve( + &caller, + &entry, + fingerprint, + action.custom_recipe.as_ref(), + action.custom_dispatch.as_ref(), + &action.custom_resources, + )?; + tokio::task::spawn_blocking(move || { + let fingerprint = plan + .fingerprint() + .map_err(|_| Status::failed_precondition("the launch plan is invalid"))?; + let review = super::super::launch_plan::review(&plan, fingerprint.clone()); + Ok::<_, Status>((fingerprint, Some(review))) + }) + .await + .map_err(|_| Status::internal("launch plan fingerprint worker failed"))?? + } else { + (String::new(), None) + }; + let game = entry.game_id.map(|id| id.to_string()).unwrap_or_default(); + let recipe_revision = action + .custom_recipe + .as_ref() + .map(|recipe| recipe.revision) + .unwrap_or_default(); + let binding = Binding { + plugin_id: identity.plugin_id.clone(), + publisher_fingerprint: identity.publisher_fingerprint.clone(), + profile_epoch: caller.profile_epoch, + game_id: game.clone(), + installation_id: entry.installation_id.clone(), + operation: action.operation, + target_revision: fingerprint, + recipe_id: action + .custom_recipe + .as_ref() + .map(|recipe| recipe.recipe_id.clone()) + .unwrap_or_default(), + recipe_revision, + plan_fingerprint: plan_fingerprint.clone(), + }; + let custom_recipe_id = action + .custom_recipe + .as_ref() + .map(|recipe| recipe.recipe_id.as_str()) + .unwrap_or_default(); + let custom_recipe_revision = action + .custom_recipe + .as_ref() + .map(|recipe| recipe.revision.to_string()) + .unwrap_or_default(); + let hash = request_hash(&[ + "game-action", + action.operation.as_str(), + &action.game_id, + &action.installation_id, + &action.expected_revision.unwrap_or(0).to_string(), + &action.intent, + custom_recipe_id, + &custom_recipe_revision, + &plan_fingerprint, + ]); + + // Retries and first requests are decided together, so a retry never spends a second + // intent or opens a second dialog. + let _serial = self.mutations.lock.lock().await; + if let Some(job) = self.jobs.replay(&owner, &action.key, hash)? { + return Ok(job); + } + let authorized = if (!action.intent.is_empty() + && self.intents.redeem(&binding, &action.intent).is_ok()) + || self.remembered(&caller, &binding).await? + { + Authorized::Already + } else { + if !self.intents.can_confirm() { + return Err(Status::failed_precondition( + "this GameNode build cannot ask for confirmations yet", + )); + } + Authorized::Ask(self.intents.begin_pending(&binding)?) + }; + let awaiting = matches!(authorized, Authorized::Ask(_)).then_some(AWAITING); + + let api = self.clone(); + let work_caller = caller.clone(); + let work_context = context.clone(); + let extension_session = context.session_kind() == SessionKind::Extension; + let extension_session_id = context.session_id.clone(); + let request = ConfirmationRequest { + plugin_id: identity.plugin_id, + publisher_fingerprint: identity.publisher_fingerprint, + game_name: entry + .display_name + .clone() + .unwrap_or_else(|| entry.name.clone()), + operation: action.operation, + details: vec![], + launch_plan: launch_plan_review, + }; + let (game_arg, installation_arg, operation) = ( + action.game_id.clone(), + action.installation_id.clone(), + action.operation, + ); + let custom_recipe = action.custom_recipe.clone(); + let custom_dispatch = action.custom_dispatch.clone(); + let custom_resources = action.custom_resources.clone(); + let permission = action.permission; + let run = work(move |ctx| async move { + let _shutdown = extension_session.then(|| ExtensionActionShutdown { + providers: api.providers.clone(), + session_id: extension_session_id, + }); + api.run_action( + ctx, + &work_caller, + work_context, + permission, + authorized, + request, + binding, + (&game_arg, &installation_arg), + operation, + custom_recipe, + custom_dispatch, + custom_resources, + ) + .await + }); + let (job, _) = self.start_job( + &caller, + context, + action.permission, + &action.key, + hash, + awaiting, + run, + )?; + Ok(job) + } + + /// Whether the user remembered this plugin for this game and operation, and the game's + /// target is still the one they approved. + async fn remembered(&self, caller: &ResourceCaller, binding: &Binding) -> Result { + let (installation, operation) = + (binding.installation_id.clone(), binding.operation.as_str()); + let approval = self + .in_namespace(caller, move |namespace| { + namespace.intent_approval(&installation, operation) + }) + .await?; + Ok(approval.is_some_and(|approval| { + approval.game_id == binding.game_id + && approval.target_revision == binding.target_revision + && approval.recipe_id == binding.recipe_id + && approval.recipe_revision == binding.recipe_revision + && approval.plan_fingerprint == binding.plan_fingerprint + })) + } + + /// The job's work: wait for the user if needed, remember the answer if asked to, check + /// everything again right before dispatching, then hand the entry to the library's own path. + #[allow(clippy::too_many_arguments)] + async fn run_action( + &self, + mut ctx: JobContext, + caller: &ResourceCaller, + context: ServiceContext, + permission: &'static str, + authorized: Authorized, + request: ConfirmationRequest, + binding: Binding, + names: (&str, &str), + operation: Operation, + custom_recipe: Option, + custom_dispatch: Option, + custom_resources: Vec, + ) -> Outcome { + if let Authorized::Ask(pending) = authorized { + let verdict = tokio::select! { + verdict = self.intents.confirm(request.clone()) => verdict, + () = ctx.cancelled() => return Outcome::cancelled("withdrawn before the user answered"), + }; + drop(pending); + match verdict { + Ok(Verdict::Approved { remember }) => { + if remember + && let Err(status) = self + .remember_answer(caller, &context, permission, &binding, &request) + .await + { + return Outcome::stopped(&status); + } + } + Ok(Verdict::Declined) => { + return Outcome::failed("declined", "the user declined"); + } + Ok(Verdict::TimedOut) => { + return Outcome::failed("timed_out", "the user did not answer in time"); + } + Err(_) => { + return Outcome::failed("unavailable", "the host could not ask the user"); + } + } + } + if ctx.start().is_err() { + return Outcome::cancelled("withdrawn before it started"); + } + // The user may have taken minutes, or the intent seconds: nothing earlier is trusted. + if let Err(status) = ctx.check() { + return Outcome::stopped(&status); + } + let Some(host) = self.library.host() else { + return Outcome::failed("unavailable", "the library is not available"); + }; + let (entry_key, entry) = match self.action_target(caller, &context, names.0, names.1) { + Ok(found) => found, + Err(status) => return Outcome::failed(code_word(&status), "the game is not available"), + }; + if matches!(operation, Operation::Launch | Operation::CustomLaunch) { + match host.launch_fingerprint(entry_key.clone()).await { + Ok(current) if current == binding.target_revision => {} + Ok(_) => { + return Outcome::failed( + "target_changed", + "the game's launch target changed; ask again", + ); + } + Err(status) => return Outcome::failed(code_word(&status), status.message()), + } + } + if entry.game_id.map(|id| id.to_string()).unwrap_or_default() != binding.game_id { + return Outcome::failed("target_changed", "the game changed; ask again"); + } + if ctx.check().is_err() { + return Outcome::cancelled("cancelled before it was started"); + } + if operation == Operation::CustomLaunch + && let Some(recipe) = custom_recipe.as_ref() + { + let Some(dispatch) = custom_dispatch.as_ref() else { + return Outcome::failed("unavailable", "the custom launch recipe is unavailable"); + }; + let current_resources = match self + .revalidate_custom_handles(caller, &context, &entry_key, recipe, dispatch) + .await + { + Ok(resources) => resources, + Err(status) => return Outcome::stopped(&status), + }; + match host.launch_fingerprint(entry_key.clone()).await { + Ok(current) if current == binding.target_revision => {} + Ok(_) => { + return Outcome::failed( + "target_changed", + "the game's launch target changed; ask again", + ); + } + Err(status) => return Outcome::stopped(&status), + } + match host + .custom_launch_recipe( + super::mutations::mutation_owner(caller), + recipe.recipe_id.clone(), + ) + .await + { + Ok(Some(current)) if current == *recipe => {} + Ok(_) => { + return Outcome::failed( + "recipe_changed", + "the custom launch recipe changed; ask again", + ); + } + Err(status) => return Outcome::stopped(&status), + } + if let Err(status) = ctx.check() { + return Outcome::stopped(&status); + } + let current_plan = match super::super::launch_plan::resolve( + caller, + &entry, + binding.target_revision, + Some(recipe), + Some(dispatch), + ¤t_resources, + ) { + Ok(plan) => plan, + Err(status) => return Outcome::stopped(&status), + }; + let current_fingerprint = match tokio::task::spawn_blocking(move || { + current_plan.fingerprint() + }) + .await + { + Ok(Ok(fingerprint)) => fingerprint, + _ => { + return Outcome::failed("target_changed", "the launch plan changed; ask again"); + } + }; + if current_fingerprint != binding.plan_fingerprint { + return Outcome::failed("target_changed", "the launch plan changed; ask again"); + } + } else if operation == Operation::Launch { + let current_plan = match super::super::launch_plan::resolve( + caller, + &entry, + binding.target_revision, + None, + None, + &custom_resources, + ) { + Ok(plan) => plan, + Err(status) => return Outcome::stopped(&status), + }; + let current_fingerprint = match tokio::task::spawn_blocking(move || { + current_plan.fingerprint() + }) + .await + { + Ok(Ok(fingerprint)) => fingerprint, + _ => { + return Outcome::failed("target_changed", "the launch plan changed; ask again"); + } + }; + if current_fingerprint != binding.plan_fingerprint { + return Outcome::failed("target_changed", "the launch plan changed; ask again"); + } + } + // The final spawn and a permission revocation must have a defined ordering. Holding the + // provider commit guard through dispatch ensures a revocation that wins first prevents + // the launch; a revocation after spawn does not terminate the running game. + let _launch_guard = if operation == Operation::CustomLaunch { + match self + .providers + .authorize_resource_commit(&context, permission) + .await + { + Ok((current, guard)) if current.grant_revision == caller.grant_revision => { + Some(guard) + } + Ok(_) => { + return Outcome::failed("revoked", "plugin permissions changed before launch"); + } + Err(status) => return Outcome::stopped(&status), + } + } else { + None + }; + if let Err(status) = ctx.check() { + return Outcome::stopped(&status); + } + let dispatch = if operation == Operation::CustomLaunch { + match custom_dispatch { + Some(dispatch) => { + if let Some(namespace) = &caller.namespace { + let identity = namespace.identity(); + let requires_files = custom_recipe.as_ref().is_some_and(|recipe| { + recipe.executable.is_some() + || recipe.working_directory.is_some() + || !recipe.executable_handle.is_empty() + || !recipe.working_directory_handle.is_empty() + || !recipe.runtime_handle.is_empty() + }); + let authority = crate::plugin_host::library::UserLaunchAuthority { + plugin_id: identity.plugin_id.clone(), + publisher_fingerprint: identity.publisher_fingerprint.clone(), + profile_id: identity.profile_id.clone(), + profile_epoch: caller.profile_epoch, + grant_revision: None, + requires_files, + }; + host.launch_custom_for_entry_authorized(dispatch, entry_key, authority) + .await + } else { + host.launch_custom_for_entry(dispatch, entry_key).await + } + } + None => Err(tonic::Status::failed_precondition( + "custom launch recipe is unavailable", + )), + } + } else { + host.open_entry(entry_key, operation == Operation::Install) + .await + }; + match dispatch { + Ok(()) => Outcome::succeeded( + "opened", + match operation { + Operation::Launch => "the game was started", + Operation::CustomLaunch => "the custom game launch was started", + Operation::Install => "the provider's install flow was opened", + Operation::BackupRestore => unreachable!("restores use the backup adapter"), + Operation::RuntimeSessionContext => { + unreachable!("runtime contexts do not dispatch game actions") + } + }, + ), + Err(status) => Outcome::failed(code_word(&status), status.message()), + } + } + + /// Records that the user allowed this plugin to do this to this game. + async fn remember_answer( + &self, + caller: &ResourceCaller, + context: &ServiceContext, + permission: &'static str, + binding: &Binding, + request: &ConfirmationRequest, + ) -> Result<(), Status> { + let mut bytes = [0_u8; 16]; + getrandom::fill(&mut bytes).map_err(|_| Status::internal("no source of randomness"))?; + let approval = gamenode_platform::plugin_storage::IntentApproval { + id: bytes.iter().map(|b| format!("{b:02x}")).collect(), + game_id: binding.game_id.clone(), + installation_id: binding.installation_id.clone(), + operation: binding.operation.as_str().to_owned(), + target_revision: binding.target_revision, + recipe_id: binding.recipe_id.clone(), + recipe_revision: binding.recipe_revision, + plan_fingerprint: binding.plan_fingerprint.clone(), + game_name: request.game_name.chars().take(120).collect(), + approved_at: 0, + }; + let guard = self.guard(context.clone(), permission, caller.grant_revision); + self.in_namespace(caller, move |namespace| { + let approval = gamenode_platform::plugin_storage::IntentApproval { + approved_at: namespace.now(), + ..approval + }; + namespace.save_intent_approval(&approval, &guard) + }) + .await + } +} diff --git a/crates/app/src/plugin_host/resources/jobs.rs b/crates/app/src/plugin_host/resources/jobs.rs new file mode 100644 index 000000000..3a43d057c --- /dev/null +++ b/crates/app/src/plugin_host/resources/jobs.rs @@ -0,0 +1,179 @@ +//! `JobsGet`, `JobsWatch` and `JobsCancel` of `ResourceHost` (task 7.1). +//! +//! A job is addressed by its opaque id alone and belongs to the caller's host-authenticated +//! plugin/publisher/profile ([`JobOwner`]); see `plugin_host::jobs` for the registry. These +//! calls have no permission of their own: after finding the job under the caller's own owner, +//! each one needs the permission of the operation that created it, checked again before every +//! event a watch delivers. An id that is unknown, someone else's, from an earlier profile or +//! forgotten is the same `NOT_FOUND`. + +use std::sync::Arc; + +use gamenode_plugin_protocol::proto::*; +use tokio::sync::mpsc; +use tokio_stream::wrappers::ReceiverStream; +use tonic::{Request, Response, Status}; + +use super::mutations::mutation_key; +use super::{ResourceApi, WATCH_QUEUE, WATCH_RECHECK}; +use crate::plugin_host::jobs::{Fence, JobOwner, Submission, Work}; +use crate::plugin_host::provider::ResourceCaller; + +const MAX_JOB_ID_BYTES: usize = 128; + +fn job_id(id: &str) -> Result<&str, Status> { + if id.is_empty() || id.len() > MAX_JOB_ID_BYTES { + return Err(Status::invalid_argument( + "job_id is required: 1 to 128 bytes", + )); + } + Ok(id) +} + +impl ResourceApi { + /// Authenticates the call, finds the job under the caller's own owner and checks the + /// permission of the operation that created it. Returns the caller, the owner, the job id and + /// that permission. + fn job_access<'a>( + &self, + context: Option<&ServiceContext>, + id: &'a str, + ) -> Result<(ResourceCaller, JobOwner, &'a str, &'static str), Status> { + let caller = self.providers.authorize_resource_session(context)?; + let owner = JobOwner::of(&caller)?; + let id = job_id(id)?; + let permission = self.jobs.permission(&owner, id)?; + self.providers.authorize_resource(context, permission)?; + Ok((caller, owner, id, permission)) + } + + pub(super) async fn get_job( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + let (_, owner, id, _) = self.job_access(request.context.as_ref(), &request.job_id)?; + self.jobs.get(&owner, id).map(Response::new) + } + + pub(super) async fn cancel_job( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + let mutation = request + .mutation + .as_ref() + .ok_or_else(|| Status::invalid_argument("mutation is required"))?; + // Cancelling is idempotent in itself (a second request finds the first one's result), so + // no outcome is stored; the key is still checked for its shape like every mutation's. + mutation_key(mutation)?; + let (_, owner, id, _) = self.job_access(mutation.context.as_ref(), &request.job_id)?; + self.jobs.cancel(&owner, id).await.map(Response::new) + } + + pub(super) async fn watch_job( + &self, + request: Request, + ) -> Result>, Status> { + let request = request.into_inner(); + let context = request.context.clone(); + let (caller, owner, id, permission) = self.job_access(context.as_ref(), &request.job_id)?; + let id = id.to_owned(); + let slot = self.watch_slot(&caller.session_id)?; + let (mut pending, mut over, mut changed) = + self.jobs + .events_after(&owner, &id, request.after_sequence)?; + let (tx, rx) = mpsc::channel(WATCH_QUEUE); + let providers = self.providers.clone(); + let jobs = self.jobs.clone(); + let mut position = request.after_sequence; + tokio::spawn(async move { + let _slot = slot; + // Every delivery rechecks the session, profile and the creating permission; losing + // it ends the stream with the denial rather than going on telling the plugin. + let check = || providers.authorize_resource(context.as_ref(), permission); + let mut recheck = tokio::time::interval(WATCH_RECHECK); + recheck.tick().await; + loop { + for event in pending.drain(..) { + if let Err(status) = check() { + let _ = tx.send(Err(status)).await; + return; + } + position = event.sequence; + if tx.send(Ok(event)).await.is_err() { + return; + } + } + if over { + return; + } + tokio::select! { + _ = changed.changed() => {} + _ = recheck.tick() => { + if let Err(status) = check() { + let _ = tx.send(Err(status)).await; + return; + } + } + () = tx.closed() => return, + } + match jobs.events_after(&owner, &id, position) { + Ok((events, finished, _)) => { + pending = events; + over = finished; + } + Err(status) => { + let _ = tx.send(Err(status)).await; + return; + } + } + } + }); + Ok(Response::new(Box::pin(ReceiverStream::new(rx)))) + } + + /// Starts `work` as a job of `caller` for the operation that needs `permission`, or answers + /// with the job the same idempotency key started before (`true`: a replay, nothing started). + /// + /// The work's fence is the same check every mutation makes at its commit: the permission is + /// still held and the grants have not changed since the call began. + #[allow(clippy::too_many_arguments)] + pub(super) fn start_job( + &self, + caller: &ResourceCaller, + context: ServiceContext, + permission: &'static str, + key: &str, + hash: [u8; 32], + awaiting: Option<&'static str>, + work: Work, + ) -> Result<(JobReply, bool), Status> { + let owner = JobOwner::of(caller)?; + let providers = self.providers.clone(); + let grant_revision = caller.grant_revision; + let fence: Fence = Arc::new(move || { + let current = providers.authorize_resource(Some(&context), permission)?; + if current.grant_revision == grant_revision { + Ok(()) + } else { + Err(Status::failed_precondition( + "plugin permissions changed; the job's effect was not committed", + )) + } + }); + self.jobs.submit( + &owner, + Submission { + permission, + key: key.to_owned(), + hash, + fence, + profile: self.providers.profiles().subscribe(), + awaiting, + }, + work, + ) + } +} diff --git a/crates/app/src/plugin_host/resources/libraries.rs b/crates/app/src/plugin_host/resources/libraries.rs new file mode 100644 index 000000000..aaf036e41 --- /dev/null +++ b/crates/app/src/plugin_host/resources/libraries.rs @@ -0,0 +1,894 @@ +//! Logical libraries and approved scan roots. Metadata and physical paths stay in the +//! authenticated account namespace, separate from global DRM-free watch configuration. +use super::mutations::{mutation_key, request_hash}; +use super::*; +use crate::plugin_host::files::{APPROVAL_TIMEOUT, AffectedGame, RootRequest, RootScope}; +use crate::plugin_host::library::PluginScanRoot; +use gamenode_platform::plugin_files::{ApprovedRoot, Confined, Identity, approve_root}; +use gamenode_platform::plugin_locations::{Os, SystemFolders}; +use gamenode_platform::plugin_storage::{PluginLibraryRoot as Root, PluginLibraryRow as Row}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; + +const MAX_LIBRARIES: usize = gamenode_platform::plugin_storage::MAX_PLUGIN_LIBRARIES; +const MAX_ROOTS: usize = gamenode_platform::plugin_storage::MAX_PLUGIN_LIBRARY_ROOTS; + +pub(super) struct Libraries { + instance: u64, + cancelled: Arc, + monitors: Mutex>, + epochs: Mutex>>, +} + +impl Default for Libraries { + fn default() -> Self { + static NEXT_INSTANCE: AtomicU64 = AtomicU64::new(1); + Self { + instance: NEXT_INSTANCE.fetch_add(1, Ordering::Relaxed), + cancelled: Arc::default(), + monitors: Mutex::default(), + epochs: Mutex::default(), + } + } +} + +#[derive(Debug)] +pub(super) enum Edit { + Create(String, String), + Update(String, String, String, Vec), + Remove(String), + Add(String, String, String, Vec), + Root( + String, + String, + String, + String, + Vec, + Vec, + bool, + ), + RemoveRoot(String, String), +} +impl Edit { + fn permission(&self) -> &'static str { + match self { + Self::Create(..) | Self::Add(..) => cap::LIBRARY_ROOTS_CREATE, + Self::Update(..) | Self::Root(..) => cap::LIBRARY_ROOTS_UPDATE, + _ => cap::LIBRARY_ROOTS_DELETE, + } + } + fn library(&self) -> Option<&str> { + match self { + Self::Create(..) => None, + Self::Update(id, ..) + | Self::Remove(id) + | Self::Add(id, ..) + | Self::Root(id, ..) + | Self::RemoveRoot(id, ..) => Some(id), + } + } +} +fn name(value: &str) -> Result { + crate::plugin_host::saves::check_name("name", value) +} +fn description(value: &str) -> Result<(), Status> { + if value.len() > 2048 || !crate::plugin_host::notifications::is_plain_line(value) { + return Err(Status::invalid_argument( + "description must be plain text, at most 2048 bytes", + )); + } + Ok(()) +} +fn id(prefix: &str) -> Result { + let mut bytes = [0u8; 16]; + getrandom::fill(&mut bytes).map_err(|_| Status::internal("no randomness"))?; + Ok(format!( + "{prefix}{}", + bytes.iter().map(|v| format!("{v:02x}")).collect::() + )) +} +fn physical(root: &Root) -> Result<(), Status> { + Confined::open( + &ApprovedRoot { + path: PathBuf::from(&root.path), + identity: Identity { + volume: root.volume, + node: root.node, + }, + }, + &Default::default(), + ) + .map_err(|_| Status::failed_precondition("approved root is unavailable or replaced"))?; + if gamenode_platform::volume::volume_info(Path::new(&root.path)).is_none_or(|v| { + v.volume_identity_token.is_empty() || v.volume_identity_token != root.volume_token + }) { + return Err(Status::failed_precondition( + "approved volume is unavailable or replaced", + )); + } + Ok(()) +} +fn record(row: &Row, plugin: &str, files: &FileAccess, session: &str) -> LibraryRecord { + LibraryRecord { + id: row.id.clone(), + name: row.name.clone(), + description: row.description.clone(), + creator_plugin_id: plugin.into(), + root_ids: row.roots.iter().map(|r| r.id.clone()).collect(), + revision: row.revision, + roots: row + .roots + .iter() + .map(|root| LibraryRootRecord { + id: root.id.clone(), + display_name: root.name.clone(), + watching: root.watching, + availability: if physical(root).is_ok() { + InspectionAvailability::Available + } else { + InspectionAvailability::Disconnected + } as i32, + approved_root_handle: files.seal_handle(session, &root.handle_id(), &[]), + discovery_state: if cfg!(windows) { + "available" + } else { + "unsupported_platform" + } + .into(), + }) + .collect(), + } +} +struct RootMonitoring { + task: tokio::task::JoinHandle<()>, + cancelled: Arc, +} +impl Drop for RootMonitoring { + fn drop(&mut self) { + self.cancelled.store(true, Ordering::Release); + self.task.abort(); + } +} + +impl ResourceApi { + pub(crate) fn monitor_library_roots(&self) -> impl Drop + Send + use<> { + let api = self.clone(); + let cancelled = self.libraries.cancelled.clone(); + let task = tokio::spawn(async move { + loop { + for context in api.providers.resource_session_contexts() { + let running = api + .libraries + .monitors + .lock() + .unwrap_or_else(|p| p.into_inner()) + .contains_key(&context.session_id); + if !running + && let Ok(caller) = api.providers.authorize_resource_session(Some(&context)) + && caller.namespace.is_some() + && let Err(error) = api.start_library_monitor(&caller, &context).await + { + tracing::debug!(code = ?error.code(), "library-root monitoring is unavailable"); + } + } + tokio::time::sleep(Duration::from_secs(1)).await; + } + }); + RootMonitoring { task, cancelled } + } + + fn libraries_epoch(&self, caller: &ResourceCaller) -> Result, Status> { + let owner = caller + .namespace + .as_ref() + .ok_or_else(|| Status::failed_precondition("third-party account namespace required"))? + .storage_owner(); + Ok(self + .libraries + .epochs + .lock() + .unwrap_or_else(|p| p.into_inner()) + .entry(*owner.key()) + .or_default() + .clone()) + } + async fn sync_library_scans( + &self, + caller: &ResourceCaller, + context: &ServiceContext, + ) -> Result<(), Status> { + let host = self + .library + .host() + .ok_or_else(|| Status::unavailable("Core library host unavailable"))?; + let epoch = self.libraries_epoch(caller)?; + let observed = epoch.load(Ordering::Acquire); + let rows = self.in_namespace(caller, |n| n.plugin_libraries()).await?; + let providers = self.providers.clone(); + let context = context.clone(); + let cancelled = self.libraries.cancelled.clone(); + let roots = rows + .into_iter() + .filter(|r| !r.removed) + .flat_map(|r| r.roots) + .filter(|r| r.watching) + .map(|root| { + let (epoch, providers, context, cancelled) = ( + epoch.clone(), + providers.clone(), + context.clone(), + cancelled.clone(), + ); + PluginScanRoot { + root, + valid: Arc::new(move || { + if cancelled.load(Ordering::Acquire) + || epoch.load(Ordering::Acquire) != observed + { + return Err(Status::cancelled("library roots changed")); + } + providers.authorize_resource_session(Some(&context))?; + Ok(()) + }), + } + }) + .collect(); + if epoch.load(Ordering::Acquire) != observed { + return Ok(()); + } + host.set_plugin_roots( + format!("logical:{}:{}", self.libraries.instance, caller.session_id), + roots, + ) + } + async fn start_library_monitor( + &self, + caller: &ResourceCaller, + context: &ServiceContext, + ) -> Result<(), Status> { + // Without a connected Core host, metadata remains independently readable. + if self + .library + .host() + .is_none_or(|host| !host.plugin_roots_supported()) + { + return Ok(()); + } + let session = caller.session_id.clone(); + let is_new = { + let mut monitors = self + .libraries + .monitors + .lock() + .unwrap_or_else(|p| p.into_inner()); + if !monitors.contains_key(&session) && monitors.len() >= 64 { + return Err(Status::resource_exhausted( + "Core root monitor limit reached", + )); + } + monitors + .insert(session.clone(), (caller.clone(), context.clone())) + .is_none() + }; + if let Err(error) = self.sync_library_scans(caller, context).await { + if is_new { + self.libraries + .monitors + .lock() + .unwrap_or_else(|p| p.into_inner()) + .remove(&session); + } + return Err(error); + } + if !is_new { + return Ok(()); + } + let (api, context) = (self.clone(), context.clone()); + tokio::spawn(async move { + loop { + tokio::time::sleep(Duration::from_secs(30)).await; + if api.libraries.cancelled.load(Ordering::Acquire) { + break; + } + let fresh = match api.providers.authorize_resource_session(Some(&context)) { + Ok(fresh) => fresh, + Err(_) => break, + }; + if api.sync_library_scans(&fresh, &context).await.is_err() { + break; + } + } + if let Some(host) = api.library.host() { + let _ = host.set_plugin_roots( + format!("logical:{}:{}", api.libraries.instance, session), + vec![], + ); + } + api.libraries + .monitors + .lock() + .unwrap_or_else(|p| p.into_inner()) + .remove(&session); + }); + Ok(()) + } + pub(super) async fn list_libraries( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + let page = request.page.unwrap_or_default(); + let caller = self + .providers + .authorize_resource(page.context.as_ref(), cap::LIBRARY_ROOTS_READ)?; + no_common_data(page.common_data_categories.as_ref())?; + if !request.kind.is_empty() && request.kind != "libraries" { + return Err(Status::invalid_argument("unsupported library kind")); + } + let plugin = caller + .namespace + .as_ref() + .ok_or_else(|| Status::failed_precondition("account namespace required"))? + .identity() + .plugin_id + .clone(); + if !request.owner_filter.is_empty() && request.owner_filter != plugin { + return Err(Status::permission_denied( + "foreign library scope is not granted", + )); + } + let (files, session) = (self.files.clone(), caller.session_id.clone()); + let cursor = page.cursor; + let grant = caller.grant_revision; + let max = if page.page_size == 0 { + 50 + } else { + page.page_size.min(MAX_PAGE_SIZE as u32) + } as usize; + let result = self + .in_namespace(&caller, move |n| { + let revision = n.revision()?; + let binding = format!("logical-libraries:{revision}:{grant}"); + let after = if cursor.is_empty() { + String::new() + } else { + files + .open_cursor(&session, &binding, &cursor) + .ok_or_else(|| { + Status::failed_precondition("library cursor changed; list again") + })? + }; + let mut rows = n + .plugin_libraries()? + .into_iter() + .filter(|r| !r.removed && r.id > after) + .collect::>(); + let more = rows.len() > max; + rows.truncate(max); + let next_cursor = if more { + files.seal_cursor(&session, &binding, &rows.last().unwrap().id) + } else { + String::new() + }; + Ok(LibrariesListReply { + libraries: rows + .iter() + .map(|r| record(r, &plugin, &files, &session)) + .collect(), + next_cursor, + revision, + }) + }) + .await?; + self.providers + .authorize_resource(page.context.as_ref(), cap::LIBRARY_ROOTS_READ)?; + if let Some(context) = page.context { + self.start_library_monitor(&caller, &context).await?; + } + Ok(Response::new(result)) + } + pub(super) async fn get_library( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + let caller = self + .providers + .authorize_resource(request.context.as_ref(), cap::LIBRARY_ROOTS_READ)?; + no_common_data(request.shared_records.as_ref())?; + let plugin = caller + .namespace + .as_ref() + .ok_or_else(|| Status::failed_precondition("account namespace required"))? + .identity() + .plugin_id + .clone(); + let (files, session) = (self.files.clone(), caller.session_id.clone()); + let result = self + .in_namespace(&caller, move |n| { + let row = n + .plugin_libraries()? + .into_iter() + .find(|r| r.id == request.resource_id && !r.removed) + .ok_or_else(|| Status::not_found("library not found"))?; + if request.expected_revision != 0 && request.expected_revision != row.revision { + return Err(Status::aborted("library revision changed")); + } + Ok(LibraryRecordReply { + revision: row.revision, + library: Some(record(&row, &plugin, &files, &session)), + }) + }) + .await?; + self.providers + .authorize_resource(request.context.as_ref(), cap::LIBRARY_ROOTS_READ)?; + Ok(Response::new(result)) + } + async fn choose_library_root( + &self, + caller: &ResourceCaller, + library: &str, + handle: &str, + display: &str, + suggestions: &[DeclaredLocation], + ) -> Result { + if self + .library + .host() + .is_none_or(|host| !host.plugin_roots_supported()) + { + return Err(Status::failed_precondition( + "Core root discovery is not connected", + )); + } + if !handle.is_empty() { + let (approved_id, path) = self + .files + .open_handle(&caller.session_id, handle) + .filter(|(_, p)| p.is_empty()) + .ok_or_else(|| Status::not_found("library-root handle not found"))?; + let _ = path; + let root = self + .in_namespace(caller, move |n| { + n.plugin_libraries().map(|rows| { + rows.into_iter() + .filter(|r| !r.removed) + .flat_map(|r| r.roots) + .find(|r| r.handle_id() == approved_id) + }) + }) + .await? + .ok_or_else(|| Status::not_found("library-root handle not found"))?; + let mut root = tokio::task::spawn_blocking(move || { + physical(&root)?; + Ok::<_, Status>(root) + }) + .await + .map_err(|_| Status::internal("root validation failed"))??; + root.id = id("lroot-")?; + root.name = name(display)?; + root.watching = true; + return Ok(root); + } + if suggestions.len() > 8 { + return Err(Status::invalid_argument("at most eight root suggestions")); + } + let mut parsed = Vec::new(); + for suggestion in suggestions { + if !matches!(suggestion.kind.as_str(), "" | "library") { + return Err(Status::invalid_argument( + "root suggestion kind must be library", + )); + } + description(&suggestion.description)?; + parsed.push(( + gamenode_platform::plugin_locations::parse(&suggestion.location) + .map_err(|_| Status::invalid_argument("invalid declared root"))?, + suggestion.description.clone(), + )); + } + let files = self.files.clone(); + let reserved = files.reserved.clone(); + let declared = tokio::task::spawn_blocking(move || { + let mut folders = Vec::new(); + for (location, description) in parsed { + if let Some(path) = location.expand(Os::current(), &SystemFolders) + && !reserved.is_reserved(&path) + && !folders + .iter() + .any(|f: &crate::plugin_host::files::DeclaredFolder| f.path == path) + { + let exists = std::fs::metadata(&path).is_ok_and(|m| m.is_dir()); + folders.push(crate::plugin_host::files::DeclaredFolder { + path, + description, + exists, + }); + } + } + folders + }) + .await + .map_err(|_| Status::internal("root suggestions failed"))?; + let identity = caller + .namespace + .as_ref() + .ok_or_else(|| Status::failed_precondition("account namespace required"))? + .identity() + .clone(); + let _waiting = files + .begin_approval(*caller.namespace.as_ref().unwrap().storage_owner().key()) + .ok_or_else(|| Status::aborted("a folder approval is already pending"))?; + let approver = files + .approver() + .ok_or_else(|| Status::failed_precondition("folder approval dialog unavailable"))?; + let display = name(display)?; + let preselected = declared.iter().find(|f| f.exists).map(|f| f.path.clone()); + let originals = declared.clone(); + let chosen = tokio::time::timeout( + APPROVAL_TIMEOUT, + approver.choose_root(RootRequest { + plugin_id: identity.plugin_id.clone(), + publisher_fingerprint: identity.publisher_fingerprint.clone(), + installation_name: library.into(), + kind: "library".into(), + operations: vec!["read", "plugin_discovery", "core_executable_discovery"], + previously_approved: None, + suggested: None, + preselected, + declared, + }), + ) + .await + .map_err(|_| Status::deadline_exceeded("folder approval timed out"))?? + .ok_or_else(|| Status::permission_denied("folder selection declined"))?; + let reserved = files.reserved.clone(); + let feed = self.library.clone(); + let (approved, declared, token, affected) = tokio::task::spawn_blocking(move || { + let approved = approve_root(&chosen, &reserved) + .map_err(|_| Status::failed_precondition("folder cannot be approved"))?; + let declared = originals + .iter() + .any(|f| std::fs::canonicalize(&f.path).ok().as_ref() == Some(&approved.path)); + let token = gamenode_platform::volume::volume_info(&approved.path) + .map(|v| v.volume_identity_token) + .filter(|v| !v.is_empty()) + .ok_or_else(|| Status::failed_precondition("volume identity unknown"))?; + let affected = files + .overlapping(&feed, &approved.path) + .into_iter() + .map(|entry| AffectedGame { + name: entry.name, + game_id: entry.game_id, + }) + .collect(); + Ok::<_, Status>((approved, declared, token, affected)) + }) + .await + .map_err(|_| Status::internal("folder validation failed"))??; + if !tokio::time::timeout( + APPROVAL_TIMEOUT, + approver.confirm(RootScope { + plugin_id: identity.plugin_id, + publisher_fingerprint: identity.publisher_fingerprint, + installation_name: library.into(), + kind: "library".into(), + operations: vec!["read", "plugin_discovery", "core_executable_discovery"], + root: approved.path.clone(), + declared_by_plugin: declared, + affected, + }), + ) + .await + .map_err(|_| Status::deadline_exceeded("folder approval timed out"))?? + { + return Err(Status::permission_denied("root approval declined")); + } + Ok(Root { + id: id("lroot-")?, + name: display, + path: approved.path.to_string_lossy().into_owned(), + volume: approved.identity.volume, + node: approved.identity.node, + volume_token: token, + declared, + watching: true, + }) + } + pub(super) async fn edit_library( + &self, + mutation: Option, + edit: Edit, + ) -> Result { + let mutation = mutation.ok_or_else(|| Status::invalid_argument("mutation required"))?; + let context = mutation + .context + .clone() + .ok_or_else(|| Status::invalid_argument("context required"))?; + let caller = self + .providers + .authorize_resource(Some(&context), edit.permission())?; + let epoch = self.libraries_epoch(&caller)?; + let key = mutation_key(&mutation)?.to_owned(); + let hash = request_hash(&[ + "logical-library", + &format!("{edit:?}"), + &mutation.expected_revision.to_string(), + ]); + { + let _lock = self.mutations.lock.lock().await; + if let Some(replay) = self.mutations.replay(&caller, &key, hash)? { + return Ok(replay); + } + } + let library_id = edit.library().map(str::to_owned); + let mut row = self + .in_namespace(&caller, move |n| { + let rows = n.plugin_libraries()?; + match library_id { + Some(id) => rows + .into_iter() + .find(|r| r.id == id && !r.removed) + .ok_or_else(|| Status::not_found("library not found")), + None => { + if rows.len() >= MAX_LIBRARIES { + return Err(Status::resource_exhausted("library record limit reached")); + } + Ok(Row { + id: id("library-")?, + name: String::new(), + description: String::new(), + roots: vec![], + removed: false, + revision: 0, + }) + } + } + }) + .await?; + if row.revision != mutation.expected_revision { + return Ok(super::mutations::reply( + &row.id, + row.revision, + MutationOutcome::RevisionConflict, + )); + } + let permission = edit.permission(); + let mut validate_roots = Vec::new(); + let mut result_id = row.id.clone(); + match edit { + Edit::Create(label, text) => { + row.name = name(&label)?; + description(&text)?; + row.description = text; + } + Edit::Update(_, label, text, mask) => { + if mask.is_empty() + || mask + .iter() + .any(|f| !matches!(f.as_str(), "name" | "description")) + { + return Err(Status::invalid_argument( + "field_mask must select name or description", + )); + } + if mask.iter().any(|f| f == "name") { + row.name = name(&label)?; + } + if mask.iter().any(|f| f == "description") { + description(&text)?; + row.description = text; + } + } + Edit::Remove(_) => { + row.removed = true; + row.roots.clear(); + } + Edit::Add(_, handle, label, suggestions) => { + let total = self + .in_namespace(&caller, |n| { + n.plugin_libraries() + .map(|rows| rows.iter().map(|r| r.roots.len()).sum::()) + }) + .await?; + if total >= MAX_ROOTS { + return Err(Status::resource_exhausted("root limit reached")); + } + let root = self + .choose_library_root(&caller, &row.name, &handle, &label, &suggestions) + .await?; + result_id = root.id.clone(); + validate_roots.push(root.id.clone()); + row.roots.push(root); + } + Edit::Root(_, root_id, handle, label, suggestions, mask, watching) => { + if mask.is_empty() + || mask + .iter() + .any(|f| !matches!(f.as_str(), "display_name" | "watching" | "folder")) + { + return Err(Status::invalid_argument( + "field_mask must select display_name, watching or folder", + )); + } + let root = row + .roots + .iter_mut() + .find(|r| r.id == root_id) + .ok_or_else(|| Status::not_found("root not found"))?; + if mask.iter().any(|f| f == "folder") { + let mut replacement = self + .choose_library_root(&caller, &row.name, &handle, &root.name, &suggestions) + .await?; + replacement.id = root.id.clone(); + replacement.watching = root.watching; + validate_roots.push(root.id.clone()); + *root = replacement; + } + if mask.iter().any(|f| f == "display_name") { + root.name = name(&label)?; + } + if mask.iter().any(|f| f == "watching") { + root.watching = watching; + } + result_id = root.id.clone(); + } + Edit::RemoveRoot(_, root_id) => { + let before = row.roots.len(); + row.roots.retain(|r| r.id != root_id); + if before == row.roots.len() { + return Err(Status::not_found("root not found")); + } + result_id = root_id; + } + } + let _lock = self.mutations.lock.lock().await; + if let Some(replay) = self.mutations.replay(&caller, &key, hash)? { + return Ok(replay); + } + let guard = self.guard(context.clone(), permission, caller.grant_revision); + let expected = mutation.expected_revision; + let invalidate = epoch.clone(); + let revision = self + .in_namespace(&caller, move |n| { + // Revalidate newly approved/reused roots after user wait, including volume identity. + for root in &row.roots { + if validate_roots.contains(&root.id) { + physical(root)?; + } + } + guard()?; + invalidate.fetch_add(1, Ordering::AcqRel); + n.put_plugin_library(row, expected, &guard) + }) + .await?; + let owner = caller.namespace.as_ref().unwrap().storage_owner(); + let contexts: Vec<_> = self + .libraries + .monitors + .lock() + .unwrap_or_else(|p| p.into_inner()) + .values() + .filter(|(c, _)| { + c.namespace + .as_ref() + .is_some_and(|n| n.storage_owner().key() == owner.key()) + }) + .map(|(_, context)| context.clone()) + .collect(); + for context in contexts { + if let Ok(fresh) = self.providers.authorize_resource_session(Some(&context)) { + self.sync_library_scans(&fresh, &context).await?; + } + } + let reply = super::mutations::reply(&result_id, revision, MutationOutcome::Applied); + self.mutations.remember(&caller, &key, hash, &reply); + drop(_lock); + // Metadata-only operations remain usable when Core discovery is not connected. + // Root work is dispatched only through the authenticated host contribution. + self.start_library_monitor(&caller, &context).await?; + Ok(reply) + } + pub(super) async fn watch_libraries( + &self, + request: Request, + ) -> Result>, Status> { + let request = request.into_inner(); + let context = request.context.clone(); + let caller = self + .providers + .authorize_resource(context.as_ref(), cap::LIBRARY_ROOTS_READ)?; + no_common_data(request.shared_records.as_ref())?; + let current = self.in_namespace(&caller, |n| n.revision()).await?; + if request.after_revision != 0 && request.after_revision != current { + return Err(Status::failed_precondition( + "library history is not retained; list and watch from its revision", + )); + } + let plugin = caller + .namespace + .as_ref() + .ok_or_else(|| Status::failed_precondition("account namespace required"))? + .identity() + .plugin_id + .clone(); + let slot = self.watch_slot(&caller.session_id)?; + let (tx, rx) = mpsc::channel(WATCH_QUEUE); + let api = self.clone(); + tokio::spawn(async move { + let _slot = slot; + let mut last = request.after_revision; + let mut previous: HashMap> = HashMap::new(); + let mut initial = true; + loop { + let result = async { + api.providers + .authorize_resource(context.as_ref(), cap::LIBRARY_ROOTS_READ)?; + let (files, session, plugin, filter) = ( + api.files.clone(), + caller.session_id.clone(), + plugin.clone(), + request.resource_id.clone(), + ); + let old = previous.clone(); + let (revision, events, states) = api + .in_namespace(&caller, move |n| { + let revision = n.revision()?; + let mut rows = n.plugin_libraries()?; + rows.sort_by_key(|r| r.revision); + let mut events = Vec::new(); + let mut states = HashMap::new(); + for r in rows + .into_iter() + .filter(|r| filter.is_empty() || r.id == filter) + { + let projected = record(&r, &plugin, &files, &session); + let availability = projected + .roots + .iter() + .map(|r| r.availability) + .collect::>(); + let availability_changed = !initial + && old.get(&r.id).is_some_and(|prior| prior != &availability); + if r.revision > last || availability_changed { + events.push(LibraryRecordEvent { + revision, + event_type: if r.removed { + "removed" + } else if r.revision > last { + "updated" + } else { + "availability_changed" + } + .into(), + library: Some(projected), + }); + } + states.insert(r.id, availability); + } + Ok((revision, events, states)) + }) + .await?; + api.providers + .authorize_resource(context.as_ref(), cap::LIBRARY_ROOTS_READ)?; + for event in events { + tx.try_send(Ok(event)).map_err(|_| { + Status::resource_exhausted("library watch fell behind; list again") + })?; + } + last = revision; + previous = states; + initial = false; + Ok::<_, Status>(()) + } + .await; + if let Err(error) = result { + let _ = tx.send(Err(error)).await; + return; + } + tokio::select! {_=tx.closed()=>return,_=tokio::time::sleep(Duration::from_secs(1))=>{}} + } + }); + Ok(Response::new(Box::pin(ReceiverStream::new(rx)))) + } +} diff --git a/crates/app/src/plugin_host/resources/locations.rs b/crates/app/src/plugin_host/resources/locations.rs new file mode 100644 index 000000000..c9d9540e5 --- /dev/null +++ b/crates/app/src/plugin_host/resources/locations.rs @@ -0,0 +1,1199 @@ +//! The `Locations` service, the common inspection of approved places (task 13.3, design +//! section 12): `GetSize`, `GetAccess` and `GetLastModified`. +//! +//! A place is named by a handle a plugin already holds for a folder the user approved (task +//! 6.2), or by the id of one of the plugin's save profiles (task 13.1), which stands for the +//! union of its folders narrowed by their naming rules. Inspection reads *metadata only*: no file +//! is opened for its content, and nothing is changed to find out (no permission, no timestamp, no +//! file). It needs `game.storage.inspect` for an installation folder and `game.saves.inspect` for +//! a save or prefix folder or a profile, and a standing approval; it does not need, and does not +//! give, the right to read a file. +//! +//! The walk is bounded (entries, time) and stops when the call is abandoned. A cut is reported as +//! `complete = false`; a folder that is gone or unreadable is reported through `availability`, +//! never as zero bytes. Sizes are logical bytes of the files, not allocated disk space. +//! Volume inspection and availability watches are implemented in `volumes`. + +use std::collections::HashSet; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::{Duration, Instant}; + +use gamenode_platform::plugin_files::{ACCESS_METHOD, AccessInfo, Budget, Entry, FileError, Tri}; +use gamenode_platform::plugin_storage::SaveProfileRow; +use gamenode_plugin_protocol::{capability as cap, proto::*}; +use tonic::{Request, Response, Status}; + +use super::files::{ + Opened, approval_of_handle, file_status, open_approval_inspect, open_handle_inspect, +}; +use super::mutations::request_hash; +use super::{BoxStream, ResourceApi, Served}; +use crate::plugin_host::files::FileAccess; +use crate::plugin_host::fingerprints::{ + self as fingerprints, ALGORITHM, CODE_READY, DEFAULT_ENTRIES as DEFAULT_FINGERPRINT_ENTRIES, + MAX_BYTES, MAX_ENTRIES as MAX_FINGERPRINT_ENTRIES, MAX_TIME, Record, Snapshot, +}; +use crate::plugin_host::jobs::{JobOwner, Outcome, work}; +use crate::plugin_host::library::LibraryFeed; +use crate::plugin_host::saves::{self as saves, Directory}; +use crate::plugin_host::storage::Namespace; + +/// Entries a size walk visits when the request does not say, and the most it may be asked to. +mod volumes; + +const DEFAULT_ENTRIES: usize = 10_000; +const MAX_ENTRIES: usize = 100_000; +/// Entries a timestamp or access answer lists when the request does not say, and the most. +const DEFAULT_LISTED: usize = 100; +const MAX_LISTED: usize = 1_000; +/// Entry handles one access request may name. +const MAX_ENTRY_HANDLES: usize = 100; +/// The longest a walk runs. +const WALK_TIME: Duration = Duration::from_secs(5); +const MAX_HANDLE_BYTES: usize = 16 * 1024; + +const INSPECT_PERMISSIONS: &str = "game.storage.inspect,game.saves.inspect"; +const SCOPE: &str = "a folder the user approved for this plugin, or one of its save profiles; \ + game.storage.inspect for an installation folder, game.saves.inspect for saves"; + +/// The `Locations` methods this build serves, for `DescribeApi`. +pub const SERVED: &[Served] = &[ + Served::new("Inspect", INSPECT_PERMISSIONS, false, SCOPE), + Served::new("WatchAvailability", INSPECT_PERMISSIONS, false, SCOPE), + Served::new("GetSize", INSPECT_PERMISSIONS, false, SCOPE), + Served::new("GetAccess", INSPECT_PERMISSIONS, false, SCOPE), + Served::new("GetLastModified", INSPECT_PERMISSIONS, false, SCOPE), + Served::new("GetFingerprint", INSPECT_PERMISSIONS, false, SCOPE), + Served::new("Compare", INSPECT_PERMISSIONS, true, SNAPSHOT_SCOPE), +]; + +const SNAPSHOT_SCOPE: &str = "this plugin's own fingerprints, of places it may inspect"; + +/// Stops a walk that is still running on a worker when the call that wanted it is dropped. +struct StopOnDrop(Arc); + +impl Drop for StopOnDrop { + fn drop(&mut self) { + self.0.store(true, Ordering::Relaxed); + } +} + +/// What a place is, once looked up. +#[allow(clippy::large_enum_variant)] // A short-lived temporary, not a stored collection. +enum Place { + /// A folder or file below an approval. + Handle { + kind: String, + }, + Profile { + row: SaveProfileRow, + }, +} + +impl Place { + /// The permission the place needs. + fn permission(&self) -> &'static str { + match self { + Self::Handle { kind } if matches!(kind.as_str(), "installation" | "library") => { + cap::GAME_STORAGE_INSPECT + } + _ => cap::GAME_SAVES_INSPECT, + } + } +} + +fn handle_text(handle: &str) -> Result<(), Status> { + if handle.is_empty() || handle.len() > MAX_HANDLE_BYTES { + return Err(Status::invalid_argument( + "approved_resource_handle is required", + )); + } + Ok(()) +} + +/// How a place that could not be inspected is reported. +fn availability_of(error: FileError) -> Option { + match error { + FileError::NotFound | FileError::RootChanged => Some(InspectionAvailability::Missing), + FileError::Access => Some(InspectionAvailability::Inaccessible), + FileError::Io => Some(InspectionAvailability::Unknown), + // A path outside the approval is a refusal, not an availability. + _ => None, + } +} + +fn or_unavailable( + result: Result, +) -> Result, Status> { + match result { + Ok(value) => Ok(Ok(value)), + Err(error) => availability_of(error) + .map(Err) + .ok_or_else(|| file_status(error)), + } +} + +/// What an access question is about, once looked up. +enum Target { + Open(Box), + Unavailable(InspectionAvailability), +} + +/// One entry seen on the way. +struct Seen { + approval_id: String, + path: Vec, + entry: Entry, +} + +/// What a walk of a place found. +#[derive(Default)] +struct Measured { + bytes: u64, + files: u64, + directories: u64, + complete: bool, + /// Entries below the place, in visit order, for the timestamp answer (bounded). + seen: Vec, + /// The place's own folder, when it is one. + own: Option, + /// The newest modification of a selected entry below the place. + newest: Option<(i64, u32)>, + unavailable: Option, +} + +fn newer(a: Option<(i64, u32)>, b: (i64, u32)) -> Option<(i64, u32)> { + Some(a.map_or(b, |a| a.max(b))) +} + +/// Walks `start` below `approval_id`, counting what the folder's rules select once each. +#[allow(clippy::too_many_arguments)] +fn walk_folder( + opened: &Opened, + approval_id: &str, + start: &[String], + patterns: &[String], + counted: &mut HashSet<(String, String)>, + budget: &Budget<'_>, + keep: usize, + measured: &mut Measured, +) -> Result<(), FileError> { + let root = opened.confined.stat(start)?; + if !root.directory { + // A single file: it is the whole place. + if counted.insert((approval_id.to_owned(), start.join("/"))) { + measured.files += 1; + measured.bytes += root.size; + measured.newest = newer(measured.newest, (root.modified, root.modified_nanos)); + } + measured.seen.push(Seen { + approval_id: approval_id.to_owned(), + path: start.to_vec(), + entry: root, + }); + measured.complete = true; + return Ok(()); + } + if measured.own.is_none() { + measured.own = Some(Seen { + approval_id: approval_id.to_owned(), + path: start.to_vec(), + entry: root, + }); + } + let walk = opened + .confined + .walk_tree(start, budget, &mut |path, entry| { + let relative = &path[start.len()..]; + if entry.directory { + if counted.insert((approval_id.to_owned(), path.join("/"))) { + measured.directories += 1; + } + return; + } + if !saves::selected(patterns, relative) { + return; + } + if counted.insert((approval_id.to_owned(), path.join("/"))) { + measured.files += 1; + measured.bytes += entry.size; + measured.newest = newer(measured.newest, (entry.modified, entry.modified_nanos)); + if measured.seen.len() < keep { + measured.seen.push(Seen { + approval_id: approval_id.to_owned(), + path: path.to_vec(), + entry: entry.clone(), + }); + } + } + })?; + measured.complete &= walk.complete; + Ok(()) +} + +/// Looks the place up, on the namespace worker. A handle that is not this session's, not an +/// approval of this plugin or no longer standing is `NOT_FOUND`. +fn find_place( + files: &FileAccess, + feed: &LibraryFeed, + namespace: &mut Namespace<'_>, + session: &str, + handle: &str, +) -> Result { + if handle.starts_with("profile-") { + let row = namespace + .save_profile(handle)? + .ok_or_else(|| Status::not_found("save profile not found"))?; + return Ok(Place::Profile { row }); + } + let approval = approval_of_handle(files, feed, namespace, session, handle)?; + Ok(Place::Handle { + kind: approval.kind, + }) +} + +impl ResourceApi { + /// Finds the place and authorizes it: the permission is the one the place's kind needs, so + /// the plugin is asked for it only once its handle is known to be real. + async fn inspect_place( + &self, + context: Option<&ServiceContext>, + handle: &str, + ) -> Result< + ( + crate::plugin_host::provider::ResourceCaller, + Place, + &'static str, + ), + Status, + > { + let caller = self.providers.authorize_resource_session(context)?; + handle_text(handle)?; + let (files, feed, session) = ( + self.files.clone(), + self.library.clone(), + caller.session_id.clone(), + ); + let wanted = handle.to_owned(); + let place = self + .in_namespace(&caller, move |namespace| { + find_place(&files, &feed, namespace, &session, &wanted) + }) + .await?; + let permission = place.permission(); + let caller = self.providers.authorize_resource(context, permission)?; + Ok((caller, place, permission)) + } + + /// Walks the place on a blocking worker under the plugin's namespace lock. The walk stops when + /// this call is dropped. + async fn measure( + &self, + caller: &crate::plugin_host::provider::ResourceCaller, + place: Place, + handle: String, + max_entries: usize, + keep: usize, + ) -> Result { + let cancel = Arc::new(AtomicBool::new(false)); + let _stop = StopOnDrop(cancel.clone()); + let (files, feed, session) = ( + self.files.clone(), + self.library.clone(), + caller.session_id.clone(), + ); + self.in_namespace(caller, move |namespace| { + let budget = Budget { + max_entries, + deadline: Instant::now() + WALK_TIME, + cancel: &cancel, + }; + let mut measured = Measured { + complete: true, + ..Measured::default() + }; + let mut counted = HashSet::new(); + match place { + Place::Handle { .. } => { + let opened = + match open_handle_inspect(&files, &feed, namespace, &session, &handle)? { + Ok(opened) => opened, + // The folder cannot be opened now: say what it is like instead. + Err(error) => { + measured.complete = false; + measured.unavailable = + Some(availability_of(error).ok_or_else(|| file_status(error))?); + return Ok(measured); + } + }; + let id = opened.approval.id.clone(); + let start = opened.path.clone(); + if let Err(error) = walk_folder( + &opened, + &id, + &start, + &[], + &mut counted, + &budget, + keep, + &mut measured, + ) { + measured = Measured::default(); + measured.unavailable = + Some(availability_of(error).ok_or_else(|| file_status(error))?); + } + } + Place::Profile { row } => { + for directory in saves::directories_from_json(&row.directories) { + let Directory { + approval_id, + path, + naming_patterns, + .. + } = directory; + // A folder whose approval is gone (or moved to another entry) is not + // reachable: the total is then partial, not zero. + let opened = match open_approval_inspect( + &files, + &feed, + namespace, + &approval_id, + path.clone(), + ) { + Ok(Ok(opened)) + if opened.approval.installation_id == row.installation_id => + { + opened + } + _ => { + measured.complete = false; + continue; + } + }; + if let Err(error) = walk_folder( + &opened, + &approval_id, + &path, + &naming_patterns, + &mut counted, + &budget, + keep, + &mut measured, + ) { + match availability_of(error) { + Some(_) => measured.complete = false, + None => return Err(file_status(error)), + } + } + } + } + } + Ok(measured) + }) + .await + } + + pub(super) async fn get_location_size( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + let context = request.context.clone(); + let (caller, place, permission) = self + .inspect_place(context.as_ref(), &request.approved_resource_handle) + .await?; + let max = match request.max_entries as usize { + 0 => DEFAULT_ENTRIES, + max => max.min(MAX_ENTRIES), + }; + let measured = self + .measure(&caller, place, request.approved_resource_handle, max, 0) + .await?; + // The permission was checked before a walk that may have taken seconds. + self.providers + .authorize_resource(context.as_ref(), permission)?; + let reply = match measured.unavailable { + Some(availability) => LocationSizeReply { + logical_bytes: 0, + file_count: 0, + directory_count: 0, + complete: false, + availability: availability as i32, + }, + None => LocationSizeReply { + logical_bytes: measured.bytes, + file_count: measured.files, + directory_count: measured.directories, + complete: measured.complete, + availability: InspectionAvailability::Available as i32, + }, + }; + Ok(Response::new(reply)) + } + + pub(super) async fn get_location_last_modified( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + let context = request.context.clone(); + let (caller, place, permission) = self + .inspect_place(context.as_ref(), &request.approved_resource_handle) + .await?; + let listed = match request.max_entries as usize { + 0 => DEFAULT_LISTED, + max => max.min(MAX_LISTED), + }; + let measured = self + .measure( + &caller, + place, + request.approved_resource_handle.clone(), + DEFAULT_ENTRIES, + listed, + ) + .await?; + self.providers + .authorize_resource(context.as_ref(), permission)?; + if let Some(availability) = measured.unavailable { + return Ok(Response::new(LocationLastModifiedReply { + entries: Vec::new(), + aggregate_latest_at: None, + availability: availability as i32, + })); + } + let files = self.files.clone(); + let session = caller.session_id.clone(); + let stamp = |seen: &Seen, handle: Option<&str>| { + // An entry the system gave no time for is left out, never reported as the epoch. + if seen.entry.modified == 0 && seen.entry.modified_nanos == 0 { + return None; + } + let entry_handle = handle.map(str::to_owned).unwrap_or_else(|| { + if FileAccess::fits_handle(&seen.path) { + files.seal_handle(&session, &seen.approval_id, &seen.path) + } else { + String::new() + } + }); + Some(LocationTimestamp { + entry_handle, + modified_at: seen.entry.modified, + precision: if seen.entry.modified_nanos != 0 { + "subsecond" + } else { + "whole_second" + } + .to_owned(), + }) + }; + let mut entries = Vec::new(); + // The folder's own time comes first and apart from the entries below it. + if let Some(own) = &measured.own + && !request.approved_resource_handle.starts_with("profile-") + { + entries.extend(stamp(own, Some(&request.approved_resource_handle))); + } + entries.extend(measured.seen.iter().filter_map(|seen| stamp(seen, None))); + Ok(Response::new(LocationLastModifiedReply { + entries, + aggregate_latest_at: measured.newest.map(|(seconds, _)| seconds), + availability: InspectionAvailability::Available as i32, + })) + } + + pub(super) async fn get_location_access( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + let context = request.context.clone(); + if request.entry_handles.len() > MAX_ENTRY_HANDLES { + return Err(Status::invalid_argument(format!( + "at most {MAX_ENTRY_HANDLES} entry handles per request" + ))); + } + for handle in &request.entry_handles { + handle_text(handle)?; + } + let (caller, place, permission) = self + .inspect_place(context.as_ref(), &request.approved_resource_handle) + .await?; + let (files, feed, session) = ( + self.files.clone(), + self.library.clone(), + caller.session_id.clone(), + ); + let handle = request.approved_resource_handle.clone(); + let entry_handles = request.entry_handles.clone(); + let answers = self + .in_namespace(&caller, move |namespace| { + // What to look at: the entries named, or the place itself (a profile's folders). + let mut targets: Vec<(String, Target)> = Vec::new(); + match &place { + Place::Handle { .. } => { + let approval = + approval_of_handle(&files, &feed, namespace, &session, &handle)?; + let names: Vec<&String> = if entry_handles.is_empty() { + vec![&handle] + } else { + entry_handles.iter().collect() + }; + for name in names { + // Only entries of the same approval belong to this place. + let theirs = + approval_of_handle(&files, &feed, namespace, &session, name)?; + if theirs.id != approval.id { + return Err(Status::not_found("file handle not found")); + } + let target = match open_handle_inspect( + &files, &feed, namespace, &session, name, + )? { + Ok(opened) => Target::Open(Box::new(opened)), + Err(error) => Target::Unavailable( + availability_of(error).ok_or_else(|| file_status(error))?, + ), + }; + targets.push((name.clone(), target)); + } + } + Place::Profile { row } => { + if !entry_handles.is_empty() { + return Err(Status::invalid_argument( + "a save profile is inspected as a whole; entry_handles name \ + entries of a folder", + )); + } + for directory in saves::directories_from_json(&row.directories) { + let sealed = files.seal_handle( + &session, + &directory.approval_id, + &directory.path, + ); + // A folder whose approval is gone (or is another entry's) is reported + // as missing, not hidden. + let target = match open_approval_inspect( + &files, + &feed, + namespace, + &directory.approval_id, + directory.path.clone(), + ) { + Ok(Ok(opened)) + if opened.approval.installation_id == row.installation_id => + { + Target::Open(Box::new(opened)) + } + Ok(Err(error)) => Target::Unavailable( + availability_of(error) + .unwrap_or(InspectionAvailability::Missing), + ), + _ => Target::Unavailable(InspectionAvailability::Missing), + }; + // A lost folder has no handle to give. + let sealed = if matches!(target, Target::Open(_)) { + sealed + } else { + String::new() + }; + targets.push((sealed, target)); + } + } + } + let mut entries = Vec::new(); + for (entry_handle, target) in targets { + let unavailable = + |entry_handle: String, availability: InspectionAvailability| { + LocationAccessEntry { + entry_handle, + read_only_state: "unknown".into(), + effective_access: unknown_access(), + availability: availability as i32, + } + }; + entries.push(match target { + Target::Unavailable(availability) => { + unavailable(entry_handle, availability) + } + Target::Open(opened) => { + match or_unavailable(opened.confined.access(&opened.path))? { + Ok(info) => access_entry(entry_handle, &info), + Err(availability) => unavailable(entry_handle, availability), + } + } + }); + } + Ok(entries) + }) + .await?; + self.providers + .authorize_resource(context.as_ref(), permission)?; + Ok(Response::new(LocationAccessReply { + entries: answers, + availability: InspectionAvailability::Available as i32, + })) + } +} + +/// One folder of a fingerprint, opened on the namespace worker and then walked away from it. +struct Folder { + /// The profile's folder number, which starts its labels (`d/`); `None` for a plain handle. + index: Option, + approval_id: String, + start: Vec, + patterns: Vec, + opened: Opened, +} + +/// What a fingerprint covers, ready to be read without the plugin's namespace lock. +struct Plan { + scope: String, + revision: u64, + folders: Vec, + /// A folder of a profile whose approval is gone. + partial: bool, + unavailable: Option, +} + +fn unix_now() -> i64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |elapsed| elapsed.as_secs() as i64) +} + +fn label_of(folder: &Folder, path: &[String]) -> String { + match folder.index { + Some(index) => format!("d{index}/{}", path.join("/")), + None => { + // Below the place's own folder; a single file is named by its own name. + let below = path.get(folder.start.len()..).unwrap_or(&[]); + if below.is_empty() { + path.last().cloned().unwrap_or_default() + } else { + below.join("/") + } + } + } +} + +/// Reads the plan's folders and hashes their files. Blocking. `None` when cancelled. +fn build_snapshot( + plan: &Plan, + id: String, + permission: &'static str, + max_entries: usize, + cancel: &AtomicBool, + after_hash: Option, +) -> Option { + let started_at = unix_now(); + let deadline = Instant::now() + MAX_TIME; + let mut complete = !plan.partial; + let mut unstable = false; + let mut bytes_read = 0_u64; + let mut records: Vec = Vec::new(); + let mut counted: HashSet<(String, String)> = HashSet::new(); + 'folders: for folder in &plan.folders { + let confined = &folder.opened.confined; + let budget = Budget { + max_entries: max_entries.saturating_sub(records.len()), + deadline, + cancel, + }; + // What is below the start (the start itself when it is a file), as the walk saw it. + let mut found: Vec<(Vec, Entry)> = Vec::new(); + match confined.stat(&folder.start) { + Ok(root) if !root.directory => found.push((folder.start.clone(), root)), + Ok(_) => match confined.walk_tree(&folder.start, &budget, &mut |path, entry| { + found.push((path.to_vec(), entry.clone())); + }) { + Ok(walk) => complete &= walk.complete, + Err(_) => { + complete = false; + continue; + } + }, + Err(_) => { + complete = false; + continue; + } + } + if cancel.load(Ordering::Relaxed) { + return None; + } + for (path, entry) in found { + let relative = path.get(folder.start.len()..).unwrap_or(&[]); + if !entry.directory + && !saves::selected(&folder.patterns, relative) + && !relative.is_empty() + { + continue; + } + if !counted.insert((folder.approval_id.clone(), path.join("/"))) { + continue; + } + let mut record = Record { + label: label_of(folder, &path), + approval_id: folder.approval_id.clone(), + path: path.clone(), + directory: entry.directory, + size: entry.size, + digest: None, + unreadable: false, + unstable: false, + }; + if !entry.directory { + match confined.hash_file(&path, cancel, deadline) { + Ok(Some(digest)) => { + if let Some(hook) = &after_hash { + hook(&path); + } + // The same file, as long as it still has the size and time it had. + let steady = confined.stat(&path).is_ok_and(|after| { + after.size == entry.size + && after.modified == entry.modified + && after.modified_nanos == entry.modified_nanos + }) && digest.bytes == entry.size; + record.digest = Some(digest.sha256); + record.size = digest.bytes; + if !steady { + record.unstable = true; + unstable = true; + } + bytes_read += digest.bytes; + } + Ok(None) => { + if cancel.load(Ordering::Relaxed) { + return None; + } + // The time ran out. + complete = false; + break 'folders; + } + Err(_) => { + record.unreadable = true; + complete = false; + } + } + } + records.push(record); + if bytes_read > MAX_BYTES { + complete = false; + break 'folders; + } + } + } + if cancel.load(Ordering::Relaxed) { + return None; + } + records.sort_by(|a, b| a.label.as_bytes().cmp(b.label.as_bytes())); + let whole = complete && !unstable; + Some(Snapshot { + id, + permission, + scope: plan.scope.clone(), + revision: plan.revision, + digest: whole.then(|| fingerprints::tree_digest(&records)), + entries: records, + complete: whole, + unstable, + started_at, + finished_at: unix_now(), + }) +} + +fn pending(job: &gamenode_plugin_protocol::proto::JobReply) -> LocationFingerprintReply { + LocationFingerprintReply { + job_id: job.job_id.clone(), + consistency: "pending".into(), + availability: InspectionAvailability::Available as i32, + algorithm: ALGORITHM.into(), + ..LocationFingerprintReply::default() + } +} + +impl ResourceApi { + /// What the job's reply stands for: the stored fingerprint if it finished, or how it stands. + fn fingerprint_reply( + &self, + owner: &JobOwner, + job: &JobReply, + ) -> Result { + match job.state() { + JobState::Queued | JobState::Running => Ok(pending(job)), + JobState::Succeeded if job.result_code == CODE_READY => { + let snapshot = self.snapshots.get(owner, &job.message).ok_or_else(|| { + Status::failed_precondition( + "that fingerprint is no longer kept; ask again with a new idempotency key", + ) + })?; + Ok(LocationFingerprintReply { + snapshot_id: snapshot.id.clone(), + algorithm: ALGORITHM.into(), + digest: snapshot.digest.map(|d| d.to_vec()).unwrap_or_default(), + revision: snapshot.revision, + complete: snapshot.complete, + consistency: if snapshot.unstable { + "unstable" + } else { + "best_effort" + } + .into(), + job_id: job.job_id.clone(), + availability: InspectionAvailability::Available as i32, + observed_start_at: snapshot.started_at, + observed_end_at: snapshot.finished_at, + }) + } + JobState::Cancelled => Ok(LocationFingerprintReply { + job_id: job.job_id.clone(), + consistency: "cancelled".into(), + availability: InspectionAvailability::Unknown as i32, + algorithm: ALGORITHM.into(), + ..LocationFingerprintReply::default() + }), + _ => Ok(LocationFingerprintReply { + job_id: job.job_id.clone(), + consistency: "failed".into(), + availability: InspectionAvailability::Unknown as i32, + algorithm: ALGORITHM.into(), + ..LocationFingerprintReply::default() + }), + } + } + + pub(super) async fn get_location_fingerprint( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + let context = request.context.clone(); + if !matches!(request.algorithm.as_str(), "" | "sha256" | ALGORITHM) { + return Err(Status::invalid_argument( + "algorithm must be \"sha256\" (or empty)", + )); + } + let key = request.idempotency_key.as_str(); + if key.is_empty() || key.len() > 128 || key.chars().any(char::is_control) { + return Err(Status::invalid_argument( + "idempotency_key is required: 1 to 128 bytes without control characters", + )); + } + let max_entries = match request.max_entries as usize { + 0 => DEFAULT_FINGERPRINT_ENTRIES, + max => max.min(MAX_FINGERPRINT_ENTRIES), + }; + let (caller, place, permission) = self + .inspect_place(context.as_ref(), &request.approved_resource_handle) + .await?; + let owner = JobOwner::of(&caller)?; + // Every fingerprint reads the content again: there is no cache to ask for, so + // `require_fresh` changes nothing. + let hash = request_hash(&[ + "location-fingerprint", + &request.approved_resource_handle, + &max_entries.to_string(), + ]); + + let _serial = self.mutations.lock.lock().await; + if let Some(job) = self.jobs.replay(&owner, key, hash)? { + self.providers + .authorize_resource(context.as_ref(), permission)?; + return self.fingerprint_reply(&owner, &job).map(Response::new); + } + let running = self.snapshots.begin(&owner)?; + + // The folders are opened under the plugin's namespace lock, which is then let go: the + // reading takes as long as it takes and must not hold up the plugin's other calls. + let (files, feed, session) = ( + self.files.clone(), + self.library.clone(), + caller.session_id.clone(), + ); + let handle = request.approved_resource_handle.clone(); + let plan = self + .in_namespace(&caller, move |namespace| { + let mut plan = Plan { + scope: String::new(), + revision: 0, + folders: Vec::new(), + partial: false, + unavailable: None, + }; + match place { + Place::Handle { .. } => { + match open_handle_inspect(&files, &feed, namespace, &session, &handle)? { + Ok(opened) => { + plan.scope = format!( + "handle:{}:{}", + opened.approval.id, + opened.path.join("/") + ); + plan.folders.push(Folder { + index: None, + approval_id: opened.approval.id.clone(), + start: opened.path.clone(), + patterns: Vec::new(), + opened, + }); + } + Err(error) => { + plan.unavailable = + Some(availability_of(error).ok_or_else(|| file_status(error))?); + } + } + } + Place::Profile { row } => { + plan.scope = format!("profile:{}", row.id); + plan.revision = row.revision; + for (index, directory) in saves::directories_from_json(&row.directories) + .into_iter() + .enumerate() + { + match open_approval_inspect( + &files, + &feed, + namespace, + &directory.approval_id, + directory.path.clone(), + ) { + Ok(Ok(opened)) + if opened.approval.installation_id == row.installation_id => + { + plan.folders.push(Folder { + index: Some(index), + approval_id: directory.approval_id, + start: directory.path, + patterns: directory.naming_patterns, + opened, + }); + } + _ => plan.partial = true, + } + } + } + } + Ok(plan) + }) + .await?; + if let Some(availability) = plan.unavailable { + // There is nothing to read: say why, with no digest and no job. + return Ok(Response::new(LocationFingerprintReply { + algorithm: ALGORITHM.into(), + consistency: "unavailable".into(), + availability: availability as i32, + ..LocationFingerprintReply::default() + })); + } + + let snapshots = self.snapshots.clone(); + let (job_owner, id) = (owner.clone(), fingerprints::new_snapshot_id()?); + let run = work(move |mut ctx| async move { + // The slot stays taken until the job ends, however it ends. + let _running = running; + let cancel = std::sync::Arc::new(AtomicBool::new(false)); + let flag = cancel.clone(); + let hook = snapshots.after_hash(); + let mut blocking = tokio::task::spawn_blocking(move || { + build_snapshot(&plan, id, permission, max_entries, &flag, hook) + }); + let built = tokio::select! { + built = &mut blocking => built, + () = ctx.cancelled() => { + // The walk and the hashing stop at the next entry or chunk. + cancel.store(true, Ordering::Relaxed); + blocking.await + } + }; + match built { + Ok(Some(snapshot)) => { + // Whatever happened to the permission while it ran, nothing is kept for a + // plugin that no longer may inspect. + if let Err(status) = ctx.check() { + return Outcome::stopped(&status); + } + let kept = snapshots.keep(&job_owner, snapshot); + Outcome::succeeded(CODE_READY, &kept.id) + } + Ok(None) => Outcome::cancelled("stopped before it finished"), + Err(_) => Outcome::failed("internal", "the fingerprint could not be made"), + } + }); + let (job, _) = self.start_job( + &caller, + context.clone().unwrap_or_default(), + permission, + key, + hash, + None, + run, + )?; + // A small place is done at once; a large one answers with its job. + let job = self + .jobs + .wait_over(&owner, &job.job_id, self.snapshots.fast_wait()) + .await?; + self.providers + .authorize_resource(context.as_ref(), permission)?; + self.fingerprint_reply(&owner, &job).map(Response::new) + } + + pub(super) async fn compare_location_snapshots( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + let context = request.context.clone(); + let caller = self + .providers + .authorize_resource_session(context.as_ref())?; + let owner = JobOwner::of(&caller)?; + let get = |id: &str| { + self.snapshots + .get(&owner, id) + .ok_or_else(|| Status::not_found("fingerprint not found")) + }; + let before = get(&request.before_snapshot_id)?; + let after = get(&request.after_snapshot_id)?; + // Comparing needs what taking them needed, for both. + for snapshot in [&before, &after] { + self.providers + .authorize_resource(context.as_ref(), snapshot.permission)?; + } + if request.expected_revision != 0 && request.expected_revision != before.revision { + return Err(Status::failed_precondition( + "the place changed since that revision; take new fingerprints", + )); + } + let size = match request.page_size as usize { + 0 => 100, + size => size.min(500), + }; + let start = if request.cursor.is_empty() { + 0 + } else { + request + .cursor + .parse::() + .map_err(|_| Status::invalid_argument("the cursor is not one this host gave"))? + }; + let comparison = fingerprints::compare(&before, &after); + let files = self.files.clone(); + let session = caller.session_id.clone(); + let page: Vec = comparison + .changes + .iter() + .skip(start) + .take(size) + .map(|change| LocationChange { + entry_handle: match &change.current { + Some(now) if FileAccess::fits_handle(&now.path) => { + files.seal_handle(&session, &now.approval_id, &now.path) + } + _ => String::new(), + }, + change_kind: change.kind.as_str().into(), + previous_size_bytes: change.previous_size, + current_size_bytes: change.current_size, + relative_path: change.label.clone(), + }) + .collect(); + let end = start + page.len(); + Ok(Response::new(LocationCompareReply { + changes: page, + next_cursor: if end < comparison.changes.len() { + end.to_string() + } else { + String::new() + }, + status: comparison.status.as_str().into(), + revision: before.revision, + })) + } +} + +fn word(answer: Tri) -> &'static str { + match answer { + Tri::Allowed => "allowed", + Tri::Denied => "denied", + Tri::Unknown => "unknown", + } +} + +fn unknown_access() -> String { + "read=unknown write=unknown create=unknown delete=unknown method=none".into() +} + +fn access_entry(entry_handle: String, info: &AccessInfo) -> LocationAccessEntry { + LocationAccessEntry { + entry_handle, + read_only_state: if info.read_only { + "read_only" + } else { + "writable" + } + .into(), + effective_access: format!( + "read={} write={} create={} delete={} method={ACCESS_METHOD}", + word(info.read), + word(info.write), + word(info.create), + word(info.delete) + ), + availability: InspectionAvailability::Available as i32, + } +} + +#[tonic::async_trait] +impl locations_server::Locations for ResourceApi { + type WatchAvailabilityStream = BoxStream; + + async fn inspect( + &self, + request: Request, + ) -> Result, Status> { + self.inspect_location(request).await + } + + async fn get_size( + &self, + request: Request, + ) -> Result, Status> { + self.get_location_size(request).await + } + + async fn get_access( + &self, + request: Request, + ) -> Result, Status> { + self.get_location_access(request).await + } + + async fn get_last_modified( + &self, + request: Request, + ) -> Result, Status> { + self.get_location_last_modified(request).await + } + + async fn get_fingerprint( + &self, + request: Request, + ) -> Result, Status> { + self.get_location_fingerprint(request).await + } + + async fn compare( + &self, + request: Request, + ) -> Result, Status> { + self.compare_location_snapshots(request).await + } + + async fn watch_availability( + &self, + request: Request, + ) -> Result, Status> { + self.watch_location_availability(request).await + } +} diff --git a/crates/app/src/plugin_host/resources/locations/volumes.rs b/crates/app/src/plugin_host/resources/locations/volumes.rs new file mode 100644 index 000000000..9c503c2ba --- /dev/null +++ b/crates/app/src/plugin_host/resources/locations/volumes.rs @@ -0,0 +1,290 @@ +//! Volume observations are read-only worker operations. Watches poll with bounded backpressure. +use super::*; +use gamenode_platform::plugin_storage::FileApproval; +use gamenode_platform::volume; +use std::path::Path; +use tokio_stream::wrappers::ReceiverStream; + +static WATCH_SLOTS: std::sync::LazyLock> = + std::sync::LazyLock::new(|| Arc::new(tokio::sync::Semaphore::new(64))); + +fn describe(approval: &FileApproval, id: String) -> LocationDescription { + let path = Path::new(&approval.root); + let mut ancestor = Some(path); + let info = loop { + let Some(candidate) = ancestor else { + break None; + }; + if let Some(info) = volume::volume_info(candidate) { + break Some(info); + } + ancestor = candidate.parent(); + }; + let mut result = LocationDescription { + resource_id: id, + availability: InspectionAvailability::Unknown as i32, + network_state: "unknown".into(), + media_type: "unknown".into(), + attachment: "unknown".into(), + interface_type: "unknown".into(), + evidence: if cfg!(target_os = "linux") { + "mountinfo/statvfs; sysfs connection and rotational hints; unknown is not evidence of internal storage or SSD" + } else if cfg!(windows) { + "Win32 volume GUID, drive type and capacity; physical interface and medium unknown" + } else { "platform metadata unavailable" }.into(), + observed_at: std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_secs() as i64), + ..Default::default() + }; + match info { + None => { + result.availability = match std::fs::metadata(&approval.root) { + Err(e) if e.kind() == std::io::ErrorKind::PermissionDenied => { + InspectionAvailability::Inaccessible + } + _ => InspectionAvailability::Disconnected, + } as i32; + } + Some(info) => { + if approval.volume_token.is_empty() + || info.volume_identity_token != approval.volume_token + { + result.availability = InspectionAvailability::Disconnected as i32; + // Do not disclose metadata for the replacement volume. + return result; + } + result.availability = if std::fs::metadata(path).is_ok() { + InspectionAvailability::Available + } else { + InspectionAvailability::Missing + } as i32; + result.volume_identity_token = info.volume_identity_token; + result.mount_point = info.mount_point; + result.network_state = info.locality.as_str().into(); + result.media_type = info.media_type.as_str().into(); + result.attachment = info.removability.as_str().into(); + result.interface_type = info.bus_type.as_str().into(); + result.capacity_bytes = info.capacity_bytes; + result.free_bytes = info.free_bytes; + result.observed_at = info.observed_at; + } + } + result +} + +impl ResourceApi { + pub(super) async fn inspect_location( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + for dimension in &request.requested_dimensions { + if !matches!( + dimension.as_str(), + "availability" + | "volume" + | "locality" + | "attachment" + | "interface" + | "media" + | "capacity" + ) { + return Err(Status::invalid_argument("unsupported inspection dimension")); + } + } + let context = request.context; + let handle = request.approved_resource_handle; + let (caller, place, permission) = self.inspect_place(context.as_ref(), &handle).await?; + let (files, feed, session) = ( + self.files.clone(), + self.library.clone(), + caller.session_id.clone(), + ); + let reply = self + .in_namespace(&caller, move |namespace| { + let mut locations = Vec::new(); + match place { + Place::Handle { .. } => { + let approval = + approval_of_handle(&files, &feed, namespace, &session, &handle)?; + let mut description = describe(&approval, handle.clone()); + if description.availability == InspectionAvailability::Available as i32 { + // Revalidate both the folder identity and the relative entry; the latter + // can be missing even when its approved volume is still mounted. + match open_handle_inspect(&files, &feed, namespace, &session, &handle)? + { + Ok(opened) => { + if let Err(error) = opened.confined.stat(&opened.path) { + description.availability = availability_of(error) + .ok_or_else(|| file_status(error))? + as i32; + } + } + Err(error) => { + description.availability = availability_of(error) + .ok_or_else(|| file_status(error))? + as i32 + } + } + } + locations.push(description); + } + Place::Profile { row } => { + for (index, directory) in saves::directories_from_json(&row.directories) + .into_iter() + .enumerate() + { + let approval = namespace + .approval(&directory.approval_id)? + .filter(|a| a.revoked_at.is_none()) + .ok_or_else(|| Status::not_found("folder approval not found"))?; + // Validate scope and affected games just as a regular handle does. + let root_handle = + files.seal_handle(&session, &approval.id, &directory.path); + let approval = approval_of_handle( + &files, + &feed, + namespace, + &session, + &root_handle, + )?; + if approval.installation_id != row.installation_id { + return Err(Status::not_found("folder approval not found")); + } + let mut description = describe(&approval, format!("{handle}/d{index}")); + if description.availability == InspectionAvailability::Available as i32 + { + match open_approval_inspect( + &files, + &feed, + namespace, + &approval.id, + directory.path, + )? { + Ok(opened) => { + if let Err(error) = opened.confined.stat(&opened.path) { + description.availability = availability_of(error) + .ok_or_else(|| file_status(error))? + as i32; + } + } + Err(error) => { + description.availability = availability_of(error) + .ok_or_else(|| file_status(error))? + as i32 + } + } + } + locations.push(description); + } + } + } + let location = if locations.len() == 1 { + locations.first().cloned() + } else { + Some(LocationDescription { + resource_id: handle, + availability: if locations + .iter() + .all(|l| l.availability == InspectionAvailability::Available as i32) + { + InspectionAvailability::Available + } else { + InspectionAvailability::Unknown + } as i32, + network_state: "unknown".into(), + media_type: "unknown".into(), + attachment: "unknown".into(), + interface_type: "unknown".into(), + ..Default::default() + }) + }; + Ok(LocationInspectReply { + location, + locations, + observations: vec![], + }) + }) + .await?; + self.providers + .authorize_resource(context.as_ref(), permission)?; + Ok(Response::new(reply)) + } + + pub(super) async fn watch_location_availability( + &self, + request: Request, + ) -> Result>, Status> { + let permit = WATCH_SLOTS + .clone() + .try_acquire_owned() + .map_err(|_| Status::resource_exhausted("availability watch limit reached"))?; + let request = request.into_inner(); + if request.after_sequence != 0 { + return Err(Status::failed_precondition( + "availability streams have no replay; resubscribe with after_sequence=0 for a fresh observation", + )); + } + let inspect = LocationInspectRequest { + context: request.context, + approved_resource_handle: request.approved_resource_handle, + ..Default::default() + }; + let initial = self + .inspect_location(Request::new(inspect.clone())) + .await? + .into_inner(); + let api = self.clone(); + // A bounded queue stops slow consumers. Dropping the receiver stops polling. + let (tx, rx) = tokio::sync::mpsc::channel(128); + tokio::spawn(async move { + let _permit = permit; + let mut sequence = 0u64; + let mut previous = Vec::new(); + let mut reply = initial; + loop { + for location in &reply.locations { + let state = ( + location.resource_id.clone(), + location.availability, + location.volume_identity_token.clone(), + ); + if !previous.contains(&state) { + sequence += 1; + let event = LocationAvailabilityEvent { + sequence, + resource_id: state.0, + availability: state.1, + volume_identity_token: state.2, + observed_at: location.observed_at, + }; + if tx.try_send(Ok(event)).is_err() { + return; + } + } + } + previous = reply + .locations + .iter() + .map(|l| { + ( + l.resource_id.clone(), + l.availability, + l.volume_identity_token.clone(), + ) + }) + .collect(); + tokio::select! { _ = tx.closed() => return, _ = tokio::time::sleep(Duration::from_secs(1)) => {} } + match api.inspect_location(Request::new(inspect.clone())).await { + Ok(next) => reply = next.into_inner(), + Err(error) => { + let _ = tx.try_send(Err(error)); + return; + } + } + } + }); + Ok(Response::new(Box::pin(ReceiverStream::new(rx)))) + } +} diff --git a/crates/app/src/plugin_host/resources/matching.rs b/crates/app/src/plugin_host/resources/matching.rs new file mode 100644 index 000000000..a8fa0942e --- /dev/null +++ b/crates/app/src/plugin_host/resources/matching.rs @@ -0,0 +1,197 @@ +//! Catalog search and match assignment of `ResourceHost`. +//! +//! Search spends the user's verified GameNode session on a title query, so it is bounded: a +//! short query, one small page and a per-plugin rate. Assign changes one of the caller's own +//! entries through the library's own match policy: the entry's revision must be current, the game +//! must be one the host knows or a search just offered, and a match the user chose is never +//! replaced. Like every mutation it needs an idempotency key and is serialized with the others. + +use std::collections::{HashMap, VecDeque}; +use std::sync::Mutex; +use std::time::{Duration, Instant}; + +use gamenode_plugin_protocol::{capability as cap, proto::*}; +use tonic::{Request, Response, Status}; + +use super::mutations::{game_id, mutation_key, reply, request_hash, unavailable}; +use super::{ResourceApi, Scope}; +use crate::plugin_host::library::MatchWrite; + +const MAX_QUERY_BYTES: usize = 128; +const DEFAULT_RESULTS: usize = 20; +const MAX_RESULTS: usize = 50; +/// Catalog searches one plugin may start per window, across its sessions. +pub(super) const SEARCHES_PER_WINDOW: usize = 20; +const SEARCH_WINDOW: Duration = Duration::from_secs(60); +const MAX_INSTALLATION_ID_BYTES: usize = 128; + +/// Recent search times by plugin and profile epoch. +#[derive(Default)] +pub(super) struct SearchLimiter { + recent: Mutex>>, +} + +impl SearchLimiter { + fn admit(&self, provider: &str, epoch: u64) -> Result<(), Status> { + let mut recent = self.recent.lock().unwrap_or_else(|p| p.into_inner()); + let now = Instant::now(); + recent.retain(|_, times| { + times.retain(|at| now.duration_since(*at) < SEARCH_WINDOW); + !times.is_empty() + }); + let times = recent.entry((provider.to_owned(), epoch)).or_default(); + if times.len() >= SEARCHES_PER_WINDOW { + return Err(Status::resource_exhausted( + "too many catalog searches; try again in a minute", + )); + } + times.push_back(now); + Ok(()) + } +} + +/// The trimmed query of a search. +fn query(text: &str) -> Result<&str, Status> { + let text = text.trim(); + if text.is_empty() { + return Err(Status::invalid_argument("query is required")); + } + if text.len() > MAX_QUERY_BYTES { + return Err(Status::invalid_argument("query is longer than 128 bytes")); + } + if text.chars().any(char::is_control) { + return Err(Status::invalid_argument( + "query contains control characters", + )); + } + Ok(text) +} + +impl ResourceApi { + pub(super) async fn search_catalog( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + let caller = self + .providers + .authorize_resource(request.context.as_ref(), cap::MATCHING_READ)?; + let text = query(&request.query)?; + if !request.platform.is_empty() { + return Err(Status::invalid_argument( + "platform filters are not supported; leave platform empty", + )); + } + if !request.cursor.is_empty() { + return Err(Status::invalid_argument( + "a search is a single page; leave cursor empty", + )); + } + let limit = match request.page_size as usize { + 0 => DEFAULT_RESULTS, + size => size.min(MAX_RESULTS), + }; + let host = self.library.host().ok_or_else(unavailable)?; + self.searches + .admit(&caller.provider_id, caller.profile_epoch)?; + let games = host.search_catalog(text.to_owned(), limit).await?; + // The answer was fetched for a call that may since have lost its permission. + self.providers + .authorize_resource(request.context.as_ref(), cap::MATCHING_READ)?; + Ok(Response::new(MatchingSearchReply { + candidates: games + .into_iter() + .map(|game| MatchCandidate { + game_id: game.id.to_string(), + title: game.name, + platform: String::new(), + confidence: String::new(), + release_year: game.release_year.unwrap_or(0), + }) + .collect(), + next_cursor: String::new(), + })) + } + + pub(super) async fn assign_match( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + let mutation = request + .mutation + .as_ref() + .ok_or_else(|| Status::invalid_argument("mutation is required"))?; + let caller = self + .providers + .authorize_resource(mutation.context.as_ref(), cap::MATCHING_WRITE)?; + let key = mutation_key(mutation)?; + if !request.provider_id.is_empty() || !request.provider_game_id.is_empty() { + return Err(Status::invalid_argument( + "name the entry by installation_id; provider_id and provider_game_id are reserved", + )); + } + if request.installation_id.is_empty() { + return Err(Status::invalid_argument("installation_id is required")); + } + if request.installation_id.len() > MAX_INSTALLATION_ID_BYTES { + return Err(Status::invalid_argument("installation_id is too long")); + } + let game = game_id(&request.gamenode_game_id)? + .ok_or_else(|| Status::invalid_argument("gamenode_game_id is required"))?; + let hash = request_hash(&[ + "match", + &request.installation_id, + &game.to_string(), + &mutation.expected_revision.to_string(), + ]); + + let _serial = self.mutations.lock.lock().await; + if let Some(original) = self.mutations.replay(&caller, key, hash)? { + return Ok(Response::new(original)); + } + // Writes never reach another provider's entries, whatever the caller may read. + let own = Scope { + own_provider: caller.provider_id.clone(), + read_all: false, + provider_filter: None, + }; + let (entry_key, entry) = self + .library + .target(&own, &request.installation_id) + .ok_or_else(|| Status::not_found("library entry not found"))?; + let host = self.library.host().ok_or_else(unavailable)?; + let guard = self.guard( + mutation.context.clone().unwrap_or_default(), + cap::MATCHING_WRITE, + caller.grant_revision, + ); + let (outcome, revision, commit) = match host.assign_match( + &entry_key, + game, + mutation.expected_revision, + guard.as_ref(), + )? { + MatchWrite::Applied { revision } => (MutationOutcome::Applied, revision, true), + MatchWrite::AlreadyApplied { revision } => { + (MutationOutcome::AlreadyApplied, revision, true) + } + MatchWrite::Conflict { current } => (MutationOutcome::RevisionConflict, current, false), + MatchWrite::UnknownGame => { + return Err(Status::not_found( + "the game is not known to GameNode on this device; find it with MatchingSearch first", + )); + } + MatchWrite::UserChoice => { + return Err(Status::failed_precondition( + "the user chose this entry's match; only the user can change it", + )); + } + }; + let answer = reply(&entry.installation_id, revision, outcome); + if commit { + self.mutations.remember(&caller, key, hash, &answer); + } + Ok(Response::new(answer)) + } +} diff --git a/crates/app/src/plugin_host/resources/mutations.rs b/crates/app/src/plugin_host/resources/mutations.rs new file mode 100644 index 000000000..cd05c297d --- /dev/null +++ b/crates/app/src/plugin_host/resources/mutations.rs @@ -0,0 +1,450 @@ +//! Display-metadata and favorite services of `ResourceHost`. +//! +//! Both are mutations of the caller's own library entries: the plugin names an installation (or +//! a GameNode game one of its own entries is matched to), the host validates the request against +//! Core rules, and the engine commits it. Every mutation needs an idempotency key. A retried key +//! with the same request returns the original committed outcome; the same key with another +//! request is refused. The table is in memory (bounded, 24 hours), so a replay after a restart +//! falls back to the resource's own guard: metadata is protected by its revision, and favorites +//! are desired-state writes that are idempotent by nature. + +use std::collections::HashMap; +use std::sync::Mutex; +use std::time::{Duration, Instant}; + +use gamenode_core::library::DisplayWrite; +use gamenode_plugin_protocol::{capability as cap, proto::*}; +use sha2::{Digest, Sha256}; +use tonic::{Request, Response, Status}; + +use super::{DEFAULT_PAGE_SIZE, MAX_PAGE_SIZE, ResourceApi, Scope, no_common_data, stale_cursor}; +use crate::plugin_host::library::{CommitGuard, CursorBinding, CursorError, FavoriteWrite}; +use crate::plugin_host::provider::ResourceCaller; + +/// The only display field a plugin may write. +pub const DISPLAY_NAME: &str = "display_name"; +const MAX_DISPLAY_NAME_BYTES: usize = 256; +const MAX_KEY_BYTES: usize = 128; +const IDEMPOTENCY_TTL: Duration = Duration::from_secs(24 * 60 * 60); +const IDEMPOTENCY_PER_PLUGIN: usize = 1024; + +struct Seen { + hash: [u8; 32], + reply: MutationReply, + /// A fact some replies carry beyond [`MutationReply`] (a storage value's expiry); 0 if none. + extra: i64, + at: Instant, +} + +/// Serializes mutating calls and remembers their committed outcomes by +/// `(authenticated namespace, profile epoch, idempotency key)`; a new profile starts with no keys. +#[derive(Default)] +pub(super) struct Mutations { + pub(super) lock: tokio::sync::Mutex<()>, + seen: Mutex>, +} + +impl Mutations { + pub(super) fn replay( + &self, + caller: &ResourceCaller, + key: &str, + hash: [u8; 32], + ) -> Result, Status> { + Ok(self.replay_with(caller, key, hash)?.map(|(reply, _)| reply)) + } + + /// [`replay`](Self::replay), also returning the `extra` value stored with the outcome. + pub(crate) fn replay_with( + &self, + caller: &ResourceCaller, + key: &str, + hash: [u8; 32], + ) -> Result, Status> { + let mut seen = self.seen.lock().unwrap_or_else(|p| p.into_inner()); + let id = (mutation_owner(caller), caller.profile_epoch, key.to_owned()); + match seen.get(&id) { + Some(entry) if entry.at.elapsed() >= IDEMPOTENCY_TTL => { + seen.remove(&id); + Ok(None) + } + Some(entry) if entry.hash == hash => Ok(Some((entry.reply.clone(), entry.extra))), + Some(_) => Err(Status::failed_precondition( + "the idempotency key was already used for a different request", + )), + None => Ok(None), + } + } + + pub(super) fn remember( + &self, + caller: &ResourceCaller, + key: &str, + hash: [u8; 32], + reply: &MutationReply, + ) { + self.remember_with(caller, key, hash, reply, 0); + } + + /// [`remember`](Self::remember), keeping `extra` beside the outcome. + pub(crate) fn remember_with( + &self, + caller: &ResourceCaller, + key: &str, + hash: [u8; 32], + reply: &MutationReply, + extra: i64, + ) { + let mut seen = self.seen.lock().unwrap_or_else(|p| p.into_inner()); + seen.retain(|_, entry| entry.at.elapsed() < IDEMPOTENCY_TTL); + let own = |(provider, epoch, _): &(String, u64, String)| { + *provider == mutation_owner(caller) && *epoch == caller.profile_epoch + }; + if seen.keys().filter(|id| own(id)).count() >= IDEMPOTENCY_PER_PLUGIN + && let Some(oldest) = seen + .iter() + .filter(|(id, _)| own(id)) + .min_by_key(|(_, entry)| entry.at) + .map(|(id, _)| id.clone()) + { + seen.remove(&oldest); + } + seen.insert( + (mutation_owner(caller), caller.profile_epoch, key.to_owned()), + Seen { + hash, + reply: reply.clone(), + extra, + at: Instant::now(), + }, + ); + } +} + +// Provider-free extensions share an empty provider id; their authenticated namespace, +// not that alias, owns mutation receipts. +pub(super) fn mutation_owner(caller: &ResourceCaller) -> String { + caller + .namespace + .as_ref() + .map(|resolver| resolver.library_recipe_owner_key()) + .unwrap_or_else(|| format!("provider:{}", caller.provider_id)) +} + +/// A digest of a request's meaningful fields, length-prefixed so parts cannot run together. +pub(super) fn request_hash(parts: &[&str]) -> [u8; 32] { + let mut hash = Sha256::new(); + for part in parts { + hash.update((part.len() as u64).to_be_bytes()); + hash.update(part.as_bytes()); + } + hash.finalize().into() +} + +/// Hashes a request containing a potentially large binary field without expanding it into text. +pub(super) fn request_hash_with_bytes(parts: &[&str], bytes: &[u8]) -> [u8; 32] { + let mut hash = Sha256::new(); + for part in parts { + hash.update((part.len() as u64).to_be_bytes()); + hash.update(part.as_bytes()); + } + hash.update((bytes.len() as u64).to_be_bytes()); + hash.update(bytes); + hash.finalize().into() +} + +/// The idempotency key of a mutation, after the shape checks every mutation shares. +pub(super) fn mutation_key(mutation: &MutationContext) -> Result<&str, Status> { + if mutation.operation_id.len() > MAX_KEY_BYTES { + return Err(Status::invalid_argument("operation_id is too long")); + } + let key = mutation.idempotency_key.as_str(); + if key.is_empty() || key.len() > MAX_KEY_BYTES || key.chars().any(char::is_control) { + return Err(Status::invalid_argument( + "idempotency_key is required: 1 to 128 bytes without control characters", + )); + } + Ok(key) +} + +/// The display name a request sets (`Some`) or clears (`None`, from an empty value). +fn display_name(fields: &HashMap) -> Result, Status> { + if fields.is_empty() { + return Err(Status::invalid_argument( + "display_fields is empty; the writable field is display_name", + )); + } + if let Some(other) = fields.keys().find(|key| key.as_str() != DISPLAY_NAME) { + return Err(Status::invalid_argument(format!( + "display_fields.{other} is not writable; the writable field is display_name" + ))); + } + let value = fields[DISPLAY_NAME].trim(); + if value.len() > MAX_DISPLAY_NAME_BYTES { + return Err(Status::invalid_argument( + "display_name is longer than 256 bytes", + )); + } + if value.chars().any(char::is_control) { + return Err(Status::invalid_argument( + "display_name contains control characters", + )); + } + Ok((!value.is_empty()).then(|| value.to_owned())) +} + +pub(super) fn game_id(text: &str) -> Result, Status> { + match text { + "" => Ok(None), + text => text + .parse::() + .map(Some) + .map_err(|_| Status::invalid_argument("invalid game_id")), + } +} + +pub(super) fn reply(resource_id: &str, revision: u64, outcome: MutationOutcome) -> MutationReply { + MutationReply { + resource_id: resource_id.to_owned(), + revision, + outcome: outcome as i32, + } +} + +impl ResourceApi { + /// Fails unless `profile_id` is empty or names the active account profile. + fn check_profile(&self, profile_id: &str) -> Result<(), Status> { + if profile_id.is_empty() { + return Ok(()); + } + match self.providers.profiles().current() { + Some(profile) if profile.profile_id() == profile_id => Ok(()), + _ => Err(Status::failed_precondition( + "profile_id is not the active profile", + )), + } + } + + /// A commit-time check for `permission` that also fails when the grants changed since the + /// call was authorized. + pub(super) fn guard( + &self, + context: ServiceContext, + permission: &'static str, + grant_revision: u64, + ) -> CommitGuard { + let providers = self.providers.clone(); + Box::new(move || { + let current = providers.authorize_resource(Some(&context), permission)?; + if current.grant_revision == grant_revision { + Ok(()) + } else { + Err(Status::failed_precondition( + "plugin permissions changed; try again", + )) + } + }) + } + + pub(super) async fn update_metadata( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + let mutation = request + .mutation + .as_ref() + .ok_or_else(|| Status::invalid_argument("mutation is required"))?; + let caller = self + .providers + .authorize_resource(mutation.context.as_ref(), cap::LIBRARY_METADATA_WRITE)?; + let key = mutation_key(mutation)?; + let name = display_name(&request.display_fields)?; + let expected_game = game_id(&request.game_id)?; + if request.installation_id.is_empty() { + return Err(Status::invalid_argument("installation_id is required")); + } + let hash = request_hash(&[ + "metadata", + &request.installation_id, + &request.game_id, + &mutation.expected_revision.to_string(), + name.as_deref().unwrap_or("\u{0}"), + ]); + + let _serial = self.mutations.lock.lock().await; + if let Some(original) = self.mutations.replay(&caller, key, hash)? { + return Ok(Response::new(original)); + } + // Writes never reach another provider's entries, whatever the caller may read. + let own = Scope { + own_provider: caller.provider_id.clone(), + read_all: false, + provider_filter: None, + }; + let (entry_key, entry) = self + .library + .target(&own, &request.installation_id) + .filter(|(_, entry)| expected_game.is_none() || entry.game_id == expected_game) + .ok_or_else(|| Status::not_found("library entry not found"))?; + let host = self.library.host().ok_or_else(unavailable)?; + let guard = self.guard( + mutation.context.clone().unwrap_or_default(), + cap::LIBRARY_METADATA_WRITE, + caller.grant_revision, + ); + let written = host + .set_display_name(entry_key, mutation.expected_revision, name, guard) + .await?; + let (outcome, revision, commit) = match written { + DisplayWrite::Applied { revision } => (MutationOutcome::Applied, revision, true), + DisplayWrite::Unchanged { revision } => { + (MutationOutcome::AlreadyApplied, revision, true) + } + DisplayWrite::Conflict { current } => { + (MutationOutcome::RevisionConflict, current, false) + } + }; + let answer = reply(&entry.installation_id, revision, outcome); + if commit { + self.mutations.remember(&caller, key, hash, &answer); + } + Ok(Response::new(answer)) + } + + pub(super) async fn set_favorite( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + let mutation = request + .mutation + .as_ref() + .ok_or_else(|| Status::invalid_argument("mutation is required"))?; + let caller = self + .providers + .authorize_resource(mutation.context.as_ref(), cap::FAVORITES_WRITE)?; + let key = mutation_key(mutation)?; + if mutation.expected_revision != 0 { + return Err(Status::invalid_argument( + "favorites carry no revision; expected_revision must be 0", + )); + } + self.check_profile(&request.profile_id)?; + let game = game_id(&request.game_id)? + .ok_or_else(|| Status::invalid_argument("game_id is required"))?; + let hash = request_hash(&[ + "favorite", + &game.to_string(), + if request.favorite { "1" } else { "0" }, + ]); + + let _serial = self.mutations.lock.lock().await; + if let Some(original) = self.mutations.replay(&caller, key, hash)? { + return Ok(Response::new(original)); + } + let host = self.library.host().ok_or_else(unavailable)?; + let guard = self.guard( + mutation.context.clone().unwrap_or_default(), + cap::FAVORITES_WRITE, + caller.grant_revision, + ); + let outcome = + match host.set_favorite(&caller.provider_id, game, request.favorite, guard.as_ref())? { + FavoriteWrite::Applied => MutationOutcome::Applied, + FavoriteWrite::AlreadyApplied => MutationOutcome::AlreadyApplied, + // The same answer for an unknown game and for one only another provider has. + FavoriteWrite::NoMatchedEntry => { + return Err(Status::not_found( + "none of this provider's entries is matched to that game", + )); + } + }; + let answer = reply(&game.to_string(), 0, outcome); + self.mutations.remember(&caller, key, hash, &answer); + Ok(Response::new(answer)) + } + + pub(super) async fn list_favorites( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + let page = request + .page + .ok_or_else(|| Status::invalid_argument("page is required"))?; + let caller = self + .providers + .authorize_resource(page.context.as_ref(), cap::FAVORITES_READ)?; + no_common_data(page.common_data_categories.as_ref())?; + self.check_profile(&request.profile_id)?; + let limit = match page.page_size as usize { + 0 => DEFAULT_PAGE_SIZE, + size => size.min(MAX_PAGE_SIZE), + }; + let binding = CursorBinding { + route: "favorites", + session_id: caller.session_id.clone(), + profile_epoch: caller.profile_epoch, + grant_revision: caller.grant_revision, + scope: Scope { + own_provider: caller.provider_id.clone(), + read_all: false, + provider_filter: None, + }, + search: None, + }; + let resumed = if page.cursor.is_empty() { + None + } else { + let (after, issued) = + self.library + .open_cursor(&page.cursor, &binding) + .map_err(|error| match error { + CursorError::Malformed => { + Status::invalid_argument("invalid favorites cursor") + } + CursorError::Stale => stale_cursor(), + })?; + let after = after + .parse::() + .map_err(|_| Status::invalid_argument("invalid favorites cursor"))?; + Some((after, issued)) + }; + let host = self.library.host().ok_or_else(unavailable)?; + let revision = self.library.revision(); + if resumed.is_some_and(|(_, issued)| issued != revision) { + return Err(stale_cursor()); + } + let mut games = host.favorites(&caller.provider_id); + games.sort_unstable_by_key(|(game, _)| *game); + let after = resumed.map(|(after, _)| after); + let mut remaining = games + .into_iter() + .filter(|(game, _)| after.is_none_or(|after| *game > after)); + let entries: Vec<_> = remaining.by_ref().take(limit).collect(); + let next_cursor = match entries.last() { + Some((last, _)) if remaining.next().is_some() => { + self.library + .issue_cursor(&binding, revision, &last.to_string()) + } + _ => String::new(), + }; + Ok(Response::new(FavoritesListReply { + entries: entries + .into_iter() + .map(|(game, favorite)| FavoriteEntry { + game_id: game.to_string(), + favorite, + revision: 0, + }) + .collect(), + next_cursor, + revision, + })) + } +} + +pub(super) fn unavailable() -> Status { + Status::unavailable("the library is not available") +} diff --git a/crates/app/src/plugin_host/resources/network.rs b/crates/app/src/plugin_host/resources/network.rs new file mode 100644 index 000000000..9418af120 --- /dev/null +++ b/crates/app/src/plugin_host/resources/network.rs @@ -0,0 +1,152 @@ +//! `NetworkFetch` of `ResourceHost`. +//! +//! A plugin asks the host to fetch an https URL. It needs `network.fetch` *and* an approved +//! origin: the URL's exact origin (scheme, host, port) must be one the user approved for this +//! plugin, and nothing is reachable by default. The origin is checked again for every redirect +//! hop, so an unapproved or since-revoked origin is never contacted. The host adds no +//! credentials of its own, never connects to loopback, private, link-local or similar addresses +//! (the checks are in [`gamenode_platform::plugin_network`]), bounds the response and the whole +//! fetch, and answers a refusal without saying where a name resolved or where a redirect led. + +use std::collections::HashMap; +use std::sync::Arc; + +use gamenode_platform::plugin_network::{FetchError, Request as Fetch}; +use gamenode_plugin_protocol::{capability as cap, proto::*}; +use tonic::{Request, Response, Status}; + +use super::ResourceApi; +use crate::plugin_host::network::AllowOrigin; +use crate::plugin_host::provider::ResourceCaller; + +fn fetch_status(error: FetchError, denied: impl FnOnce() -> Status) -> Status { + match error { + FetchError::Denied => denied(), + FetchError::TooLarge => Status::resource_exhausted( + "the response is larger than max_response_bytes (at most 8 MiB); nothing was truncated", + ), + FetchError::Timeout => Status::deadline_exceeded("the fetch took longer than timeout_ms"), + FetchError::TooManyRedirects => Status::failed_precondition("too many redirects"), + FetchError::Unreachable => Status::unavailable("the destination could not be reached"), + FetchError::BadResponse => Status::unavailable("the destination sent an invalid redirect"), + } +} + +impl ResourceApi { + pub(super) async fn fetch_url( + &self, + request: Request, + ) -> Result, Status> { + let NetworkFetchRequest { + context, + url, + method, + headers, + body, + max_response_bytes, + timeout_ms, + } = request.into_inner(); + let caller = self + .providers + .authorize_resource(context.as_ref(), cap::NETWORK_FETCH)?; + let resolver = caller.namespace.as_ref().ok_or_else(|| { + Status::failed_precondition("official providers use trusted host adapters") + })?; + let identity = resolver.identity().clone(); + let owner = *resolver.storage_owner().key(); + let fetcher = self + .network + .fetcher() + .ok_or_else(|| Status::unavailable("network fetch is not available"))?; + + let headers: Vec<(&str, &str)> = headers + .iter() + .map(|(name, value)| (name.as_str(), value.as_str())) + .collect(); + let fetch = Fetch::build(&url, &method, headers, body, max_response_bytes, timeout_ms) + .map_err(|error| Status::invalid_argument(error.to_string()))?; + // The origin the plugin may reach is the user's to name, and exact. + let origin = fetch + .origin() + .ok_or_else(|| Status::invalid_argument("url must be an https URL"))?; + let _slots = self.network.permits(owner)?; + let profiles = self.providers.profiles(); + let mut profile_changes = profiles.subscribe(); + let mut permission_changes = profiles.subscribe_permissions(); + let approved = self + .network + .approved_origins(&identity, caller.profile_epoch) + .await + .filter(|approved| approved.origins.contains(&origin)) + .ok_or_else(|| self.deny_scope(&caller))?; + + // Pin the permission revision so even revoke-then-reapprove fences this fetch. + let profile_epoch = caller.profile_epoch; + let session_revision = caller.grant_revision; + let allow: AllowOrigin = { + let providers = self.providers.clone(); + let network = self.network.clone(); + let context = context.clone(); + Arc::new(move |origin| { + let (providers, network, context, identity) = ( + providers.clone(), + network.clone(), + context.clone(), + identity.clone(), + ); + let revision = approved.revision; + Box::pin(async move { + network + .approved_origins(&identity, profile_epoch) + .await + .is_some_and(|current| { + current.revision == revision && current.origins.contains(&origin) + }) + && providers + .authorize_resource(context.as_ref(), cap::NETWORK_FETCH) + .is_ok_and(|current| current.grant_revision == session_revision) + }) + }) + }; + let revoked = async { + loop { + tokio::select! { + _ = profile_changes.changed() => {}, + _ = permission_changes.changed() => {}, + } + if !allow(origin.clone()).await { + break; + } + } + }; + let response = tokio::select! { + _ = revoked => { + self.providers.authorize_resource(context.as_ref(), cap::NETWORK_FETCH)?; + return Err(self.deny_scope(&caller)); + } + response = fetcher.fetch(fetch, allow.clone()) => response, + }; + // Recheck even when the current hop completed without a redirect. + self.providers + .authorize_resource(context.as_ref(), cap::NETWORK_FETCH)?; + if !allow(origin.clone()).await { + return Err(self.deny_scope(&caller)); + } + let response = + response.map_err(|error| fetch_status(error, || self.deny_scope(&caller)))?; + if response.final_origin != origin && !allow(response.final_origin.clone()).await { + return Err(self.deny_scope(&caller)); + } + Ok(Response::new(NetworkFetchReply { + status_code: u32::from(response.status), + headers: response.headers.into_iter().collect::>(), + body: response.body, + final_origin: response.final_origin, + })) + } + + fn deny_scope(&self, caller: &ResourceCaller) -> Status { + self.providers + .deny_resource_scope(caller, cap::NETWORK_FETCH) + } +} diff --git a/crates/app/src/plugin_host/resources/notifications.rs b/crates/app/src/plugin_host/resources/notifications.rs new file mode 100644 index 000000000..9b842bba1 --- /dev/null +++ b/crates/app/src/plugin_host/resources/notifications.rs @@ -0,0 +1,118 @@ +//! `NotificationsPublish` of `ResourceHost`. +//! +//! A plugin with `notifications.publish` may ask Core to show a short plain-text notice. Core +//! attributes it to the authenticated plugin, never to a name in the request, bounds and checks the +//! text ([`crate::plugin_host::notifications`]), lets a plugin speak only a few times a minute +//! and hands the notice to the application, which renders it as plain text. A retried key is +//! answered from the first delivery, so a notice is shown once; a call that was refused for its rate +//! is not remembered, so it can be retried after the wait. + +use gamenode_plugin_protocol::{capability as cap, proto::*}; +use tonic::{Request, Response, Status}; + +use super::ResourceApi; +use super::mutations::{mutation_key, reply, request_hash}; +use crate::plugin_host::notifications::{ + MAX_TRANSLATIONS, PluginNotice, Severity, Text, check_text, +}; + +impl ResourceApi { + pub(super) async fn publish_notification( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + let mutation = request + .mutation + .as_ref() + .ok_or_else(|| Status::invalid_argument("mutation is required"))?; + let context = mutation.context.clone().unwrap_or_default(); + let caller = self + .providers + .authorize_resource(Some(&context), cap::NOTIFICATIONS_PUBLISH)?; + let key = mutation_key(mutation)?; + if mutation.expected_revision != 0 { + return Err(Status::invalid_argument( + "notifications carry no revision; expected_revision must be 0", + )); + } + let resolver = caller.namespace.as_ref().ok_or_else(|| { + Status::failed_precondition("official providers use trusted host adapters") + })?; + let plugin_id = resolver.identity().plugin_id.clone(); + let owner = *resolver.storage_owner().key(); + + let invalid = |refused: crate::plugin_host::notifications::Refused| { + Status::invalid_argument(refused.to_string()) + }; + let severity = Severity::parse(&request.severity).ok_or_else(|| { + Status::invalid_argument( + "severity must be empty or one of \"info\", \"success\", \"warning\", \"error\"", + ) + })?; + let main = check_text(&request.locale, &request.title, &request.body).map_err(invalid)?; + if request.translations.len() > MAX_TRANSLATIONS { + return Err(Status::invalid_argument(format!( + "at most {MAX_TRANSLATIONS} translations are allowed" + ))); + } + let mut texts = vec![main]; + for translation in &request.translations { + if translation.locale.is_empty() { + return Err(Status::invalid_argument("every translation needs a locale")); + } + let text = check_text(&translation.locale, &translation.title, &translation.body) + .map_err(invalid)?; + if texts + .iter() + .any(|known: &Text| known.locale.eq_ignore_ascii_case(&text.locale)) + { + return Err(Status::invalid_argument( + "each locale may appear once, the main text's included", + )); + } + texts.push(text); + } + + let mut parts: Vec<&str> = vec!["notification", &request.severity]; + for text in &texts { + parts.extend([ + text.locale.as_str(), + text.title.as_str(), + text.body.as_str(), + ]); + } + let hash = request_hash(&parts); + + // Delivery is quick, so the whole decision runs under the mutation lock: a retry that + // races its first call sees its outcome instead of delivering twice. + let _serial = self.mutations.lock.lock().await; + if let Some(original) = self.mutations.replay(&caller, key, hash)? { + return Ok(Response::new(original)); + } + let sink = self + .notifications + .sink() + .ok_or_else(|| Status::unavailable("notifications are not available"))?; + // Permissions are checked again before the call is counted or delivered. + self.guard(context, cap::NOTIFICATIONS_PUBLISH, caller.grant_revision)()?; + if let Err(wait) = self.notifications.admit(owner) { + let mut status = Status::resource_exhausted(format!( + "too many notifications; retry after {} seconds", + wait.as_secs().max(1) + )); + if let Ok(value) = wait.as_millis().to_string().parse() { + status.metadata_mut().insert("retry-after-ms", value); + } + return Err(status); + } + sink.deliver(PluginNotice { + plugin_id, + severity, + texts, + }); + let answer = reply("", 0, MutationOutcome::Applied); + self.mutations.remember(&caller, key, hash, &answer); + Ok(Response::new(answer)) + } +} diff --git a/crates/app/src/plugin_host/resources/observations.rs b/crates/app/src/plugin_host/resources/observations.rs new file mode 100644 index 000000000..b57bf5510 --- /dev/null +++ b/crates/app/src/plugin_host/resources/observations.rs @@ -0,0 +1,1138 @@ +//! Host-validated hardware observations and expiring game-presence state. +//! +//! Both families are sensitive data. Publication is authenticated to the current plugin session; +//! cross-plugin reads use the shared-data broker's exact dataset/field policy. Neither route +//! starts a collector, publishes online status, nor makes a process/backup decision. + +use super::super::shared_data::{MAX_PAGE_SIZE, Publication, PublisherMetadata, QueryRequest}; +use super::super::sharing_policy::{Delivery, SharingClass}; +use super::*; +use futures_util::Stream; +use std::pin::Pin; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::time::Duration; +use tonic::{Request, Response, Status}; + +const COMPUTER_DATASET: &str = "computer.hardware.observations.v1"; +const PRESENCE_DATASET: &str = "game.presence.v1"; +const COMPUTER_PROJECTION: &str = "hardware.v1"; +const PRESENCE_PROJECTION: &str = "presence.v1"; +const PRESENCE_CLEAR_SCHEMA: &str = "game.presence.v1.clear"; +const HOST_COMPUTER_CONTEXT: &str = "active-host"; +const MAX_TEXT: usize = 512; +const MAX_FIELDS: usize = 256; +const MAX_STRUCT_DEPTH: usize = 8; +const MAX_RECORD_BYTES: usize = 64 * 1024; +const MAX_PAGE: usize = 200; +const MAX_PRESENCE_TTL_SECONDS: u64 = 300; +const CLEAR_TOMBSTONE_TTL_SECONDS: u64 = 600; +const WATCH_QUEUE: usize = 32; +const WATCH_RECHECK: Duration = Duration::from_secs(5); + +static NEXT_OBSERVATION_SEQUENCE: AtomicU64 = AtomicU64::new(0); + +type WatchStream = Pin> + Send + 'static>>; + +pub const COMPUTER_SERVED: &[Served] = &[ + Served::new( + "List", + cap::COMPUTER_HARDWARE_READ, + true, + "own reports or exact sensitive source/recipient field grants", + ), + Served::new( + "Get", + cap::COMPUTER_HARDWARE_READ, + false, + "own report or exact sensitive source/recipient field grants", + ), + Served::new( + "Watch", + cap::COMPUTER_HARDWARE_READ, + false, + "own reports or exact sensitive source/recipient live field grants", + ), +]; + +pub const PRESENCE_SERVED: &[Served] = &[ + Served::new( + "List", + cap::GAME_PRESENCE_READ, + true, + "own presence or exact sensitive source/recipient field grants", + ), + Served::new( + "Get", + cap::GAME_PRESENCE_READ, + false, + "own presence or exact sensitive source/recipient field grants", + ), + Served::new( + "Watch", + cap::GAME_PRESENCE_READ, + false, + "own presence or exact sensitive source/recipient live field grants", + ), +]; + +fn broker_status(error: BrokerError) -> Status { + match error { + BrokerError::StaleCursor | BrokerError::StaleSubscription => { + Status::failed_precondition("observation cursor is stale; query again") + } + BrokerError::AuthorizationChanged | BrokerError::Expired => { + Status::failed_precondition("observation authorization changed") + } + BrokerError::RecordTooLarge | BrokerError::QuotaExceeded => { + Status::resource_exhausted("observation capacity exceeded") + } + BrokerError::SequenceConflict(_) => { + Status::aborted("observation sequence is stale; publish again") + } + _ => Status::invalid_argument("invalid observation request"), + } +} + +fn projection(value: &str, expected: &'static str) -> Result<(), Status> { + if value == expected { + Ok(()) + } else { + Err(Status::invalid_argument("unknown observation projection")) + } +} + +fn next_sequence() -> Result { + NEXT_OBSERVATION_SEQUENCE + .try_update(Ordering::Relaxed, Ordering::Relaxed, |current| { + current.checked_add(1) + }) + .map(|previous| previous + 1) + .map_err(|_| Status::resource_exhausted("observation sequence is exhausted")) +} + +fn checked_time(observed_at: i64, now: i64) -> Result<(), Status> { + if observed_at <= 0 || observed_at > now.saturating_add(300) { + Err(Status::invalid_argument( + "observation time is outside the supported range", + )) + } else { + Ok(()) + } +} + +fn safe_field_name(value: &str) -> bool { + !value.is_empty() + && value.len() <= 128 + && value + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-')) + && !value.starts_with('_') +} + +fn private_hardware_identifier(value: &str) -> bool { + let normalized = value + .bytes() + .filter(u8::is_ascii_alphanumeric) + .map(|byte| byte.to_ascii_lowercase()) + .collect::>(); + matches!( + normalized.as_slice(), + b"serial" + | b"serialnumber" + | b"uuid" + | b"machineid" + | b"hardwareid" + | b"deviceid" + | b"mac" + | b"macaddress" + | b"assettag" + | b"servicetag" + | b"uniqueid" + | b"hostid" + ) +} + +fn safe_value(value: &JsonValue, depth: usize, items: &mut usize) -> Result<(), Status> { + if depth > MAX_STRUCT_DEPTH { + return Err(Status::invalid_argument("observation fields are too deep")); + } + *items += 1; + if *items > MAX_FIELDS { + return Err(Status::resource_exhausted( + "observation field limit exceeded", + )); + } + match value { + JsonValue::Object(fields) => { + for (key, value) in fields { + if !safe_field_name(key) || private_hardware_identifier(key) { + return Err(Status::invalid_argument( + "observation contains an unsafe field name", + )); + } + safe_value(value, depth + 1, items)?; + } + } + JsonValue::Array(values) => { + if values.len() > MAX_FIELDS { + return Err(Status::resource_exhausted("observation array is too large")); + } + for value in values { + safe_value(value, depth + 1, items)?; + } + } + JsonValue::String(text) if text.len() > MAX_TEXT || text.chars().any(char::is_control) => { + return Err(Status::invalid_argument("observation text is invalid")); + } + JsonValue::Number(number) if number.as_f64().is_none_or(|value| !value.is_finite()) => { + return Err(Status::invalid_argument("observation number is invalid")); + } + _ => {} + } + Ok(()) +} + +fn flatten(prefix: &str, value: &JsonValue, output: &mut JsonMap) { + if let JsonValue::Object(fields) = value { + for (key, value) in fields { + let path = if prefix.is_empty() { + key.clone() + } else { + format!("{prefix}.{key}") + }; + flatten(&path, value, output); + } + } else { + output.insert(prefix.to_owned(), value.clone()); + } +} + +fn checked_struct( + value: Option<&prost_types::Struct>, + root: &str, +) -> Result, Status> { + let value = value.ok_or_else(|| Status::invalid_argument("observations are required"))?; + let json = JsonValue::Object(super::struct_to_json(value)?); + let mut items = 0; + safe_value(&json, 0, &mut items)?; + let encoded = serde_json::to_vec(&json) + .map_err(|_| Status::invalid_argument("observations are invalid"))?; + if encoded.len() > MAX_RECORD_BYTES { + return Err(Status::resource_exhausted( + "observation payload is too large", + )); + } + let mut flattened = JsonMap::new(); + flatten(root, &json, &mut flattened); + Ok(flattened) +} + +fn nested_fields(fields: &JsonMap, prefix: &str) -> JsonMap { + fn insert_path(root: &mut JsonMap, parts: &[&str], value: JsonValue) { + if let Some((head, tail)) = parts.split_first() { + if tail.is_empty() { + root.insert((*head).to_owned(), value); + } else { + let child = root + .entry((*head).to_owned()) + .or_insert_with(|| JsonValue::Object(JsonMap::new())); + if let JsonValue::Object(child) = child { + insert_path(child, tail, value); + } + } + } + } + let mut result = JsonMap::new(); + for (path, value) in fields { + let Some(suffix) = path.strip_prefix(prefix) else { + continue; + }; + let Some(suffix) = suffix.strip_prefix('.') else { + continue; + }; + let parts = suffix.split('.').collect::>(); + insert_path(&mut result, &parts, value.clone()); + } + result +} + +fn plugin_id(record: &ProjectedRecord) -> String { + record.provenance().source.plugin_id.clone() +} + +fn computer_report(record: &ProjectedRecord) -> ComputerReport { + let fields = record.fields(); + ComputerReport { + record_id: record.record_id().to_owned(), + computer_context_id: HOST_COMPUTER_CONTEXT.into(), + owner_plugin_id: plugin_id(record), + schema_id: record.schema().0.to_owned(), + schema_version: record.schema().1, + typed_observations: Some(super::json_to_struct(&nested_fields( + fields, + "observations", + ))), + approved_extension: Some(prost_types::Struct::default()), + observed_at: record.observed_at(), + revision: record.revision(), + } +} + +fn presence_record(record: &ProjectedRecord) -> PresenceRecord { + let fields = record.fields(); + let (game_id, session_id) = record + .resource_id() + .split_once('/') + .map(|(game_id, session_id)| (game_id.to_owned(), session_id.to_owned())) + .unwrap_or_default(); + PresenceRecord { + presence_id: record.record_id().to_owned(), + game_id, + session_id, + owner_plugin_id: plugin_id(record), + sequence: record.revision(), + observed_at: record.observed_at(), + expires_at: record.expires_at().unwrap_or_default(), + approved_details: Some(super::json_to_struct(&nested_fields(fields, "details"))), + revision: record.revision(), + } +} + +fn matches_presence(record: &ProjectedRecord, game_id: &str, session_id: &str) -> bool { + let Some((record_game_id, record_session_id)) = record.resource_id().split_once('/') else { + return false; + }; + (game_id.is_empty() || record_game_id == game_id) + && (session_id.is_empty() || record_session_id == session_id) +} + +fn is_cleared(record: &ProjectedRecord) -> bool { + record.schema().0 == PRESENCE_CLEAR_SCHEMA +} + +fn publication_metadata(caller: &ResourceCaller) -> PublisherMetadata { + PublisherMetadata { + declared_developer: caller.declared_developer.clone(), + origin: caller.origin.clone(), + package_version: caller.package_version.clone(), + package_digest: caller.package_digest.clone(), + } +} + +fn observation_game_id(text: &str) -> Result { + if text.len() > 20 || text.is_empty() || !text.bytes().all(|byte| byte.is_ascii_digit()) { + return Err(Status::invalid_argument( + "game_id must be a GameNode game id", + )); + } + let parsed = text + .parse::() + .ok() + .filter(|id| *id > 0) + .ok_or_else(|| Status::invalid_argument("game_id must be a GameNode game id"))?; + Ok(parsed.to_string()) +} + +fn presence_session_id(text: &str) -> Result<(), Status> { + if text.is_empty() + || text.len() > 128 + || !text + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-' | b'.' | b':')) + { + return Err(Status::invalid_argument("session_id is invalid")); + } + Ok(()) +} + +fn presence_resource(game_id: &str, session_id: &str) -> String { + format!("{game_id}/{session_id}") +} + +impl ResourceApi { + pub(super) async fn publish_hardware( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + let mutation = request + .mutation + .as_ref() + .ok_or_else(|| Status::invalid_argument("mutation is required"))?; + let context = mutation + .context + .clone() + .ok_or_else(|| Status::invalid_argument("context is required"))?; + let caller = self + .providers + .authorize_resource(Some(&context), cap::COMPUTER_HARDWARE_PUBLISH)?; + let owner = Self::data_identity(&caller)?; + if !request.computer_id.is_empty() { + return Err(Status::invalid_argument( + "computer context is host assigned; omit computer_id", + )); + } + if request.schema_id.is_empty() + || request.schema_id.len() > 256 + || !request + .schema_id + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-')) + || request.schema_version == 0 + { + return Err(Status::invalid_argument("invalid hardware schema")); + } + let now = super::unix_now()?; + checked_time(request.observed_at, now)?; + let fields = checked_struct(request.observations.as_ref(), "observations")?; + if fields.is_empty() { + return Err(Status::invalid_argument("observations are empty")); + } + let material = serde_json::to_string(&fields) + .map_err(|_| Status::invalid_argument("observations are invalid"))?; + let key = mutation_key(mutation)?.to_owned(); + let hash = mutations::request_hash(&[ + "computer-hardware", + &request.schema_id, + &request.schema_version.to_string(), + &request.observed_at.to_string(), + &mutation.expected_revision.to_string(), + &material, + ]); + let _serial = self.mutations.lock.lock().await; + if let Some(original) = self.mutations.replay(&caller, &key, hash)? { + return Ok(Response::new(ReportMutationReply { + report_id: original.resource_id, + revision: original.revision, + outcome: original.outcome, + ..Default::default() + })); + } + let fresh = self + .providers + .authorize_resource(Some(&context), cap::COMPUTER_HARDWARE_PUBLISH)?; + if fresh.grant_revision != caller.grant_revision { + return Err(Status::failed_precondition( + "permissions changed; retry the hardware report", + )); + } + let receipt = self + .data + .publish( + Publication { + owner, + dataset_id: COMPUTER_DATASET.into(), + category: None, + class: SharingClass::Sensitive, + schema_id: request.schema_id, + schema_version: request.schema_version, + fields, + opaque_payload: Vec::new(), + resource_id: format!("{HOST_COMPUTER_CONTEXT}/{}", caller.profile_epoch), + observed_at: request.observed_at, + sequence: 0, + source_observation_id: String::new(), + session_id: Some(caller.session_id.clone()), + publisher: None, + expires_at: None, + }, + now, + ) + .map_err(broker_status)?; + let outcome = if receipt.duplicate { + MutationOutcome::AlreadyApplied + } else { + MutationOutcome::Applied + }; + self.mutations.remember( + &caller, + &key, + hash, + &mutations::reply(&receipt.record_id, receipt.revision, outcome), + ); + Ok(Response::new(ReportMutationReply { + report_id: receipt.record_id, + revision: receipt.revision, + outcome: outcome as i32, + ..Default::default() + })) + } + + pub(super) async fn publish_presence( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + let mutation = request + .mutation + .as_ref() + .ok_or_else(|| Status::invalid_argument("mutation is required"))?; + let context = mutation + .context + .clone() + .ok_or_else(|| Status::invalid_argument("context is required"))?; + let caller = self + .providers + .authorize_resource(Some(&context), cap::GAME_PRESENCE_PUBLISH)?; + let owner = Self::data_identity(&caller)?; + let game_id = observation_game_id(&request.game_id)?; + presence_session_id(&request.session_id)?; + if request.ttl_seconds == 0 || request.ttl_seconds > MAX_PRESENCE_TTL_SECONDS { + return Err(Status::invalid_argument( + "presence TTL must be 1 to 300 seconds", + )); + } + let now = super::unix_now()?; + let fields = checked_struct(request.details.as_ref(), "details")?; + let material = serde_json::to_string(&fields) + .map_err(|_| Status::invalid_argument("presence details are invalid"))?; + let key = mutation_key(mutation)?.to_owned(); + let hash = mutations::request_hash(&[ + "game-presence-publish", + &game_id, + &request.session_id, + &request.ttl_seconds.to_string(), + &mutation.expected_revision.to_string(), + &material, + ]); + let _serial = self.mutations.lock.lock().await; + if let Some(original) = self.mutations.replay(&caller, &key, hash)? { + return Ok(Response::new(ReportMutationReply { + report_id: original.resource_id, + revision: original.revision, + outcome: original.outcome, + ..Default::default() + })); + } + let fresh = self + .providers + .authorize_resource(Some(&context), cap::GAME_PRESENCE_PUBLISH)?; + if fresh.grant_revision != caller.grant_revision { + return Err(Status::failed_precondition( + "permissions changed; retry the presence report", + )); + } + let receipt = self + .data + .publish_replacing( + Publication { + owner, + dataset_id: PRESENCE_DATASET.into(), + category: None, + class: SharingClass::Sensitive, + schema_id: PRESENCE_DATASET.into(), + schema_version: 1, + fields, + opaque_payload: Vec::new(), + resource_id: presence_resource(&game_id, &request.session_id), + observed_at: now, + sequence: next_sequence()?, + source_observation_id: key.clone(), + session_id: Some(caller.session_id.clone()), + publisher: Some(publication_metadata(&caller)), + expires_at: Some(now.saturating_add(request.ttl_seconds as i64)), + }, + now, + ) + .map_err(broker_status)?; + let outcome = if receipt.duplicate { + MutationOutcome::AlreadyApplied + } else { + MutationOutcome::Applied + }; + self.mutations.remember( + &caller, + &key, + hash, + &mutations::reply(&receipt.record_id, receipt.revision, outcome), + ); + Ok(Response::new(ReportMutationReply { + report_id: receipt.record_id, + revision: receipt.revision, + outcome: outcome as i32, + ..Default::default() + })) + } + + pub(super) async fn clear_presence( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + let mutation = request + .mutation + .as_ref() + .ok_or_else(|| Status::invalid_argument("mutation is required"))?; + let context = mutation + .context + .clone() + .ok_or_else(|| Status::invalid_argument("context is required"))?; + let caller = self + .providers + .authorize_resource(Some(&context), cap::GAME_PRESENCE_PUBLISH)?; + let owner = Self::data_identity(&caller)?; + let game_id = observation_game_id(&request.game_id)?; + presence_session_id(&request.session_id)?; + let now = super::unix_now()?; + let key = mutation_key(mutation)?.to_owned(); + let hash = mutations::request_hash(&[ + "game-presence-clear", + &game_id, + &request.session_id, + &mutation.expected_revision.to_string(), + ]); + let _serial = self.mutations.lock.lock().await; + if let Some(original) = self.mutations.replay(&caller, &key, hash)? { + return Ok(Response::new(MutationReply { + resource_id: original.resource_id, + revision: original.revision, + outcome: original.outcome, + })); + } + let fresh = self + .providers + .authorize_resource(Some(&context), cap::GAME_PRESENCE_PUBLISH)?; + if fresh.grant_revision != caller.grant_revision { + return Err(Status::failed_precondition( + "permissions changed; retry the presence clear", + )); + } + let current = self + .data + .query_data( + QueryRequest { + caller: owner.clone(), + dataset_id: PRESENCE_DATASET.into(), + record_id: None, + category: None, + selector: None, + delivery: Delivery::History, + page_size: MAX_PAGE_SIZE, + cursor: None, + }, + self.shared_authorizer.as_ref(), + now, + ) + .map_err(broker_status)?; + let resource_id = presence_resource(&game_id, &request.session_id); + let mut fields = current + .records + .iter() + .find(|record| record.resource_id() == resource_id) + .map(|record| { + record + .fields() + .keys() + .filter(|field| field.starts_with("details.")) + .map(|field| (field.clone(), JsonValue::Null)) + .collect::>() + }) + .unwrap_or_default(); + if fields.is_empty() { + // A host-owned clear marker is exposed only if the recipient explicitly selects it. + fields.insert("details.cleared".into(), JsonValue::Bool(true)); + } + let receipt = self + .data + .publish_replacing( + Publication { + owner, + dataset_id: PRESENCE_DATASET.into(), + category: None, + class: SharingClass::Sensitive, + schema_id: PRESENCE_CLEAR_SCHEMA.into(), + schema_version: 1, + fields, + opaque_payload: Vec::new(), + resource_id, + observed_at: now, + sequence: next_sequence()?, + source_observation_id: key.clone(), + session_id: Some(caller.session_id.clone()), + publisher: Some(publication_metadata(&caller)), + expires_at: Some(now.saturating_add(CLEAR_TOMBSTONE_TTL_SECONDS as i64)), + }, + now, + ) + .map_err(broker_status)?; + let outcome = if receipt.duplicate { + MutationOutcome::AlreadyApplied + } else { + MutationOutcome::Applied + }; + self.mutations.remember( + &caller, + &key, + hash, + &mutations::reply(&receipt.record_id, receipt.revision, outcome), + ); + Ok(Response::new(MutationReply { + resource_id: receipt.record_id, + revision: receipt.revision, + outcome: outcome as i32, + })) + } + + async fn list_computers( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + let page = request + .page + .ok_or_else(|| Status::invalid_argument("page is required"))?; + let context = page + .context + .clone() + .ok_or_else(|| Status::invalid_argument("context is required"))?; + let caller = self + .providers + .authorize_resource(Some(&context), cap::COMPUTER_HARDWARE_READ)?; + let identity = Self::data_identity(&caller)?; + projection(&request.projection_id, COMPUTER_PROJECTION)?; + if !request.computer_context_id.is_empty() + && request.computer_context_id != HOST_COMPUTER_CONTEXT + { + return Err(Status::not_found("computer context not found")); + } + let cursor = self.take_data_cursor(&page.cursor, &caller.session_id)?; + let size = if page.page_size == 0 { + DEFAULT_PAGE_SIZE + } else { + (page.page_size as usize).min(MAX_PAGE) + }; + let result = self + .data + .query_data( + QueryRequest { + caller: identity, + dataset_id: COMPUTER_DATASET.into(), + record_id: None, + category: None, + selector: None, + delivery: Delivery::History, + page_size: size.min(MAX_PAGE_SIZE), + cursor, + }, + self.shared_authorizer.as_ref(), + super::unix_now()?, + ) + .map_err(broker_status)?; + let reports = result.records.iter().map(computer_report).collect(); + let next_cursor = match result.next_cursor { + Some(cursor) => self.issue_data_cursor(&caller.session_id, cursor)?, + None => String::new(), + }; + Ok(Response::new(ComputerListReply { + reports, + next_cursor, + revision: result.revision, + })) + } + + async fn get_computer( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + if request.computer_record_id.is_empty() || request.computer_record_id.len() > 256 { + return Err(Status::invalid_argument("computer_record_id is required")); + } + projection(&request.projection_id, COMPUTER_PROJECTION)?; + let context = request + .context + .as_ref() + .ok_or_else(|| Status::invalid_argument("context is required"))?; + let caller = self + .providers + .authorize_resource(Some(context), cap::COMPUTER_HARDWARE_READ)?; + let result = self + .data + .query_data( + QueryRequest { + caller: Self::data_identity(&caller)?, + dataset_id: COMPUTER_DATASET.into(), + record_id: Some(request.computer_record_id.clone()), + category: None, + selector: None, + delivery: Delivery::Query, + page_size: 1, + cursor: None, + }, + self.shared_authorizer.as_ref(), + super::unix_now()?, + ) + .map_err(broker_status)?; + let record = result + .records + .iter() + .find(|record| record.record_id() == request.computer_record_id) + .ok_or_else(|| Status::not_found("computer report not found"))?; + Ok(Response::new(ComputerGetReply { + report: Some(computer_report(record)), + })) + } + + async fn watch_computers( + &self, + request: Request, + ) -> Result>, Status> { + let request = request.into_inner(); + if !request.computer_context_id.is_empty() + && request.computer_context_id != HOST_COMPUTER_CONTEXT + { + return Err(Status::not_found("computer context not found")); + } + projection(&request.projection_id, COMPUTER_PROJECTION)?; + let context = request + .context + .clone() + .ok_or_else(|| Status::invalid_argument("context is required"))?; + let caller = self + .providers + .authorize_resource(Some(&context), cap::COMPUTER_HARDWARE_READ)?; + let subscription = self + .data + .subscribe( + QueryRequest { + caller: Self::data_identity(&caller)?, + dataset_id: COMPUTER_DATASET.into(), + record_id: None, + category: None, + selector: None, + delivery: Delivery::Live, + page_size: DEFAULT_PAGE_SIZE, + cursor: None, + }, + request.after_revision, + WATCH_QUEUE, + self.shared_authorizer.clone(), + ) + .map_err(broker_status)?; + let slot = self.watch_slot(&caller.session_id)?; + let providers = self.providers.clone(); + let grant_revision = caller.grant_revision; + let context = request.context; + let stream = futures_util::stream::unfold( + Some((subscription, slot, providers, context)), + move |state| async move { + let (subscription, slot, providers, context) = state?; + loop { + let received = tokio::time::timeout( + WATCH_RECHECK, + subscription.recv(super::unix_now().unwrap_or(0)), + ) + .await; + match providers + .authorize_resource(context.as_ref(), cap::COMPUTER_HARDWARE_READ) + { + Ok(active) if active.grant_revision == grant_revision => {} + Ok(_) => { + return Some(( + Err(Status::failed_precondition( + "permissions changed; watch again", + )), + None, + )); + } + Err(error) => return Some((Err(error), None)), + } + let event = match received { + Ok(Ok(Some(record))) => record, + Ok(Ok(None)) | Err(_) => continue, + Ok(Err(SubscriptionEnd::Revoked)) => { + return Some(( + Err(Status::failed_precondition( + "hardware sharing changed; watch again", + )), + None, + )); + } + Ok(Err(SubscriptionEnd::FellBehind)) => { + return Some(( + Err(Status::resource_exhausted( + "hardware watch fell behind; list again", + )), + None, + )); + } + }; + let value = ComputerEvent { + revision: event.revision(), + event_type: "published".into(), + report: Some(computer_report(&event)), + }; + return Some((Ok(value), Some((subscription, slot, providers, context)))); + } + }, + ); + Ok(Response::new(Box::pin(stream))) + } + + async fn list_presence( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + let page = request + .page + .ok_or_else(|| Status::invalid_argument("page is required"))?; + let context = page + .context + .clone() + .ok_or_else(|| Status::invalid_argument("context is required"))?; + let caller = self + .providers + .authorize_resource(Some(&context), cap::GAME_PRESENCE_READ)?; + let identity = Self::data_identity(&caller)?; + projection(&request.projection_id, PRESENCE_PROJECTION)?; + let game = if request.game_id.is_empty() { + String::new() + } else { + observation_game_id(&request.game_id)? + }; + if !request.session_id.is_empty() { + presence_session_id(&request.session_id)?; + } + let cursor = self.take_data_cursor(&page.cursor, &caller.session_id)?; + let size = if page.page_size == 0 { + DEFAULT_PAGE_SIZE + } else { + (page.page_size as usize).min(MAX_PAGE) + }; + let result = self + .data + .query_data( + QueryRequest { + caller: identity, + dataset_id: PRESENCE_DATASET.into(), + record_id: None, + category: None, + selector: None, + delivery: Delivery::History, + page_size: size.min(MAX_PAGE_SIZE), + cursor, + }, + self.shared_authorizer.as_ref(), + super::unix_now()?, + ) + .map_err(broker_status)?; + let records = result + .records + .iter() + .filter(|record| { + !is_cleared(record) && matches_presence(record, &game, &request.session_id) + }) + .map(presence_record) + .collect(); + let next_cursor = match result.next_cursor { + Some(cursor) => self.issue_data_cursor(&caller.session_id, cursor)?, + None => String::new(), + }; + Ok(Response::new(PresenceListReply { + records, + next_cursor, + revision: result.revision, + })) + } + + async fn get_presence( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + if request.presence_id.is_empty() || request.presence_id.len() > 256 { + return Err(Status::invalid_argument("presence_id is required")); + } + projection(&request.projection_id, PRESENCE_PROJECTION)?; + let context = request + .context + .as_ref() + .ok_or_else(|| Status::invalid_argument("context is required"))?; + let caller = self + .providers + .authorize_resource(Some(context), cap::GAME_PRESENCE_READ)?; + let result = self + .data + .query_data( + QueryRequest { + caller: Self::data_identity(&caller)?, + dataset_id: PRESENCE_DATASET.into(), + record_id: Some(request.presence_id.clone()), + category: None, + selector: None, + delivery: Delivery::Query, + page_size: 1, + cursor: None, + }, + self.shared_authorizer.as_ref(), + super::unix_now()?, + ) + .map_err(broker_status)?; + let record = result + .records + .iter() + .find(|record| record.record_id() == request.presence_id && !is_cleared(record)) + .ok_or_else(|| Status::not_found("presence record not found"))?; + Ok(Response::new(PresenceGetReply { + record: Some(presence_record(record)), + })) + } + + async fn watch_presence( + &self, + request: Request, + ) -> Result>, Status> { + let request = request.into_inner(); + projection(&request.projection_id, PRESENCE_PROJECTION)?; + let game = if request.game_id.is_empty() { + String::new() + } else { + observation_game_id(&request.game_id)? + }; + if !request.session_id.is_empty() { + presence_session_id(&request.session_id)?; + } + let context = request + .context + .clone() + .ok_or_else(|| Status::invalid_argument("context is required"))?; + let caller = self + .providers + .authorize_resource(Some(&context), cap::GAME_PRESENCE_READ)?; + let subscription = self + .data + .subscribe( + QueryRequest { + caller: Self::data_identity(&caller)?, + dataset_id: PRESENCE_DATASET.into(), + record_id: None, + category: None, + selector: None, + delivery: Delivery::Live, + page_size: DEFAULT_PAGE_SIZE, + cursor: None, + }, + request.after_sequence, + WATCH_QUEUE, + self.shared_authorizer.clone(), + ) + .map_err(broker_status)?; + let slot = self.watch_slot(&caller.session_id)?; + let providers = self.providers.clone(); + let grant_revision = caller.grant_revision; + let context = request.context; + let session_id = request.session_id; + let stream = futures_util::stream::unfold( + Some((subscription, slot, providers, context, game, session_id)), + move |state| async move { + let (subscription, slot, providers, context, game, session_id) = state?; + loop { + let received = tokio::time::timeout( + WATCH_RECHECK, + subscription.recv(super::unix_now().unwrap_or(0)), + ) + .await; + match providers.authorize_resource(context.as_ref(), cap::GAME_PRESENCE_READ) { + Ok(active) if active.grant_revision == grant_revision => {} + Ok(_) => { + return Some(( + Err(Status::failed_precondition( + "permissions changed; watch again", + )), + None, + )); + } + Err(error) => return Some((Err(error), None)), + } + let event = match received { + Ok(Ok(Some(record))) => record, + Ok(Ok(None)) | Err(_) => continue, + Ok(Err(SubscriptionEnd::Revoked)) => { + return Some(( + Err(Status::failed_precondition( + "presence sharing changed; watch again", + )), + None, + )); + } + Ok(Err(SubscriptionEnd::FellBehind)) => { + return Some(( + Err(Status::resource_exhausted( + "presence watch fell behind; list again", + )), + None, + )); + } + }; + if !matches_presence(&event, &game, &session_id) { + continue; + } + let cleared = is_cleared(&event); + let value = PresenceEvent { + sequence: event.revision(), + event_type: if cleared { "cleared" } else { "published" }.into(), + record: Some(presence_record(&event)), + }; + return Some(( + Ok(value), + Some((subscription, slot, providers, context, game, session_id)), + )); + } + }, + ); + Ok(Response::new(Box::pin(stream))) + } +} + +#[tonic::async_trait] +impl computer_server::Computer for ResourceApi { + type WatchStream = WatchStream; + + async fn list( + &self, + request: Request, + ) -> Result, Status> { + self.list_computers(request).await + } + + async fn get( + &self, + request: Request, + ) -> Result, Status> { + self.get_computer(request).await + } + + async fn watch( + &self, + request: Request, + ) -> Result, Status> { + self.watch_computers(request).await + } +} + +#[tonic::async_trait] +impl game_presence_server::GamePresence for ResourceApi { + type WatchStream = WatchStream; + + async fn list( + &self, + request: Request, + ) -> Result, Status> { + self.list_presence(request).await + } + + async fn get( + &self, + request: Request, + ) -> Result, Status> { + self.get_presence(request).await + } + + async fn watch( + &self, + request: Request, + ) -> Result, Status> { + self.watch_presence(request).await + } +} diff --git a/crates/app/src/plugin_host/resources/performance.rs b/crates/app/src/plugin_host/resources/performance.rs new file mode 100644 index 000000000..37b7dde12 --- /dev/null +++ b/crates/app/src/plugin_host/resources/performance.rs @@ -0,0 +1,1572 @@ +//! Bounded plugin-produced game-performance history. The host validates and retains samples but +//! starts no collector and does not infer process ownership from reported metrics. + +use super::super::shared_data::{MAX_PAGE_SIZE, Publication, PublisherMetadata, QueryRequest}; +use super::super::sharing_policy::{Delivery, SharingClass}; +use super::*; +use futures_util::Stream; +use gamenode_plugin_protocol::prost::Message; +use serde_json::{Map as JsonMap, Value as JsonValue, json}; +use sha2::{Digest, Sha256}; +use std::pin::Pin; +use std::time::Duration; +use tonic::{Request, Response, Status}; + +const DATASET: &str = "game.performance.history.v1"; +const PROJECTION: &str = "performance.v1"; +const HOST_COMPUTER_CONTEXT: &str = "active-host"; +const MAX_SERIES_ID: usize = 128; +const MAX_TEXT: usize = 256; +const MAX_BATCH_SAMPLES: usize = 1000; +const MAX_BATCH_BYTES: usize = 1024 * 1024; +const MAX_SERIES_BYTES: usize = 1024 * 1024; +const MIN_SAMPLE_INTERVAL_MS: u32 = 100; +const MAX_SAMPLE_INTERVAL_MS: u32 = 60_000; +const MAX_SAMPLE_WINDOW_MS: u32 = 600_000; +const MAX_FPS: f64 = 10_000.0; +const MAX_PAGE: usize = 200; +const WATCH_QUEUE: usize = 32; +const WATCH_RECHECK: Duration = Duration::from_secs(5); +const BATCH_INTERVAL: Duration = Duration::from_secs(1); +const CURSOR_TTL: Duration = Duration::from_secs(5 * 60); +const MAX_CURSORS: usize = 4096; + +type WatchStream = Pin> + Send + 'static>>; + +pub(super) struct CursorEntry { + session_id: String, + owner: super::super::grants::PluginIdentity, + scope_hash: [u8; 32], + broker_revision: u64, + policy_revision: u64, + after_sequence: u64, + expires_at: Instant, +} + +pub const SERVED: &[Served] = &[ + Served::new( + "List", + cap::GAME_PERFORMANCE_READ, + true, + "own session-retained series or explicitly selected common category/records", + ), + Served::new( + "Get", + cap::GAME_PERFORMANCE_READ, + false, + "own series or explicitly selected common category/record", + ), + Served::new( + "Watch", + cap::GAME_PERFORMANCE_READ, + false, + "own session-retained series or explicitly selected common category/records", + ), + Served::new( + "QuerySeries", + cap::GAME_PERFORMANCE_READ, + true, + "retained samples projected by current sharing policy", + ), + Served::new( + "Aggregate", + cap::GAME_PERFORMANCE_READ, + false, + "aggregates only available retained samples", + ), +]; + +fn broker_status(error: BrokerError) -> Status { + match error { + BrokerError::StaleCursor | BrokerError::StaleSubscription => { + Status::failed_precondition("performance cursor is stale; query again") + } + BrokerError::AuthorizationChanged | BrokerError::Expired => { + Status::failed_precondition("performance authorization changed") + } + BrokerError::RecordTooLarge | BrokerError::QuotaExceeded => { + Status::resource_exhausted("performance retention capacity is exhausted") + } + BrokerError::SequenceConflict(_) => { + Status::aborted("performance sample sequence is duplicate or out of order") + } + _ => Status::invalid_argument("invalid performance request"), + } +} + +fn validate_projection(value: &str) -> Result<(), Status> { + if value == PROJECTION { + Ok(()) + } else { + Err(Status::invalid_argument("unknown performance projection")) + } +} + +fn valid_identifier(value: &str, max: usize) -> bool { + !value.is_empty() + && value.len() <= max + && value + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-' | b'.' | b':')) + && !value.starts_with('.') + && !value.ends_with('.') + && !value.contains("..") +} + +fn valid_text(value: &str, required: bool) -> bool { + value.len() <= MAX_TEXT + && (!required || !value.trim().is_empty()) + && !value.chars().any(char::is_control) +} + +fn series_resource_id(owner: &super::super::grants::PluginIdentity, series_id: &str) -> String { + let mut digest = Sha256::new(); + for part in [ + owner.plugin_id.as_bytes(), + owner.publisher_fingerprint.as_bytes(), + owner.profile_id.as_bytes(), + series_id.as_bytes(), + ] { + digest.update((part.len() as u64).to_be_bytes()); + digest.update(part); + } + let mut token = String::from("performance-"); + for byte in digest.finalize() { + use std::fmt::Write as _; + let _ = write!(token, "{byte:02x}"); + } + token +} + +fn owner_key(owner: &super::super::grants::PluginIdentity) -> String { + format!( + "{}:{}:{}", + owner.plugin_id, owner.publisher_fingerprint, owner.profile_id + ) +} + +fn unix_now_millis() -> Result { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_err(|_| Status::internal("system clock is before the Unix epoch"))? + .as_millis() + .try_into() + .map_err(|_| Status::internal("system clock exceeds the supported range")) +} + +fn sample_json(sample: &PerformanceSample) -> JsonValue { + json!({ + "observed_at": sample.observed_at, + "frames_per_second": sample.frames_per_second, + "cpu_percent": sample.cpu_percent, + "memory_bytes": sample.memory_bytes, + "sequence": sample.sequence, + "sampling_window_ms": sample.sampling_window_ms, + "fps_method": sample.fps_method, + "fps_statistic": sample.fps_statistic, + "fps_percentile": sample.fps_percentile, + "frames_per_second_min": sample.frames_per_second_min, + "frames_per_second_max": sample.frames_per_second_max, + "quality": sample.quality, + }) +} + +fn number(value: &JsonValue) -> Result { + value + .as_f64() + .filter(|number| number.is_finite()) + .ok_or_else(|| Status::failed_precondition("stored performance sample is invalid")) +} + +fn unsigned(value: &JsonValue) -> Result { + value + .as_u64() + .ok_or_else(|| Status::failed_precondition("stored performance sample is invalid")) +} + +fn integer(value: &JsonValue) -> Result { + value + .as_i64() + .ok_or_else(|| Status::failed_precondition("stored performance sample is invalid")) +} + +fn proto_sample(value: &JsonValue) -> Result { + let field = |name: &str| { + value + .get(name) + .ok_or_else(|| Status::failed_precondition("stored performance sample is incomplete")) + }; + Ok(PerformanceSample { + observed_at: integer(field("observed_at")?)?, + frames_per_second: number(field("frames_per_second")?)?, + cpu_percent: number(field("cpu_percent")?)?, + memory_bytes: unsigned(field("memory_bytes")?)?, + sequence: unsigned(field("sequence")?)?, + sampling_window_ms: unsigned(field("sampling_window_ms")?)? as u32, + fps_method: integer(field("fps_method")?)? as i32, + fps_statistic: integer(field("fps_statistic")?)? as i32, + fps_percentile: field("fps_percentile")?.as_f64(), + frames_per_second_min: field("frames_per_second_min")?.as_f64(), + frames_per_second_max: field("frames_per_second_max")?.as_f64(), + quality: integer(field("quality")?)? as i32, + }) +} + +fn sample_list(fields: &JsonMap) -> Result, Status> { + let encoded = fields + .get("samples") + .and_then(JsonValue::as_str) + .ok_or_else(|| Status::failed_precondition("stored performance series is invalid"))?; + let decoded: JsonValue = serde_json::from_str(encoded) + .map_err(|_| Status::failed_precondition("stored performance series is invalid"))?; + decoded + .as_array() + .ok_or_else(|| Status::failed_precondition("stored performance series is invalid"))? + .iter() + .map(proto_sample) + .collect() +} + +fn required_string(fields: &JsonMap, name: &str) -> Result { + fields + .get(name) + .and_then(JsonValue::as_str) + .map(str::to_owned) + .ok_or_else(|| Status::failed_precondition("stored performance series is invalid")) +} + +fn required_u32(fields: &JsonMap, name: &str) -> Result { + fields + .get(name) + .and_then(JsonValue::as_u64) + .and_then(|value| u32::try_from(value).ok()) + .ok_or_else(|| Status::failed_precondition("stored performance series is invalid")) +} + +fn required_i32(fields: &JsonMap, name: &str) -> Result { + fields + .get(name) + .and_then(JsonValue::as_i64) + .and_then(|value| i32::try_from(value).ok()) + .ok_or_else(|| Status::failed_precondition("stored performance series is invalid")) +} + +fn missing_samples(samples: &[PerformanceSample]) -> u64 { + samples + .first() + .map_or(0, |sample| sample.sequence.saturating_sub(1)) + .saturating_add( + samples + .windows(2) + .map(|pair| { + pair[1] + .sequence + .saturating_sub(pair[0].sequence.saturating_add(1)) + }) + .sum::(), + ) +} + +fn record_fields(record: &ProjectedRecord) -> Result<&JsonMap, Status> { + if record.schema() != (DATASET, 1) { + return Err(Status::failed_precondition( + "stored performance schema is invalid", + )); + } + Ok(record.fields()) +} + +fn series(record: &ProjectedRecord) -> Result { + let fields = record_fields(record)?; + let samples = sample_list(fields)?; + let ended_at = fields + .get("ended_at") + .and_then(JsonValue::as_i64) + .unwrap_or(0); + let started_at = samples.first().map_or(0, |sample| sample.observed_at); + let dropped_samples = missing_samples(&samples); + let source_identity = &record.provenance().source; + let owner_plugin_id = source_identity.plugin_id.clone(); + let provenance = record.provenance(); + let provenance_json = serde_json::to_string(&json!({ + "producer_plugin_id": owner_plugin_id, + "publisher_fingerprint": source_identity.publisher_fingerprint, + "package_version": provenance.package_version, + })) + .unwrap_or_default(); + Ok(PerformanceSeries { + series_id: record.resource_id().to_owned(), + record_id: record.record_id().to_owned(), + game_id: required_string(fields, "game_id")?, + installation_id: required_string(fields, "installation_id")?, + computer_context_id: required_string(fields, "computer_context_id")?, + session_id: required_string(fields, "session_id")?, + owner_plugin_id: source_identity.plugin_id.clone(), + samples, + revision: record.revision(), + runtime_id: required_string(fields, "runtime_id")?, + runtime_recipe_revision: required_string(fields, "runtime_recipe_revision")?, + source: required_string(fields, "collector_source")?, + fps_unit: required_string(fields, "fps_unit")?, + cpu_unit: required_string(fields, "cpu_unit")?, + memory_unit: required_string(fields, "memory_unit")?, + tool_name: required_string(fields, "tool_name")?, + tool_version: required_string(fields, "tool_version")?, + sample_interval_ms: required_u32(fields, "sample_interval_ms")?, + cpu_scope: required_i32(fields, "cpu_scope")?, + cpu_normalization: required_i32(fields, "cpu_normalization")?, + memory_kind: required_i32(fields, "memory_kind")?, + memory_source: required_string(fields, "memory_source")?, + started_at, + ended_at, + dropped_samples, + coverage: if dropped_samples == 0 { + "complete" + } else { + "gapped" + } + .into(), + provenance: provenance_json, + }) +} + +fn query_request( + caller: super::super::grants::PluginIdentity, + selector: Option, + delivery: Delivery, + cursor: Option, + page_size: usize, +) -> QueryRequest { + QueryRequest { + caller, + dataset_id: DATASET.into(), + record_id: None, + category: Some(CommonDataCategory::GamePerformanceHistory), + selector, + delivery, + page_size: page_size.min(MAX_PAGE_SIZE), + cursor, + } +} + +fn cursor_scope(parts: &[&str], selector: Option<&CommonDataSelector>) -> [u8; 32] { + let mut digest = Sha256::new(); + for part in parts { + digest.update((part.len() as u64).to_be_bytes()); + digest.update(part.as_bytes()); + } + if let Some(selector) = selector { + digest.update(selector.encode_to_vec()); + } + digest.finalize().into() +} + +fn performance_fields( + request: &PerformanceSamplesRequest, + caller: &ResourceCaller, + owner: &super::super::grants::PluginIdentity, + token: &str, + samples: &[PerformanceSample], + ended_at: Option, + batch_hash: &str, +) -> JsonMap { + let target = request + .mutation + .as_ref() + .and_then(|mutation| mutation.context.as_ref()) + .and_then(|context| context.target_game.as_ref()); + let mut fields = JsonMap::from_iter([ + ("series_id".into(), JsonValue::String(token.into())), + ("game_id".into(), JsonValue::String(request.game_id.clone())), + ( + "installation_id".into(), + JsonValue::String( + target.map_or_else(String::new, |target| target.installation_id.clone()), + ), + ), + ( + "computer_context_id".into(), + JsonValue::String(HOST_COMPUTER_CONTEXT.into()), + ), + ( + "session_id".into(), + JsonValue::String(caller.session_id.clone()), + ), + ( + "producer_plugin_id".into(), + JsonValue::String(owner.plugin_id.clone()), + ), + ( + "runtime_id".into(), + JsonValue::String(request.runtime_id.clone()), + ), + ( + "runtime_recipe_revision".into(), + JsonValue::String(request.runtime_recipe_revision.clone()), + ), + ( + "collector_source".into(), + JsonValue::String(request.source.clone()), + ), + ( + "tool_name".into(), + JsonValue::String(request.tool_name.clone()), + ), + ( + "tool_version".into(), + JsonValue::String(request.tool_version.clone()), + ), + ( + "sample_interval_ms".into(), + JsonValue::Number(request.sample_interval_ms.into()), + ), + ( + "cpu_scope".into(), + JsonValue::Number(request.cpu_scope.into()), + ), + ( + "cpu_normalization".into(), + JsonValue::Number(request.cpu_normalization.into()), + ), + ( + "memory_kind".into(), + JsonValue::Number(request.memory_kind.into()), + ), + ( + "memory_source".into(), + JsonValue::String(request.memory_source.clone()), + ), + ( + "fps_unit".into(), + JsonValue::String(request.fps_unit.clone()), + ), + ( + "cpu_unit".into(), + JsonValue::String(request.cpu_unit.clone()), + ), + ( + "memory_unit".into(), + JsonValue::String(request.memory_unit.clone()), + ), + ( + "samples".into(), + JsonValue::String( + serde_json::to_string(&samples.iter().map(sample_json).collect::>()) + .unwrap_or_default(), + ), + ), + ( + "last_batch_hash".into(), + JsonValue::String(batch_hash.into()), + ), + ]); + if let Some(ended_at) = ended_at { + fields.insert("ended_at".into(), JsonValue::Number(ended_at.into())); + } + fields +} + +impl ResourceApi { + pub(super) async fn publish_performance_samples( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + let mutation = request + .mutation + .as_ref() + .ok_or_else(|| Status::invalid_argument("mutation is required"))?; + let context = mutation + .context + .as_ref() + .ok_or_else(|| Status::invalid_argument("mutation context is required"))?; + let caller = self + .providers + .authorize_resource(Some(context), cap::GAME_PERFORMANCE_PUBLISH)?; + let owner = Self::data_identity(&caller)?; + let now = unix_now_millis()?; + let broker_now = unix_now()?; + let (batch_hash, samples, first_at) = validate_request(&request, now)?; + let token = series_resource_id(&owner, &request.series_id); + let key = super::mutations::mutation_key(mutation)?.to_owned(); + let hash = super::mutations::request_hash(&[ + "game-performance-publish", + &token, + &batch_hash, + &mutation.expected_revision.to_string(), + ]); + let _serial = self.mutations.lock.lock().await; + if let Some(reply) = self.mutations.replay(&caller, &key, hash)? { + return Ok(Response::new(ReportMutationReply { + report_id: reply.resource_id, + revision: reply.revision, + outcome: reply.outcome, + accepted_samples: samples.len() as u32, + retained_from: first_at, + retained_to: samples.last().map_or(first_at, |sample| sample.observed_at), + ..Default::default() + })); + } + let prior = self + .data + .owner_resource(&owner, DATASET, &token, broker_now); + if let Some(prior) = prior.as_ref() { + if prior + .fields + .get("last_batch_hash") + .and_then(JsonValue::as_str) + == Some(batch_hash.as_str()) + { + let reply = super::mutations::reply( + &token, + prior.revision, + MutationOutcome::AlreadyApplied, + ); + self.mutations.remember(&caller, &key, hash, &reply); + return Ok(Response::new(ReportMutationReply { + report_id: token, + revision: prior.revision, + outcome: MutationOutcome::AlreadyApplied as i32, + accepted_samples: samples.len() as u32, + retained_from: first_at, + retained_to: samples.last().map_or(first_at, |sample| sample.observed_at), + ..Default::default() + })); + } + if prior.fields.contains_key("ended_at") { + return Err(Status::failed_precondition("performance series has ended")); + } + let expected = performance_fields(&request, &caller, &owner, &token, &[], None, ""); + if expected.iter().any(|(field, value)| { + field != "samples" + && field != "last_batch_hash" + && prior.fields.get(field) != Some(value) + }) { + return Err(Status::failed_precondition( + "performance series metadata cannot change", + )); + } + let old = sample_list(&prior.fields)?; + let last_sequence = old.last().map_or(0, |sample| sample.sequence); + let last_time = old.last().map_or(0, |sample| sample.observed_at); + if samples + .first() + .is_none_or(|sample| sample.sequence <= last_sequence) + { + return Err(Status::aborted( + "sample sequence is duplicate or out of order", + )); + } + if samples.first().is_some_and(|sample| { + sample.observed_at.saturating_sub(last_time) < i64::from(request.sample_interval_ms) + }) { + return Err(Status::invalid_argument( + "sample rate exceeds the series interval", + )); + } + if mutation.expected_revision != prior.revision { + return Err(Status::aborted("performance series revision changed")); + } + } else if mutation.expected_revision != 0 { + return Err(Status::aborted( + "performance series does not exist at expected revision", + )); + } + let throttle_key = owner_key(&owner); + { + let mut times = self + .performance_batch_times + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + times.retain(|_, at| at.elapsed() < Duration::from_secs(60)); + if times + .get(&throttle_key) + .is_some_and(|at| at.elapsed() < BATCH_INTERVAL) + { + return Ok(Response::new(backpressure_reply( + token, + samples.len(), + 1000, + first_at, + samples.last().map_or(first_at, |sample| sample.observed_at), + ))); + } + times.insert(throttle_key, Instant::now()); + } + let mut all_samples = prior + .as_ref() + .map(|record| sample_list(&record.fields)) + .transpose()? + .unwrap_or_default(); + all_samples.extend(samples.iter().cloned()); + if all_samples.len() > 10_000 + || serde_json::to_vec(&all_samples.iter().map(sample_json).collect::>()) + .map_or(true, |bytes| bytes.len() > MAX_SERIES_BYTES) + { + return Ok(Response::new(backpressure_reply( + token, + samples.len(), + 1000, + first_at, + samples.last().map_or(first_at, |sample| sample.observed_at), + ))); + } + let (fresh, _session_commit) = self + .providers + .authorize_resource_commit(context, cap::GAME_PERFORMANCE_PUBLISH) + .await?; + if fresh.grant_revision != caller.grant_revision || Self::data_identity(&fresh)? != owner { + return Err(Status::failed_precondition( + "plugin identity or permissions changed; retry the performance batch", + )); + } + let mut full_request = request.clone(); + let fields = performance_fields( + &full_request, + &caller, + &owner, + &token, + &all_samples, + None, + &batch_hash, + ); + let retained_from = all_samples + .first() + .map_or(first_at, |sample| sample.observed_at); + let retained_to = all_samples + .last() + .map_or(first_at, |sample| sample.observed_at); + full_request.samples = all_samples; + let fields = fields.into_iter().collect(); + let receipt = match self.data.publish_replacing( + Publication { + owner, + dataset_id: DATASET.into(), + category: Some(CommonDataCategory::GamePerformanceHistory), + class: SharingClass::Common, + schema_id: DATASET.into(), + schema_version: 1, + fields, + opaque_payload: Vec::new(), + resource_id: token.clone(), + observed_at: retained_to, + sequence: full_request + .samples + .last() + .map_or(0, |sample| sample.sequence), + source_observation_id: batch_hash, + session_id: Some(caller.session_id.clone()), + publisher: Some(PublisherMetadata { + declared_developer: caller.declared_developer.clone(), + origin: caller.origin.clone(), + package_version: caller.package_version.clone(), + package_digest: caller.package_digest.clone(), + }), + expires_at: None, + }, + broker_now, + ) { + Ok(receipt) => receipt, + Err(BrokerError::RecordTooLarge | BrokerError::QuotaExceeded) => { + return Ok(Response::new(backpressure_reply( + token, + samples.len(), + 1000, + first_at, + samples.last().map_or(first_at, |sample| sample.observed_at), + ))); + } + Err(error) => return Err(broker_status(error)), + }; + let outcome = if receipt.duplicate { + MutationOutcome::AlreadyApplied + } else { + MutationOutcome::Applied + }; + let reply = super::mutations::reply(&token, receipt.revision, outcome); + self.mutations.remember(&caller, &key, hash, &reply); + Ok(Response::new(ReportMutationReply { + report_id: token, + revision: receipt.revision, + outcome: outcome as i32, + accepted_samples: samples.len() as u32, + retained_from, + retained_to, + ..Default::default() + })) + } + + pub(super) async fn end_performance_series( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + let mutation = request + .mutation + .as_ref() + .ok_or_else(|| Status::invalid_argument("mutation is required"))?; + let context = mutation + .context + .as_ref() + .ok_or_else(|| Status::invalid_argument("mutation context is required"))?; + let caller = self + .providers + .authorize_resource(Some(context), cap::GAME_PERFORMANCE_PUBLISH)?; + let owner = Self::data_identity(&caller)?; + if !valid_identifier(&request.series_id, MAX_SERIES_ID) + || request.ended_at <= 0 + || request.ended_at > unix_now_millis()?.saturating_add(300_000) + { + return Err(Status::invalid_argument("invalid series end")); + } + let token = series_resource_id(&owner, &request.series_id); + let key = super::mutations::mutation_key(mutation)?.to_owned(); + let hash = super::mutations::request_hash(&[ + "game-performance-end", + &token, + &request.ended_at.to_string(), + &request.expected_last_sequence.to_string(), + &mutation.expected_revision.to_string(), + ]); + let _serial = self.mutations.lock.lock().await; + if let Some(reply) = self.mutations.replay(&caller, &key, hash)? { + return Ok(Response::new(reply)); + } + let broker_now = unix_now()?; + let prior = self + .data + .owner_resource(&owner, DATASET, &token, broker_now) + .ok_or_else(|| Status::not_found("performance series not found"))?; + let samples = sample_list(&prior.fields)?; + let last_sequence = samples.last().map_or(0, |sample| sample.sequence); + if request.expected_last_sequence != last_sequence { + return Err(Status::aborted("last sample sequence changed")); + } + if let Some(ended) = prior.fields.get("ended_at").and_then(JsonValue::as_i64) { + if ended == request.ended_at { + let reply = MutationReply { + resource_id: token, + revision: prior.revision, + outcome: MutationOutcome::AlreadyApplied as i32, + }; + self.mutations.remember(&caller, &key, hash, &reply); + return Ok(Response::new(reply)); + } + return Err(Status::failed_precondition( + "performance series already ended", + )); + } + if request.ended_at < samples.last().map_or(0, |sample| sample.observed_at) { + return Err(Status::invalid_argument( + "series end precedes the last sample", + )); + } + if prior.revision != mutation.expected_revision { + return Err(Status::aborted("performance series revision changed")); + } + let (fresh, _session_commit) = self + .providers + .authorize_resource_commit(context, cap::GAME_PERFORMANCE_PUBLISH) + .await?; + if fresh.grant_revision != caller.grant_revision { + return Err(Status::failed_precondition( + "permissions changed; retry the series end", + )); + } + let mut fields = prior.fields; + fields.insert( + "ended_at".into(), + JsonValue::Number(request.ended_at.into()), + ); + let receipt = self + .data + .publish_replacing( + Publication { + owner: owner.clone(), + dataset_id: DATASET.into(), + category: Some(CommonDataCategory::GamePerformanceHistory), + class: SharingClass::Common, + schema_id: DATASET.into(), + schema_version: 1, + fields, + opaque_payload: Vec::new(), + resource_id: token.clone(), + observed_at: request.ended_at, + sequence: last_sequence.saturating_add(1), + source_observation_id: format!("end:{}", request.ended_at), + session_id: Some(caller.session_id.clone()), + publisher: Some(PublisherMetadata { + declared_developer: caller.declared_developer.clone(), + origin: caller.origin.clone(), + package_version: caller.package_version.clone(), + package_digest: caller.package_digest.clone(), + }), + expires_at: None, + }, + broker_now, + ) + .map_err(broker_status)?; + let reply = MutationReply { + resource_id: token, + revision: receipt.revision, + outcome: MutationOutcome::Applied as i32, + }; + self.mutations.remember(&caller, &key, hash, &reply); + Ok(Response::new(reply)) + } + + async fn list_performance( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + let page = request + .page + .as_ref() + .ok_or_else(|| Status::invalid_argument("page is required"))?; + let context = page + .context + .as_ref() + .ok_or_else(|| Status::invalid_argument("context is required"))?; + let caller = self + .providers + .authorize_resource(Some(context), cap::GAME_PERFORMANCE_READ)?; + validate_projection(&request.projection_id)?; + if !request.game_id.is_empty() && !valid_identifier(&request.game_id, MAX_SERIES_ID) { + return Err(Status::invalid_argument("invalid game_id")); + } + if !request.computer_context_id.is_empty() + && request.computer_context_id != HOST_COMPUTER_CONTEXT + { + return Err(Status::not_found("computer context not found")); + } + let identity = Self::data_identity(&caller)?; + let scope = cursor_scope( + &[ + &request.game_id, + &request.computer_context_id, + &request.projection_id, + ], + None, + ); + let cursor = self.take_scoped_data_cursor(&page.cursor, &caller.session_id, Some(scope))?; + let result = self + .data + .query_data( + query_request( + identity, + page.common_data_categories.clone(), + Delivery::History, + cursor, + if page.page_size == 0 { + MAX_PAGE + } else { + (page.page_size as usize).min(MAX_PAGE) + }, + ), + self.shared_authorizer.as_ref(), + unix_now()?, + ) + .map_err(broker_status)?; + let mut records = Vec::new(); + for record in &result.records { + let value = series(record)?; + if (request.game_id.is_empty() || value.game_id == request.game_id) + && (request.computer_context_id.is_empty() + || value.computer_context_id == request.computer_context_id) + { + records.push(value); + } + } + let next_cursor = match result.next_cursor { + Some(cursor) => { + self.issue_scoped_data_cursor(&caller.session_id, cursor, Some(scope))? + } + None => String::new(), + }; + Ok(Response::new(PerformanceListReply { + series: records, + next_cursor, + revision: result.revision, + })) + } + + async fn get_performance( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + if request.series_id.is_empty() || request.series_id.len() > 256 { + return Err(Status::invalid_argument("series_id is required")); + } + let context = request + .context + .as_ref() + .ok_or_else(|| Status::invalid_argument("context is required"))?; + let caller = self + .providers + .authorize_resource(Some(context), cap::GAME_PERFORMANCE_READ)?; + validate_projection(&request.projection_id)?; + let result = self + .data + .query_data_resource( + query_request( + Self::data_identity(&caller)?, + request.common_data_categories, + Delivery::Query, + None, + 1, + ), + &request.series_id, + self.shared_authorizer.as_ref(), + unix_now()?, + ) + .map_err(broker_status)?; + let record = result + .records + .first() + .ok_or_else(|| Status::not_found("performance series not found"))?; + Ok(Response::new(PerformanceGetReply { + series: Some(series(record)?), + })) + } + + async fn query_performance_series( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + if request.series_id.is_empty() + || request.series_id.len() > 256 + || request.from_time < 0 + || request.to_time < 0 + || (request.to_time != 0 && request.from_time > request.to_time) + || request.resolution_ms > MAX_SAMPLE_WINDOW_MS + { + return Err(Status::invalid_argument("invalid performance query range")); + } + let context = request + .context + .as_ref() + .ok_or_else(|| Status::invalid_argument("context is required"))?; + let caller = self + .providers + .authorize_resource(Some(context), cap::GAME_PERFORMANCE_READ)?; + let projection = format!( + "{}:{}:{}:{}", + request.series_id, request.from_time, request.to_time, request.resolution_ms + ); + let scope = cursor_scope(&[&projection], request.common_data_categories.as_ref()); + let page = request.page.as_ref(); + let after = if let Some(page) = page { + self.take_performance_cursor(&page.cursor, &caller, scope)? + } else { + 0 + }; + let result = self + .data + .query_data_resource( + query_request( + Self::data_identity(&caller)?, + request.common_data_categories.clone(), + Delivery::Query, + None, + 1, + ), + &request.series_id, + self.shared_authorizer.as_ref(), + unix_now()?, + ) + .map_err(broker_status)?; + let record = result + .records + .first() + .ok_or_else(|| Status::not_found("performance series not found"))?; + let value = series(record)?; + let page_size = page + .filter(|page| page.page_size > 0) + .map_or(MAX_PAGE, |page| (page.page_size as usize).min(MAX_PAGE)); + let retained = value + .samples + .iter() + .filter(|sample| { + sample.observed_at >= request.from_time + && (request.to_time == 0 || sample.observed_at <= request.to_time) + }) + .cloned() + .collect::>(); + let dropped = missing_samples(&retained); + let downsampled = request.resolution_ms > 0 && retained.len() > 1; + let resolved = if request.resolution_ms == 0 { + retained + } else { + let mut buckets = std::collections::BTreeMap::new(); + for sample in retained { + let bucket = sample.observed_at.saturating_sub(request.from_time) + / i64::from(request.resolution_ms); + buckets.entry(bucket).or_insert(sample); + } + buckets.into_values().collect::>() + }; + let raw = resolved + .iter() + .filter(|sample| sample.sequence > after) + .take(page_size) + .cloned() + .collect::>(); + let next_after = raw.last().map(|sample| sample.sequence); + let has_more = + next_after.is_some_and(|last| resolved.iter().any(|sample| sample.sequence > last)); + let next_cursor = if has_more { + self.issue_performance_cursor(&caller, scope, next_after.unwrap(), result.revision)? + } else { + String::new() + }; + let samples = raw; + Ok(Response::new(PerformanceQuerySeriesReply { + samples, + next_cursor, + coverage: if dropped > 0 { + "gapped" + } else if downsampled { + "downsampled" + } else { + "complete" + } + .into(), + dropped_samples: dropped, + })) + } + + async fn aggregate_performance( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + if request.series_id.is_empty() + || request.from_time < 0 + || request.to_time < 0 + || (request.to_time != 0 && request.from_time > request.to_time) + { + return Err(Status::invalid_argument( + "invalid performance aggregate range", + )); + } + let context = request + .context + .as_ref() + .ok_or_else(|| Status::invalid_argument("context is required"))?; + let caller = self + .providers + .authorize_resource(Some(context), cap::GAME_PERFORMANCE_READ)?; + let result = self + .data + .query_data_resource( + query_request( + Self::data_identity(&caller)?, + request.common_data_categories, + Delivery::Query, + None, + 1, + ), + &request.series_id, + self.shared_authorizer.as_ref(), + unix_now()?, + ) + .map_err(broker_status)?; + let record = result + .records + .first() + .ok_or_else(|| Status::not_found("performance series not found"))?; + let value = series(record)?; + let values = value + .samples + .iter() + .filter(|sample| { + sample.observed_at >= request.from_time + && (request.to_time == 0 || sample.observed_at <= request.to_time) + }) + .map(|sample| match request.metric.as_str() { + "fps" => Ok(sample.frames_per_second), + "cpu_percent" => Ok(sample.cpu_percent), + "memory_bytes" => Ok(sample.memory_bytes as f64), + _ => Err(Status::invalid_argument( + "metric must be fps, cpu_percent, or memory_bytes", + )), + }) + .collect::, _>>()?; + if values.is_empty() { + return Err(Status::not_found( + "no retained samples in the requested range", + )); + } + let aggregate = match request.aggregation.as_str() { + "average" => values.iter().sum::() / values.len() as f64, + "min" => values.iter().copied().fold(f64::INFINITY, f64::min), + "max" => values.iter().copied().fold(f64::NEG_INFINITY, f64::max), + value if value.starts_with('p') => { + let percentile = value[1..] + .parse::() + .ok() + .filter(|value| *value <= 100) + .ok_or_else(|| { + Status::invalid_argument("percentile aggregation must be p0 through p100") + })?; + let mut ordered = values.clone(); + ordered.sort_by(f64::total_cmp); + let index = if percentile == 0 { + 0 + } else { + ((percentile as usize * ordered.len()).div_ceil(100)).saturating_sub(1) + }; + ordered[index] + } + _ => { + return Err(Status::invalid_argument( + "aggregation must be average, min, max, or p0 through p100", + )); + } + }; + Ok(Response::new(PerformanceAggregateReply { + metric: request.metric.clone(), + aggregation: request.aggregation, + value: aggregate, + unit: match request.metric.as_str() { + "fps" => "frames/second", + "cpu_percent" => "percent", + _ => "bytes", + } + .into(), + sample_count: values.len() as u64, + coverage: value.coverage, + provenance: value.provenance, + })) + } + + async fn watch_performance( + &self, + request: Request, + ) -> Result>, Status> { + let request = request.into_inner(); + let context = request + .context + .clone() + .ok_or_else(|| Status::invalid_argument("context is required"))?; + let caller = self + .providers + .authorize_resource(Some(&context), cap::GAME_PERFORMANCE_READ)?; + validate_projection(&request.projection_id)?; + if !request.game_id.is_empty() && !valid_identifier(&request.game_id, MAX_SERIES_ID) { + return Err(Status::invalid_argument("invalid game_id")); + } + if !request.computer_context_id.is_empty() + && request.computer_context_id != HOST_COMPUTER_CONTEXT + { + return Err(Status::not_found("computer context not found")); + } + let subscription = self + .data + .subscribe( + query_request( + Self::data_identity(&caller)?, + request.common_data_categories, + Delivery::Live, + None, + MAX_PAGE, + ), + request.after_sequence, + WATCH_QUEUE, + self.shared_authorizer.clone(), + ) + .map_err(broker_status)?; + let slot = self.watch_slot(&caller.session_id)?; + let providers = self.providers.clone(); + let expected_grant_revision = caller.grant_revision; + let game_filter = request.game_id; + let computer_filter = request.computer_context_id; + let stream = futures_util::stream::unfold( + Some(( + subscription, + slot, + providers, + context, + expected_grant_revision, + )), + move |state| { + let game_filter = game_filter.clone(); + let computer_filter = computer_filter.clone(); + async move { + let (subscription, slot, providers, context, expected_grant_revision) = state?; + loop { + let received = tokio::time::timeout( + WATCH_RECHECK, + subscription.recv(unix_now().unwrap_or(0)), + ) + .await; + match providers + .authorize_resource(Some(&context), cap::GAME_PERFORMANCE_READ) + { + Ok(caller) if caller.grant_revision == expected_grant_revision => {} + Ok(_) => { + return Some(( + Err(Status::failed_precondition( + "permissions changed; watch again", + )), + None, + )); + } + Err(error) => return Some((Err(error), None)), + } + let record = match received { + Ok(Ok(Some(record))) => record, + Ok(Ok(None)) | Err(_) => continue, + Ok(Err(SubscriptionEnd::Revoked)) => { + return Some(( + Err(Status::failed_precondition( + "sharing authorization changed; watch again", + )), + None, + )); + } + Ok(Err(SubscriptionEnd::FellBehind)) => { + return Some(( + Err(Status::resource_exhausted( + "performance watch fell behind; list again", + )), + None, + )); + } + }; + let value = match series(&record) { + Ok(value) => value, + Err(error) => return Some((Err(error), None)), + }; + if (!game_filter.is_empty() && value.game_id != game_filter) + || (!computer_filter.is_empty() + && value.computer_context_id != computer_filter) + { + continue; + } + let event = PerformanceEvent { + sequence: record.revision(), + event_type: if value.ended_at > 0 { + "ended" + } else { + "published" + } + .into(), + series: Some(value), + }; + return Some(( + Ok(event), + Some(( + subscription, + slot, + providers, + context, + expected_grant_revision, + )), + )); + } + } + }, + ); + Ok(Response::new(Box::pin(stream))) + } + + fn take_performance_cursor( + &self, + token: &str, + caller: &ResourceCaller, + scope: [u8; 32], + ) -> Result { + if token.is_empty() { + return Ok(0); + } + let mut cursors = self + .performance_cursors + .lock() + .unwrap_or_else(|p| p.into_inner()); + cursors.retain(|_, value| value.expires_at > Instant::now()); + let entry = cursors + .get(token) + .ok_or_else(|| Status::failed_precondition("performance cursor is stale"))?; + if entry.session_id != caller.session_id + || entry.scope_hash != scope + || entry.owner != Self::data_identity(caller)? + || entry.broker_revision != self.data.revision() + || entry.policy_revision + != self + .shared_authorizer + .revision(&Self::data_identity(caller)?) + { + return Err(Status::failed_precondition( + "performance cursor is stale; query again", + )); + } + Ok(entry.after_sequence) + } + + fn issue_performance_cursor( + &self, + caller: &ResourceCaller, + scope: [u8; 32], + after_sequence: u64, + broker_revision: u64, + ) -> Result { + let owner = Self::data_identity(caller)?; + let mut cursors = self + .performance_cursors + .lock() + .unwrap_or_else(|p| p.into_inner()); + cursors.retain(|_, value| value.expires_at > Instant::now()); + if cursors.len() >= MAX_CURSORS + && let Some(key) = cursors + .iter() + .min_by_key(|(_, value)| value.expires_at) + .map(|(key, _)| key.clone()) + { + cursors.remove(&key); + } + let mut bytes = [0u8; 24]; + getrandom::fill(&mut bytes) + .map_err(|_| Status::internal("cursor randomness unavailable"))?; + let token = bytes + .iter() + .map(|byte| format!("{byte:02x}")) + .collect::(); + cursors.insert( + token.clone(), + CursorEntry { + session_id: caller.session_id.clone(), + owner: owner.clone(), + scope_hash: scope, + broker_revision, + policy_revision: self.shared_authorizer.revision(&owner), + after_sequence, + expires_at: Instant::now() + CURSOR_TTL, + }, + ); + Ok(token) + } +} + +#[tonic::async_trait] +impl game_performance_server::GamePerformance for ResourceApi { + type WatchStream = WatchStream; + async fn list( + &self, + request: Request, + ) -> Result, Status> { + self.list_performance(request).await + } + async fn get( + &self, + request: Request, + ) -> Result, Status> { + self.get_performance(request).await + } + async fn watch( + &self, + request: Request, + ) -> Result, Status> { + self.watch_performance(request).await + } + async fn query_series( + &self, + request: Request, + ) -> Result, Status> { + self.query_performance_series(request).await + } + async fn aggregate( + &self, + request: Request, + ) -> Result, Status> { + self.aggregate_performance(request).await + } +} + +pub(super) fn validate_request( + request: &PerformanceSamplesRequest, + now: i64, +) -> Result<(String, Vec, i64), Status> { + if !valid_identifier(&request.series_id, MAX_SERIES_ID) + || !valid_identifier(&request.game_id, MAX_SERIES_ID) + || !request.computer_id.is_empty() + || (!request.runtime_id.is_empty() && !valid_identifier(&request.runtime_id, MAX_SERIES_ID)) + || !valid_text(&request.runtime_recipe_revision, false) + || !valid_text(&request.source, true) + || !valid_text(&request.tool_name, true) + || !valid_text(&request.tool_version, true) + || !valid_text(&request.memory_source, true) + || request.fps_unit != "frames/second" + || request.cpu_unit != "percent" + || request.memory_unit != "bytes" + || !(MIN_SAMPLE_INTERVAL_MS..=MAX_SAMPLE_INTERVAL_MS).contains(&request.sample_interval_ms) + || request.samples.is_empty() + || request.samples.len() > MAX_BATCH_SAMPLES + || request.encoded_len() > MAX_BATCH_BYTES + { + return Err(Status::invalid_argument( + "invalid performance series or batch", + )); + } + if PerformanceCpuScope::try_from(request.cpu_scope) + .ok() + .is_none_or(|scope| scope == PerformanceCpuScope::Unspecified) + || PerformanceCpuNormalization::try_from(request.cpu_normalization) + .ok() + .is_none_or(|value| value == PerformanceCpuNormalization::Unspecified) + || PerformanceMemoryKind::try_from(request.memory_kind) + .ok() + .is_none_or(|value| value == PerformanceMemoryKind::Unspecified) + { + return Err(Status::invalid_argument( + "performance units and scope are required", + )); + } + let context = request + .mutation + .as_ref() + .and_then(|mutation| mutation.context.as_ref()) + .ok_or_else(|| Status::invalid_argument("performance mutation context is required"))?; + let target = context + .target_game + .as_ref() + .ok_or_else(|| Status::failed_precondition("performance samples need a selected game"))?; + if target.game_id != request.game_id { + return Err(Status::permission_denied( + "performance game does not match the host-selected game", + )); + } + if target.installation_id.is_empty() || target.installation_id.len() > MAX_SERIES_ID { + return Err(Status::failed_precondition( + "performance samples need a selected installation", + )); + } + let mut previous_sequence = 0; + let mut previous_time = 0; + let mut first_time = 0; + let mut samples = Vec::with_capacity(request.samples.len()); + for sample in &request.samples { + if sample.sequence == 0 + || sample.sequence <= previous_sequence + || sample.observed_at <= 0 + || sample.observed_at > now.saturating_add(300_000) + || (previous_time > 0 + && sample.observed_at.saturating_sub(previous_time) + < i64::from(request.sample_interval_ms)) + || !sample.frames_per_second.is_finite() + || !(0.0..=MAX_FPS).contains(&sample.frames_per_second) + || !sample.cpu_percent.is_finite() + || sample.cpu_percent < 0.0 + || (request.cpu_normalization + == PerformanceCpuNormalization::WholeMachinePercent as i32 + && sample.cpu_percent > 100.0) + || (request.cpu_normalization == PerformanceCpuNormalization::PerCorePercent as i32 + && sample.cpu_percent > MAX_FPS) + || sample.sampling_window_ms > MAX_SAMPLE_WINDOW_MS + || (sample.fps_method != PerformanceFpsMethod::Instantaneous as i32 + && sample.sampling_window_ms < request.sample_interval_ms) + || (sample.fps_method != PerformanceFpsMethod::Instantaneous as i32 + && sample.sampling_window_ms == 0) + || (sample.fps_method == PerformanceFpsMethod::Instantaneous as i32 + && sample.sampling_window_ms != 0) + || !matches!( + PerformanceFpsMethod::try_from(sample.fps_method), + Ok(PerformanceFpsMethod::Instantaneous) + | Ok(PerformanceFpsMethod::FrameCountWindow) + | Ok(PerformanceFpsMethod::FrameTimeDerived) + ) + || !matches!( + PerformanceFpsStatistic::try_from(sample.fps_statistic), + Ok(PerformanceFpsStatistic::Instantaneous) + | Ok(PerformanceFpsStatistic::Average) + | Ok(PerformanceFpsStatistic::Minimum) + | Ok(PerformanceFpsStatistic::Maximum) + | Ok(PerformanceFpsStatistic::Percentile) + ) + || !matches!( + PerformanceMeasurementQuality::try_from(sample.quality), + Ok(PerformanceMeasurementQuality::Measured) + | Ok(PerformanceMeasurementQuality::Estimated) + ) + { + return Err(Status::invalid_argument("invalid performance sample")); + } + if sample.fps_method == PerformanceFpsMethod::Instantaneous as i32 + && sample.fps_statistic != PerformanceFpsStatistic::Instantaneous as i32 + { + return Err(Status::invalid_argument( + "instantaneous FPS must use instantaneous statistic", + )); + } + match sample.fps_statistic { + value if value == PerformanceFpsStatistic::Percentile as i32 => { + if sample.fps_percentile.is_none_or(|percentile| { + !percentile.is_finite() || !(0.0..=100.0).contains(&percentile) + }) { + return Err(Status::invalid_argument( + "FPS percentile must be between 0 and 100", + )); + } + } + _ if sample.fps_percentile.is_some() => { + return Err(Status::invalid_argument( + "FPS percentile is only valid for a percentile statistic", + )); + } + _ => {} + } + if sample.frames_per_second_min.is_some_and(|value| { + !value.is_finite() || !(0.0..=sample.frames_per_second).contains(&value) + }) || sample.frames_per_second_max.is_some_and(|value| { + !value.is_finite() || !(sample.frames_per_second..=MAX_FPS).contains(&value) + }) { + return Err(Status::invalid_argument("FPS range is inconsistent")); + } + if (sample.fps_statistic == PerformanceFpsStatistic::Minimum as i32 + && sample + .frames_per_second_min + .is_some_and(|value| value != sample.frames_per_second)) + || (sample.fps_statistic == PerformanceFpsStatistic::Maximum as i32 + && sample + .frames_per_second_max + .is_some_and(|value| value != sample.frames_per_second)) + { + return Err(Status::invalid_argument( + "FPS statistic conflicts with its value", + )); + } + if first_time == 0 { + first_time = sample.observed_at; + } + previous_sequence = sample.sequence; + previous_time = sample.observed_at; + samples.push(*sample); + } + let mut canonical = request.clone(); + canonical.mutation = None; + let digest = Sha256::digest(canonical.encode_to_vec()); + let batch_hash = digest.iter().map(|byte| format!("{byte:02x}")).collect(); + Ok((batch_hash, samples, first_time)) +} + +fn backpressure_reply( + report_id: String, + dropped: usize, + retry_after_ms: u32, + retained_from: i64, + retained_to: i64, +) -> ReportMutationReply { + ReportMutationReply { + report_id, + revision: 0, + outcome: MutationOutcome::Backpressure as i32, + accepted_samples: 0, + dropped_samples: dropped.min(u32::MAX as usize) as u32, + retry_after_ms, + retained_from, + retained_to, + } +} diff --git a/crates/app/src/plugin_host/resources/persistence.rs b/crates/app/src/plugin_host/resources/persistence.rs new file mode 100644 index 000000000..30e700314 --- /dev/null +++ b/crates/app/src/plugin_host/resources/persistence.rs @@ -0,0 +1,385 @@ +//! Owner-scoped administration for a plugin's durable private key/value namespace. +//! +//! These routes expose logical metadata only. They never return values, store paths, or a +//! namespace selector supplied by the plugin. Ownership and cursor bindings come from the +//! authenticated session. + +use gamenode_platform::plugin_storage::{MAX_TTL_SECONDS, QUOTA_BYTES, RetentionPolicy}; +use gamenode_plugin_protocol::{capability as cap, proto::*}; +use sha2::{Digest, Sha256}; +use tonic::{Request, Response, Status}; + +use super::mutations::{mutation_key, reply, request_hash}; +use super::{DEFAULT_PAGE_SIZE, MAX_PAGE_SIZE, ResourceApi}; +use crate::plugin_host::library::CommitGuard; +use crate::plugin_host::provider::ResourceCaller; + +const MAX_DELETE_ENTRIES: usize = 256; +const MAX_ENTRY_ID_BYTES: usize = 64; + +fn category(value: &str) -> Result<&'static str, Status> { + if value == "private" { + Ok("private") + } else { + Err(Status::invalid_argument("category must be private")) + } +} + +fn owner_binding(caller: &ResourceCaller, revision: u64) -> Result { + let resolver = caller + .namespace + .as_ref() + .ok_or_else(|| Status::failed_precondition("account namespace required"))?; + let storage_owner = resolver.storage_owner(); + let owner = storage_owner.key(); + let owner_hex: String = owner.iter().map(|byte| format!("{byte:02x}")).collect(); + Ok(format!( + "persistence:{owner_hex}:{}:{revision}:private", + caller.profile_epoch + )) +} + +fn entry_id(caller: &ResourceCaller, key: &str) -> Result { + let resolver = caller + .namespace + .as_ref() + .ok_or_else(|| Status::failed_precondition("account namespace required"))?; + let mut digest = Sha256::new(); + digest.update(b"gamenode.persistence.entry.v1\0"); + digest.update(resolver.storage_owner().key()); + digest.update((key.len() as u64).to_be_bytes()); + digest.update(key.as_bytes()); + Ok(digest + .finalize() + .iter() + .map(|byte| format!("{byte:02x}")) + .collect()) +} + +fn validate_ids(ids: &[String]) -> Result<(), Status> { + if ids.len() > MAX_DELETE_ENTRIES { + return Err(Status::invalid_argument(format!( + "at most {MAX_DELETE_ENTRIES} entries may be deleted" + ))); + } + let mut unique = std::collections::HashSet::new(); + for id in ids { + if id.len() != MAX_ENTRY_ID_BYTES + || !id.bytes().all(|byte| byte.is_ascii_hexdigit()) + || !unique.insert(id) + { + return Err(Status::invalid_argument( + "entry ids must be unique opaque ids", + )); + } + } + Ok(()) +} + +impl ResourceApi { + pub(super) async fn persistence_usage( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + let caller = self + .providers + .authorize_resource(request.context.as_ref(), cap::STORAGE_PERSIST)?; + let usage = self + .in_namespace(&caller, |namespace| namespace.store_usage()) + .await?; + self.providers + .authorize_resource(request.context.as_ref(), cap::STORAGE_PERSIST)?; + Ok(Response::new(PersistenceUsageReply { + logical_bytes: usage.logical_bytes, + physical_bytes: usage.physical_bytes_estimate, + quota_bytes: QUOTA_BYTES, + categories: usage + .categories + .into_iter() + .map(|category| PersistenceCategoryUsage { + category: category.category, + records: category.records, + logical_bytes: category.logical_bytes, + protected_records: category.protected_records, + }) + .collect(), + // SQLite metadata and free pages belong to the whole namespace database. + physical_bytes_namespace_wide: true, + })) + } + + pub(super) async fn persistence_list( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + let page = request + .page + .ok_or_else(|| Status::invalid_argument("page is required"))?; + let category = category(&request.category)?; + let caller = self + .providers + .authorize_resource(page.context.as_ref(), cap::STORAGE_PERSIST)?; + let limit = match page.page_size as usize { + 0 => DEFAULT_PAGE_SIZE, + size => size.min(MAX_PAGE_SIZE), + }; + let (revision, entries) = self + .in_namespace(&caller, |namespace| { + Ok((namespace.revision()?, namespace.persistence_entries()?)) + }) + .await?; + let binding = owner_binding(&caller, revision)?; + let after = if page.cursor.is_empty() { + None + } else { + let key = self + .files + .open_cursor(&caller.session_id, &binding, &page.cursor) + .ok_or_else(|| { + Status::failed_precondition("persistence cursor is invalid or stale") + })?; + Some(key) + }; + let mut records = entries + .into_iter() + .filter(|entry| after.as_ref().is_none_or(|key| entry.key > *key)); + let selected: Vec<_> = records.by_ref().take(limit).collect(); + let has_more = records.next().is_some(); + let next_cursor = if has_more { + selected + .last() + .map(|last| { + self.files + .seal_cursor(&caller.session_id, &binding, &last.key) + }) + .unwrap_or_default() + } else { + String::new() + }; + self.providers + .authorize_resource(page.context.as_ref(), cap::STORAGE_PERSIST)?; + let entries = selected + .into_iter() + .map(|entry| { + Ok(PersistenceEntry { + entry_id: entry_id(&caller, &entry.key)?, + category: category.to_owned(), + logical_key: entry.key, + size_bytes: entry.size_bytes, + last_used_at: entry.last_used_at, + user_protected: entry.user_protected, + }) + }) + .collect::, Status>>()?; + Ok(Response::new(PersistenceListReply { + entries, + next_cursor, + })) + } + + pub(super) async fn persistence_delete( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + let mutation = request + .mutation + .as_ref() + .ok_or_else(|| Status::invalid_argument("mutation is required"))?; + let context = mutation + .context + .clone() + .ok_or_else(|| Status::invalid_argument("context is required"))?; + let caller = self + .providers + .authorize_resource(Some(&context), cap::STORAGE_PERSIST)?; + validate_ids(&request.entry_ids)?; + let idempotency = mutation_key(mutation)?.to_owned(); + let ids = request.entry_ids; + let mut hash_parts = vec![ + "persistence.delete".to_owned(), + mutation.expected_revision.to_string(), + ]; + hash_parts.extend(ids.iter().cloned()); + let hash_refs: Vec<_> = hash_parts.iter().map(String::as_str).collect(); + let hash = request_hash(&hash_refs); + let guard = self.guard(context, cap::STORAGE_PERSIST, caller.grant_revision); + self.persist_delete( + caller, + ids, + idempotency, + mutation.expected_revision, + hash, + guard, + ) + .await + .map(Response::new) + } + + async fn persist_delete( + &self, + caller: ResourceCaller, + ids: Vec, + idempotency: String, + expected: u64, + hash: [u8; 32], + guard: CommitGuard, + ) -> Result { + let mutations = self.mutations.clone(); + let remember_as = caller.clone(); + self.in_namespace(&caller, move |namespace| { + if let Some(original) = mutations.replay(&remember_as, &idempotency, hash)? { + return Ok(original); + } + let current = namespace.revision()?; + if current != expected { + return Ok(reply("private", current, MutationOutcome::RevisionConflict)); + } + let entries = namespace.persistence_entries()?; + let mut keys = Vec::with_capacity(ids.len()); + for requested in &ids { + let found = entries + .iter() + .find(|entry| { + entry_id(&remember_as, &entry.key).is_ok_and(|id| id == *requested) + }) + .ok_or_else(|| Status::not_found("persistence entry not found"))?; + keys.push(found.key.clone()); + } + let (reclaimed, revision) = namespace.delete_persistence_entries(&keys, &guard)?; + let answer = reply( + "private", + revision, + if reclaimed > 0 { + MutationOutcome::Applied + } else { + MutationOutcome::AlreadyApplied + }, + ); + mutations.remember(&remember_as, &idempotency, hash, &answer); + Ok(answer) + }) + .await + } + + pub(super) async fn persistence_clear_entries( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + category(&request.category)?; + let mutation = request + .mutation + .as_ref() + .ok_or_else(|| Status::invalid_argument("mutation is required"))?; + let context = mutation + .context + .clone() + .ok_or_else(|| Status::invalid_argument("context is required"))?; + let caller = self + .providers + .authorize_resource(Some(&context), cap::STORAGE_PERSIST)?; + let idempotency = mutation_key(mutation)?.to_owned(); + let hash = request_hash(&[ + "persistence.clear", + "private", + &mutation.expected_revision.to_string(), + ]); + let guard = self.guard(context, cap::STORAGE_PERSIST, caller.grant_revision); + let mutations = self.mutations.clone(); + let remember_as = caller.clone(); + let expected = mutation.expected_revision; + let answer = self + .in_namespace(&caller, move |namespace| { + if let Some(original) = mutations.replay(&remember_as, &idempotency, hash)? { + return Ok(original); + } + let current = namespace.revision()?; + if current != expected { + return Ok(reply("private", current, MutationOutcome::RevisionConflict)); + } + let entries = namespace.persistence_entries()?; + // A plugin clear never removes user-protected records; an explicit delete of a + // protected entry fails below instead. + let keys: Vec<_> = entries + .into_iter() + .filter(|entry| !entry.user_protected) + .map(|entry| entry.key) + .collect(); + let (reclaimed, revision) = namespace.delete_persistence_entries(&keys, &guard)?; + let answer = reply( + "private", + revision, + if reclaimed > 0 { + MutationOutcome::Applied + } else { + MutationOutcome::AlreadyApplied + }, + ); + mutations.remember(&remember_as, &idempotency, hash, &answer); + Ok(answer) + }) + .await?; + Ok(Response::new(answer)) + } + + pub(super) async fn persistence_set_policy( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + category(&request.category)?; + if request.max_age_seconds > MAX_TTL_SECONDS || request.max_bytes > QUOTA_BYTES { + return Err(Status::invalid_argument( + "retention limits exceed the storage maximum", + )); + } + let mutation = request + .mutation + .as_ref() + .ok_or_else(|| Status::invalid_argument("mutation is required"))?; + let context = mutation + .context + .clone() + .ok_or_else(|| Status::invalid_argument("context is required"))?; + let caller = self + .providers + .authorize_resource(Some(&context), cap::STORAGE_PERSIST)?; + let idempotency = mutation_key(mutation)?.to_owned(); + let hash = request_hash(&[ + "persistence.retention", + "private", + &mutation.expected_revision.to_string(), + &request.max_age_seconds.to_string(), + &request.max_bytes.to_string(), + ]); + let guard = self.guard(context, cap::STORAGE_PERSIST, caller.grant_revision); + let policy = RetentionPolicy { + max_age_seconds: request.max_age_seconds, + max_bytes: request.max_bytes, + }; + let mutations = self.mutations.clone(); + let remember_as = caller.clone(); + let expected = mutation.expected_revision; + let answer = self + .in_namespace(&caller, move |namespace| { + if let Some(original) = mutations.replay(&remember_as, &idempotency, hash)? { + return Ok(original); + } + let current = namespace.revision()?; + if current != expected { + return Ok(reply("private", current, MutationOutcome::RevisionConflict)); + } + let (reclaimed, revision) = + namespace.set_retention_policy("private", policy, &guard)?; + let _ = reclaimed; + let answer = reply("private", revision, MutationOutcome::Applied); + mutations.remember(&remember_as, &idempotency, hash, &answer); + Ok(answer) + }) + .await?; + Ok(Response::new(answer)) + } +} diff --git a/crates/app/src/plugin_host/resources/ports.rs b/crates/app/src/plugin_host/resources/ports.rs new file mode 100644 index 000000000..780a4c321 --- /dev/null +++ b/crates/app/src/plugin_host/resources/ports.rs @@ -0,0 +1,285 @@ +//! Finite host catalog, scoped supplied resources and the user's existing guided setup. +use super::mutations::{game_id, mutation_key, request_hash}; +use super::*; +use crate::plugin_host::jobs::{JobOwner, Outcome, work}; +use crate::plugin_host::provider::ResourceCaller; +use gamenode_core::ports::view::{PortPluginRequest, PortPluginSource}; +use gamenode_platform::plugin_storage::operation; + +fn port_id(id: &str) -> Result<(), Status> { + if id.is_empty() + || id.len() > 256 + || !id + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b"-_.:".contains(&b)) + { + return Err(Status::invalid_argument( + "a host catalog port id is required", + )); + } + Ok(()) +} +impl ResourceApi { + pub(super) async fn list_ports( + &self, + request: Request, + ) -> Result, Status> { + let r = request.into_inner(); + let page = r.page.unwrap_or_default(); + let context = page.context.unwrap_or_default(); + let caller = self + .providers + .authorize_resource(Some(&context), cap::PORTS_READ)?; + no_common_data(page.common_data_categories.as_ref())?; + if !matches!(r.platform.as_str(), "" | "windows" | "linux") + || r.query.len() > 256 + || r.query.chars().any(char::is_control) + { + return Err(Status::invalid_argument("invalid ports filter")); + } + let host = self + .library + .host() + .ok_or_else(|| Status::unavailable("ports catalog unavailable"))?; + let mut records = tokio::time::timeout(Duration::from_secs(30), host.ports_catalog(None)) + .await + .map_err(|_| Status::deadline_exceeded("ports catalog deadline exceeded"))??; + if records.len() > 10000 { + return Err(Status::resource_exhausted( + "port catalog exceeds the record limit", + )); + } + let platform = r.platform.clone(); + let query_text = r.query.clone(); + let grant_revision = caller.grant_revision; + let (records, binding) = tokio::task::spawn_blocking(move || { + let query = query_text.to_lowercase(); + records.retain(|p| { + (platform.is_empty() || p.platform == platform) + && (query.is_empty() || p.name.to_lowercase().contains(&query)) + }); + records.sort_by(|a, b| a.port_id.cmp(&b.port_id)); + let binding = format!( + "ports:{:?}", + request_hash(&[ + &platform, + &query_text, + &grant_revision.to_string(), + &format!("{records:?}") + ]) + ); + (records, binding) + }) + .await + .map_err(|_| Status::unavailable("port catalog worker unavailable"))?; + let after = if page.cursor.is_empty() { + 0 + } else { + self.files + .open_cursor(&caller.session_id, &binding, &page.cursor) + .and_then(|s| s.parse::().ok()) + .filter(|n| *n <= records.len()) + .ok_or_else(|| Status::failed_precondition("port catalog changed; list again"))? + }; + let size = if page.page_size == 0 { + DEFAULT_PAGE_SIZE + } else { + (page.page_size as usize).min(MAX_PAGE_SIZE) + }; + let end = (after + size).min(records.len()); + let next_cursor = if end < records.len() { + self.files + .seal_cursor(&caller.session_id, &binding, &end.to_string()) + } else { + String::new() + }; + (self.guard(context, cap::PORTS_READ, caller.grant_revision))()?; + Ok(Response::new(PortsListReply { + ports: records[after..end].to_vec(), + next_cursor, + })) + } + pub(super) async fn detail_port( + &self, + request: Request, + ) -> Result, Status> { + let r = request.into_inner(); + let context = r.context.unwrap_or_default(); + let caller = self + .providers + .authorize_resource(Some(&context), cap::PORTS_READ)?; + port_id(&r.port_id)?; + let host = self + .library + .host() + .ok_or_else(|| Status::unavailable("ports catalog unavailable"))?; + let records = tokio::time::timeout( + Duration::from_secs(30), + host.ports_catalog(Some(r.port_id.clone())), + ) + .await + .map_err(|_| Status::deadline_exceeded("port detail deadline exceeded"))??; + let record = records + .into_iter() + .find(|p| p.port_id == r.port_id) + .ok_or_else(|| Status::not_found("port not found"))?; + (self.guard(context, cap::PORTS_READ, caller.grant_revision))()?; + Ok(Response::new(PortDetailReply { port: Some(record) })) + } + fn resolve_port_sources( + &self, + caller: &ResourceCaller, + handles: &[String], + ) -> Result, Status> { + self.storage.on_backup_worker(caller, |namespace| { + handles + .iter() + .map(|handle| { + let opened = super::files::open_handle( + &self.files, + &self.library, + namespace, + &caller.session_id, + handle, + operation::READ, + )?; + let entry = opened + .confined + .stat(&opened.path) + .map_err(super::files::file_status)?; + let path = opened.path.iter().fold( + std::path::PathBuf::from(&opened.approval.root), + |p, part| p.join(part), + ); + Ok(PortPluginSource { + path: path.to_string_lossy().into_owned(), + directory: entry.directory, + }) + }) + .collect() + }) + } + pub(super) async fn install_port( + &self, + request: Request, + ) -> Result, Status> { + let r = request.into_inner(); + let mutation = r + .mutation + .ok_or_else(|| Status::invalid_argument("mutation required"))?; + let context = mutation.context.clone().unwrap_or_default(); + let caller = self + .providers + .authorize_resource(Some(&context), cap::PORTS_INSTALL)?; + port_id(&r.port_id)?; + if !r.user_intent_id.is_empty() { + return Err(Status::failed_precondition( + "port installation requires Core guided setup", + )); + } + if r.supplied_file_handles.len() > 16 + || r.supplied_file_handles + .iter() + .any(|s| s.is_empty() || s.len() > 16384) + { + return Err(Status::invalid_argument( + "at most 16 scoped source handles are accepted", + )); + } + let target = if game_id(&r.game_id)?.is_some() { + Some(self.tool_target(&caller, &context, &r.game_id)?) + } else { + None + }; + if target + .as_ref() + .is_some_and(|(_, e)| e.revision != mutation.expected_revision) + || (target.is_none() && mutation.expected_revision != 0) + { + return Err(Status::aborted("port source target revision changed")); + } + let host = self + .library + .host() + .filter(|h| h.ports_supported()) + .ok_or_else(|| Status::unavailable("port installation unavailable on this platform"))?; + let key = mutation_key(&mutation)?.to_owned(); + let hash = request_hash(&[ + cap::PORTS_INSTALL, + &r.port_id, + &r.game_id, + &format!("{:?}", r.supplied_file_handles), + &mutation.expected_revision.to_string(), + ]); + let owner = JobOwner::of(&caller)?; + let _serial = self.mutations.lock.lock().await; + if let Some(original) = self.jobs.replay(&owner, &key, hash)? { + return Ok(Response::new(original)); + } + if !r.supplied_file_handles.is_empty() { + self.providers + .authorize_resource(Some(&context), cap::FILES_READ)?; + } + let api = self.clone(); + let c = caller.clone(); + let handles = r.supplied_file_handles.clone(); + let sources = if handles.is_empty() { + vec![] + } else { + tokio::task::spawn_blocking(move || api.resolve_port_sources(&c, &handles)) + .await + .map_err(|_| Status::unavailable("source scope worker unavailable"))?? + }; + let identity = caller + .namespace + .as_ref() + .ok_or_else(|| Status::unavailable("plugin identity unavailable"))? + .identity(); + let review = PortPluginRequest { + id: String::new(), + catalog_id: r.port_id.clone(), + plugin_id: identity.plugin_id.clone(), + publisher_fingerprint: identity.publisher_fingerprint.clone(), + sources: sources.clone(), + }; + let api = self.clone(); + let c = caller.clone(); + let cx = context.clone(); + let run = work(move |job| async move { + if let Err(e) = job.start() { + return Outcome::stopped(&e); + } + let checkpoint = job.checkpoint(); + let check = Arc::new(move || { + checkpoint()?; + if let Some((key, entry)) = &target + && api.library.revision_of(key) != Some(entry.revision) + { + return Err(Status::failed_precondition("port source game changed")); + } + if !r.supplied_file_handles.is_empty() { + api.providers + .authorize_resource(Some(&cx), cap::FILES_READ)?; + if api.resolve_port_sources(&c, &r.supplied_file_handles)? != sources { + return Err(Status::failed_precondition("port sources changed")); + } + } + Ok(()) + }); + match host.request_port(r.port_id, review, check).await { + Ok(()) => Outcome::succeeded("port_complete", "port installation completed"), + Err(e) => Outcome::stopped(&e), + } + }); + let (job, _) = self.start_job( + &caller, + context, + cap::PORTS_INSTALL, + &key, + hash, + Some("review in Core port setup"), + run, + )?; + Ok(Response::new(job)) + } +} diff --git a/crates/app/src/plugin_host/resources/runtimes.rs b/crates/app/src/plugin_host/resources/runtimes.rs new file mode 100644 index 000000000..b73933f5a --- /dev/null +++ b/crates/app/src/plugin_host/resources/runtimes.rs @@ -0,0 +1,2061 @@ +//! Owner-scoped installed runtime resources and game-content bindings. +//! +//! Plugin file handles are session scoped. Durable records keep only the host-owned approval id +//! and relative path; reads issue a fresh handle after checking the approval and current grant. + +use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; +use std::time::{SystemTime, UNIX_EPOCH}; +use tokio::sync::mpsc; +use tokio_stream::wrappers::ReceiverStream; + +use gamenode_core::library::{ + ApprovedFileReference, LaunchPlanResource, RuntimeArgumentTemplate as CoreArgument, + RuntimeContentBinding, RuntimeExtension, RuntimeMutation, RuntimeProvenance, RuntimeResource, +}; +use gamenode_platform::plugin_storage::RuntimeApproval; +use gamenode_plugin_protocol::{ + capability as cap, + extensions::{MAX_EXTENSION_BYTES, validate_payload}, + proto::*, +}; +use tonic::{Request, Response, Status}; + +use super::mutations::{mutation_key, mutation_owner, request_hash, unavailable}; +use super::{ + CursorBinding, CursorError, DEFAULT_PAGE_SIZE, MAX_PAGE_SIZE, ResourceApi, Scope, + json_to_struct, struct_to_json, +}; +use crate::plugin_host::files::APPROVAL_TIMEOUT; +use crate::plugin_host::provider::ResourceCaller; +use crate::plugin_host::runtime_access::{ + RuntimeAccessRequest, RuntimeHints, inspect_executable, suggestions, validate_approval, +}; +use crate::plugin_host::sharing_policy::AccessDecision; + +const MAX_RUNTIME_ID_BYTES: usize = 128; +const MAX_BINDINGS_PER_ENTRY: usize = 512; +const WATCH_RECHECK: std::time::Duration = std::time::Duration::from_secs(5); +const WATCH_POLL: std::time::Duration = std::time::Duration::from_millis(500); +/// Projection names a common runtime-catalog reader may see. Executable handles, approvals and +/// private owner identifiers are never part of it. +const SHARED_RUNTIME_FIELDS: &[&str] = &[ + "id", + "name", + "version", + "platform", + "supported_formats", + "argument_template", + "extensions", + "provenance", + "revision", + "observed_at", +]; + +struct ResolvedRuntimePath { + path: String, + resource: LaunchPlanResource, +} + +fn current_platform() -> &'static str { + if cfg!(target_os = "windows") { + "windows" + } else if cfg!(target_os = "linux") { + "linux" + } else if cfg!(target_os = "macos") { + "macos" + } else { + "unknown" + } +} + +fn runtime_id() -> Result { + let mut bytes = [0u8; 16]; + getrandom::fill(&mut bytes).map_err(|_| Status::internal("no source of randomness"))?; + Ok(bytes.iter().map(|byte| format!("{byte:02x}")).collect()) +} + +fn unix_now() -> i64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|duration| duration.as_secs().min(i64::MAX as u64) as i64) + .unwrap_or_default() +} + +fn mutation_outcome(value: RuntimeMutation) -> (MutationOutcome, u64, bool) { + match value { + RuntimeMutation::Applied { revision } => (MutationOutcome::Applied, revision, true), + RuntimeMutation::Conflict { current } => { + (MutationOutcome::RevisionConflict, current, false) + } + RuntimeMutation::Missing => (MutationOutcome::RevisionConflict, 0, false), + } +} + +fn runtime_request_shape(record: &RuntimeRecord, require_executable: bool) -> Result<(), Status> { + if record.id.len() > MAX_RUNTIME_ID_BYTES + || record.name.len() > 4096 + || record.version.len() > 4096 + || record.platform.len() > MAX_RUNTIME_ID_BYTES + || (require_executable && record.executable_handle.is_empty()) + || record.executable_handle.len() > 16 * 1024 + || record.supported_formats.is_empty() + || record.supported_formats.len() > 128 + || record.argument_template.len() > 128 + { + return Err(Status::invalid_argument("invalid runtime resource")); + } + Ok(()) +} + +fn core_arguments(values: &[RuntimeArgumentTemplate]) -> Result, Status> { + values + .iter() + .map(|argument| match argument.value.as_ref() { + Some(runtime_argument_template::Value::Literal(value)) => { + Ok(CoreArgument::Literal(value.clone())) + } + Some(runtime_argument_template::Value::ContentPath(_)) => Ok(CoreArgument::ContentPath), + None => Err(Status::invalid_argument( + "runtime argument template must select a value", + )), + }) + .collect() +} + +fn proto_arguments(values: &[CoreArgument]) -> Vec { + values + .iter() + .map(|argument| RuntimeArgumentTemplate { + value: Some(match argument { + CoreArgument::Literal(value) => { + runtime_argument_template::Value::Literal(value.clone()) + } + CoreArgument::ContentPath => { + runtime_argument_template::Value::ContentPath(ContentPathArgument {}) + } + }), + }) + .collect() +} + +fn validate_common_selector(selector: Option<&CommonDataSelector>) -> Result<(), Status> { + match selector { + Some(selector) if !selector.selected_record_ids.is_empty() => Err(Status::unimplemented( + "selected-record runtime catalog reads are not available in this build", + )), + Some(selector) + if !selector.categories.is_empty() + && selector.categories != [CommonDataCategory::RuntimeCatalog as i32] => + { + Err(Status::unimplemented( + "common runtime catalog projections support only the runtime catalog category", + )) + } + _ => Ok(()), + } +} + +fn runtime_extension_payloads( + record: &RuntimeRecord, +) -> Result, Status> { + let mut extensions = BTreeMap::new(); + let mut total = 0usize; + for (namespace, payload) in &record.extensions { + let valid_namespace = !namespace.is_empty() + && namespace.len() <= MAX_RUNTIME_ID_BYTES + && namespace + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'-' | b'_')); + if !valid_namespace + || (payload.schema_id != *namespace + && !payload.schema_id.starts_with(&format!("{namespace}."))) + { + return Err(Status::invalid_argument( + "runtime extension namespace and schema do not match", + )); + } + validate_payload(payload) + .map_err(|_| Status::invalid_argument("invalid runtime extension payload"))?; + let data = payload + .data + .as_ref() + .ok_or_else(|| Status::invalid_argument("runtime extension data is required"))?; + let data = serde_json::Value::Object(struct_to_json(data)?); + total = total + .checked_add(serde_json::to_vec(&data).map_or(usize::MAX, |bytes| bytes.len())) + .ok_or_else(|| Status::invalid_argument("runtime extension size overflow"))?; + if total > MAX_EXTENSION_BYTES { + return Err(Status::resource_exhausted( + "runtime extensions exceed the accepted size", + )); + } + extensions.insert( + namespace.clone(), + RuntimeExtension { + schema_id: payload.schema_id.clone(), + schema_version: payload.schema_version, + schema_digest: payload.schema_digest.clone(), + data, + }, + ); + } + Ok(extensions) +} + +fn runtime_extension_proto( + extensions: &BTreeMap, +) -> Result, Status> { + extensions + .iter() + .map(|(namespace, extension)| { + let serde_json::Value::Object(data) = &extension.data else { + return Err(Status::internal("stored runtime extension is invalid")); + }; + Ok(( + namespace.clone(), + ExtensionPayload { + schema_id: extension.schema_id.clone(), + schema_version: extension.schema_version, + schema_digest: extension.schema_digest.clone(), + data: Some(json_to_struct(data)), + }, + )) + }) + .collect() +} + +fn runtime_provenance(caller: &ResourceCaller) -> RuntimeProvenance { + let identity = caller + .namespace + .as_ref() + .map(|namespace| namespace.identity()); + RuntimeProvenance { + plugin_id: identity + .map(|identity| identity.plugin_id.clone()) + .unwrap_or_default(), + declared_developer: caller.declared_developer.clone(), + origin: caller.origin.clone(), + publisher_fingerprint: identity + .map(|identity| identity.publisher_fingerprint.clone()) + .unwrap_or_default(), + package_version: caller.package_version.clone(), + package_digest: caller.package_digest.clone(), + } +} + +fn runtime_provenance_proto(provenance: &RuntimeProvenance) -> Option { + (!provenance.plugin_id.is_empty()).then(|| DataProvenance { + producer_plugin_id: provenance.plugin_id.clone(), + declared_developer: provenance.declared_developer.clone(), + origin: provenance.origin.clone(), + publisher_fingerprint: provenance.publisher_fingerprint.clone(), + package_version: provenance.package_version.clone(), + package_digest: provenance.package_digest.clone(), + ..Default::default() + }) +} + +fn valid_id(value: &str) -> bool { + !value.is_empty() + && value.len() <= MAX_RUNTIME_ID_BYTES + && !value + .chars() + .any(|character| character.is_control() || character == '\0') +} + +impl ResourceApi { + pub(super) fn authorize_commit( + &self, + context: &ServiceContext, + permission: &'static str, + initial_grant_revision: u64, + ) -> Result<(), Status> { + let caller = self + .providers + .authorize_resource(Some(context), permission)?; + if caller.grant_revision != initial_grant_revision { + return Err(Status::failed_precondition( + "plugin permissions changed; try again", + )); + } + Ok(()) + } + + /// Resolves a session token to a durable reference without retaining the token or a path. + async fn capture_reference( + &self, + caller: &ResourceCaller, + handle: String, + target: Option<(u64, String)>, + ) -> Result { + let files = self.files.clone(); + let feed = self.library.clone(); + let session = caller.session_id.clone(); + self.in_namespace(caller, move |namespace| { + let opened = super::files::open_handle( + &files, + &feed, + namespace, + &session, + &handle, + gamenode_platform::plugin_storage::operation::READ, + )?; + if !matches!( + opened.approval.kind.as_str(), + "installation" | "prefix" | "library" + ) { + return Err(Status::permission_denied( + "the handle is not an approved runtime or content file", + )); + } + if let Some((game_id, installation_id)) = target + && opened.approval.kind != "library" + && (opened.approval.game_id.parse::().ok() != Some(game_id) + || opened.approval.installation_id != installation_id) + { + return Err(Status::permission_denied( + "the content handle is not approved for this game installation", + )); + } + let entry = opened + .confined + .stat(&opened.path) + .map_err(super::files::file_status)?; + if entry.directory || opened.path.is_empty() { + return Err(Status::failed_precondition( + "runtime and content handles must identify files", + )); + } + let reference = ApprovedFileReference { + approval_id: opened.approval.id, + relative_path: opened.path, + }; + if reference.validate() { + Ok(reference) + } else { + Err(Status::invalid_argument("invalid approved file reference")) + } + }) + .await + } + + /// Revalidates a durable ref and creates a session-bound handle for a response. A runtime + /// approved through the host picker has no executable handle: the plugin never receives a + /// path or a file token for it. + async fn session_handle( + &self, + caller: &ResourceCaller, + reference: ApprovedFileReference, + ) -> Result { + if !reference.validate() { + return Err(Status::failed_precondition( + "stored runtime file reference is invalid", + )); + } + let files = self.files.clone(); + let feed = self.library.clone(); + let session = caller.session_id.clone(); + let reference_for_open = reference.clone(); + self.in_namespace(caller, move |namespace| { + if namespace + .runtime_approval_by_id(&reference_for_open.approval_id)? + .is_some() + { + return Ok(String::new()); + } + let opened = super::files::open_approval( + &files, + &feed, + namespace, + &reference_for_open.approval_id, + reference_for_open.relative_path.clone(), + gamenode_platform::plugin_storage::operation::READ, + )?; + let entry = opened + .confined + .stat(&opened.path) + .map_err(super::files::file_status)?; + if entry.directory || opened.path.is_empty() { + return Err(Status::failed_precondition( + "approved runtime file is no longer available", + )); + } + Ok(files.seal_handle(&session, &reference.approval_id, &reference.relative_path)) + }) + .await + } + + /// Resolves a durable host reference to a path only after checking that the approval still + /// belongs to this plugin/profile and that the target remains inside its approved root. A + /// picker-approved runtime is revalidated by identity, size and digest instead. + async fn resolve_reference_path( + &self, + caller: &ResourceCaller, + reference: ApprovedFileReference, + target: Option<(u64, String)>, + host_initiated: bool, + expected_runtime: Option, + ) -> Result { + if !reference.validate() { + return Err(Status::failed_precondition( + "approved file reference is invalid", + )); + } + let files = self.files.clone(); + let feed = self.library.clone(); + let reference_for_open = reference.clone(); + let resolve = move |namespace: &mut crate::plugin_host::storage::Namespace<'_>| { + if let Some(approval) = + namespace.runtime_approval_by_id(&reference_for_open.approval_id)? + { + if expected_runtime.as_deref() != Some(approval.runtime_id.as_str()) { + return Err(Status::failed_precondition( + "the runtime approval does not belong to this runtime", + )); + } + let path = validate_approval(&approval, &files.reserved)?; + return Ok(ResolvedRuntimePath { + path, + resource: LaunchPlanResource { + id: format!("runtime-approval:{}", approval.id), + revision: approval.approved_at.max(1) as u64, + }, + }); + } + let opened = super::files::open_approval( + &files, + &feed, + namespace, + &reference_for_open.approval_id, + reference_for_open.relative_path.clone(), + gamenode_platform::plugin_storage::operation::READ, + )?; + if let Some((game_id, installation_id)) = target + && opened.approval.kind != "library" + && (opened.approval.game_id.parse::().ok() != Some(game_id) + || opened.approval.installation_id != installation_id) + { + return Err(Status::permission_denied( + "the content approval no longer matches this game installation", + )); + } + let entry = opened + .confined + .stat(&opened.path) + .map_err(super::files::file_status)?; + if entry.directory || opened.path.is_empty() { + return Err(Status::failed_precondition( + "approved runtime or content file is no longer available", + )); + } + let root = std::fs::canonicalize(&opened.approval.root) + .map_err(|_| Status::failed_precondition("approved runtime folder changed"))?; + let mut target = root.clone(); + for component in &opened.path { + target.push(component); + } + let canonical = std::fs::canonicalize(&target) + .map_err(|_| Status::failed_precondition("approved file moved or changed"))?; + if !canonical.starts_with(&root) || !canonical.is_file() { + return Err(Status::permission_denied( + "approved file is outside its approved folder", + )); + } + let path = canonical + .to_str() + .map(str::to_owned) + .ok_or_else(|| Status::failed_precondition("approved path is not valid Unicode"))?; + Ok(ResolvedRuntimePath { + path, + resource: LaunchPlanResource { + id: format!( + "file-approval:{}:{}", + opened.approval.id, + reference_for_open.relative_path.join("/") + ), + revision: opened.approval.approved_at.max(1) as u64, + }, + }) + }; + if host_initiated { + self.in_host_namespace(caller, resolve).await + } else { + self.in_namespace(caller, resolve).await + } + } + + async fn runtime_proto( + &self, + caller: &ResourceCaller, + context: &ServiceContext, + runtime: RuntimeResource, + ) -> Result { + self.providers + .authorize_resource(Some(context), cap::FILES_READ)?; + let executable_handle = self + .session_handle(caller, runtime.executable.clone()) + .await?; + let extensions = runtime_extension_proto(&runtime.extensions)?; + let descriptors = self + .providers + .extension_schemas_for_provider(&caller.provider_id); + for (namespace, payload) in &extensions { + if let Some(descriptor) = descriptors + .iter() + .find(|schema| schema.namespace == *namespace) + { + gamenode_plugin_protocol::extensions::validate_payload_for_schema( + payload, descriptor, + ) + .map_err(|_| { + Status::internal("stored runtime extension does not match its signed schema") + })?; + } + } + Ok(RuntimeRecord { + id: runtime.id, + name: runtime.name, + version: runtime.version, + executable_handle, + supported_formats: runtime.supported_formats, + revision: runtime.revision, + observed_at: runtime.observed_at, + platform: runtime.platform, + argument_template: proto_arguments(&runtime.launch_arguments), + extensions, + provenance: runtime_provenance_proto(&runtime.provenance), + }) + } + + /// Shared catalog projection: no executable handle, approval or private owner key is exposed. + fn runtime_proto_shared(runtime: RuntimeResource) -> Result { + Ok(RuntimeRecord { + id: runtime.id, + name: runtime.name, + version: runtime.version, + executable_handle: String::new(), + supported_formats: runtime.supported_formats, + revision: runtime.revision, + observed_at: runtime.observed_at, + platform: runtime.platform, + argument_template: proto_arguments(&runtime.launch_arguments), + extensions: runtime_extension_proto(&runtime.extensions)?, + provenance: runtime_provenance_proto(&runtime.provenance), + }) + } + + /// Returns whether this query explicitly selected the runtime catalog category and is + /// currently granted. An empty selector keeps the query owner-private. + fn shared_runtime_read( + &self, + caller: &ResourceCaller, + selector: Option<&CommonDataSelector>, + ) -> Result { + validate_common_selector(selector)?; + let Some(selector) = selector.filter(|selector| !selector.categories.is_empty()) else { + return Ok(false); + }; + let recipient = caller + .namespace + .as_ref() + .map(|namespace| namespace.identity().clone()) + .ok_or_else(|| { + Status::failed_precondition( + "a third-party plugin identity is required for shared catalog reads", + ) + })?; + let fields = SHARED_RUNTIME_FIELDS + .iter() + .map(|field| (*field).to_owned()) + .collect::>(); + let decision: AccessDecision = self.shared_authorizer.common_category( + &recipient, + CommonDataCategory::RuntimeCatalog, + &fields, + ); + if !decision.allowed { + return Err(Status::permission_denied( + "common runtime catalog access is not granted", + )); + } + debug_assert_eq!( + selector.categories, + [CommonDataCategory::RuntimeCatalog as i32] + ); + Ok(true) + } + + /// Resolves a recipe's runtime and selected binding under the authenticated plugin owner. + /// All durable file refs are revalidated against current FILES_READ consent before any path + /// reaches the engine worker. + pub(super) async fn resolve_runtime_launch( + &self, + caller: &ResourceCaller, + context: Option<&ServiceContext>, + game_id: u64, + installation_id: &str, + runtime_id: &str, + content_id: &str, + ) -> Result { + if !valid_id(runtime_id) { + return Err(Status::invalid_argument("runtime id is required")); + } + if let Some(context) = context { + self.providers + .authorize_resource(Some(context), cap::FILES_READ)?; + } else if !caller.has(cap::FILES_READ) { + return Err(Status::permission_denied( + "file read permission is required", + )); + } + let owner = mutation_owner(caller); + let host = self.library.host().ok_or_else(unavailable)?; + let runtime = host + .runtime_resource(owner.clone(), runtime_id.to_owned()) + .await? + .ok_or_else(|| Status::not_found("runtime not found"))?; + let platform = current_platform(); + if runtime.platform != platform { + return Err(Status::unimplemented( + "the registered runtime targets a different platform", + )); + } + let executable = self + .resolve_reference_path( + caller, + runtime.executable.clone(), + None, + context.is_none(), + Some(runtime.id.clone()), + ) + .await?; + let mut resources = vec![executable.resource.clone()]; + let mut content_path = None; + let mut binding_revision = None; + if content_id.is_empty() { + if runtime + .launch_arguments + .iter() + .any(|argument| matches!(argument, CoreArgument::ContentPath)) + { + return Err(Status::failed_precondition( + "this runtime recipe requires a registered content binding", + )); + } + } else { + let bindings = host + .runtime_content_bindings(owner, game_id, installation_id.to_owned()) + .await?; + let binding = bindings + .into_iter() + .find(|binding| { + binding.content_id == content_id && binding.runtime_id == runtime_id + }) + .ok_or_else(|| Status::not_found("runtime content binding not found"))?; + if !runtime.supported_formats.contains(&binding.content_kind) { + return Err(Status::failed_precondition( + "the runtime does not support this content kind", + )); + } + if !binding.supported_platforms.is_empty() + && !binding + .supported_platforms + .iter() + .any(|value| value == platform) + { + return Err(Status::failed_precondition( + "the content binding does not support this platform", + )); + } + binding_revision = Some(binding.revision); + let content = self + .resolve_reference_path( + caller, + binding.content, + Some((game_id, installation_id.to_owned())), + context.is_none(), + None, + ) + .await?; + resources.push(content.resource); + content_path = Some(content.path); + } + if let Some(context) = context { + self.authorize_commit(context, cap::FILES_READ, caller.grant_revision)?; + } + let files = self.files.clone(); + let feed = self.library.clone(); + let installation = installation_id.to_owned(); + let runtime_key = runtime.id.clone(); + let lease_keys = if caller.namespace.is_some() { + self.in_namespace(caller, move |namespace| { + let mut keys = std::collections::BTreeSet::new(); + for profile in namespace.save_profiles()?.into_iter().filter(|profile| { + profile.installation_id == installation && profile.runtime_id == runtime_key + }) { + let prepared = crate::plugin_host::shared_resources::prepare_for_use( + &files, &feed, namespace, &profile, + )?; + keys.extend(prepared.into_iter().map(|resource| resource.lease_key)); + } + Ok(keys.into_iter().collect()) + }) + .await? + } else { + Vec::new() + }; + Ok(crate::plugin_host::library::ResolvedRuntimeLaunch { + runtime_id: runtime.id, + version: runtime.version, + platform: runtime.platform, + executable: executable.path, + content_id: content_id.to_owned(), + content_path, + runtime_revision: runtime.revision, + binding_revision, + arguments: runtime.launch_arguments, + resources, + lease_keys, + }) + } + + /// Resolves one approved runtime's executable identity for external-process checks. + pub(super) async fn resolve_runtime_executable( + &self, + caller: &ResourceCaller, + runtime_id: &str, + ) -> Result { + if !valid_id(runtime_id) { + return Err(Status::failed_precondition( + "the approved runtime binding is invalid", + )); + } + let owner = mutation_owner(caller); + let host = self + .library + .host() + .ok_or_else(|| Status::unavailable("runtime resources are unavailable"))?; + let runtime = host + .runtime_resource(owner, runtime_id.to_owned()) + .await? + .ok_or_else(|| Status::unavailable("the approved runtime binding is unavailable"))?; + let resolved = self + .resolve_reference_path( + caller, + runtime.executable, + None, + false, + Some(runtime.id.clone()), + ) + .await?; + Ok(resolved.path) + } + + #[allow(clippy::too_many_arguments)] // Runtime creation inputs plus the approval and provenance fields. + fn runtime_core( + request: RuntimeRecord, + executable: ApprovedFileReference, + id: String, + revision: u64, + observed_at: i64, + provenance: RuntimeProvenance, + extensions: BTreeMap, + require_executable_handle: bool, + ) -> Result { + runtime_request_shape(&request, require_executable_handle)?; + let runtime = RuntimeResource { + id, + name: request.name, + version: request.version, + executable, + platform: request.platform, + supported_formats: request.supported_formats, + launch_arguments: core_arguments(&request.argument_template)?, + revision, + observed_at, + provenance, + extensions, + }; + if runtime.validate() { + Ok(runtime) + } else { + Err(Status::invalid_argument("invalid runtime resource")) + } + } + + fn authorize_runtime_namespaces<'a>( + caller: &ResourceCaller, + namespaces: impl IntoIterator, + ) -> Result<(), Status> { + let namespaces: Vec<_> = namespaces.into_iter().collect(); + if namespaces.is_empty() { + return Ok(()); + } + let plugin_id = caller + .namespace + .as_ref() + .map(|namespace| namespace.identity().plugin_id.as_str()) + .ok_or_else(|| { + Status::permission_denied("runtime extensions require a plugin owner") + })?; + if namespaces.into_iter().any(|namespace| { + namespace != plugin_id && !namespace.starts_with(&format!("{plugin_id}.")) + }) { + return Err(Status::permission_denied( + "runtime extension namespace is not owned by this plugin", + )); + } + Ok(()) + } + + pub(super) async fn list_runtimes( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + let page = request.page.unwrap_or_default(); + let context = page + .context + .clone() + .ok_or_else(|| Status::unauthenticated("resource context required"))?; + let caller = self + .providers + .authorize_resource(page.context.as_ref(), cap::GAME_RUNTIME_READ)?; + self.providers + .authorize_resource(page.context.as_ref(), cap::FILES_READ)?; + let shared = self.shared_runtime_read(&caller, page.common_data_categories.as_ref())?; + if !request.kind.is_empty() && request.kind != "runtime" { + return Err(Status::invalid_argument("unsupported runtime kind")); + } + if !request.owner_filter.is_empty() && request.owner_filter != caller.provider_id { + return Err(Status::permission_denied( + "foreign runtime scope is not granted", + )); + } + let owner = mutation_owner(&caller); + let host = self.library.host().ok_or_else(unavailable)?; + let mut revision = if shared { + host.shared_runtime_catalog_revision().await? + } else { + host.runtime_catalog_revision(owner.clone()).await? + }; + let mut records = host + .runtime_resources(owner.clone()) + .await? + .into_iter() + .map(|runtime| (false, runtime)) + .collect::>(); + if shared { + records.extend( + host.shared_runtime_resources() + .await? + .into_iter() + .filter(|(owner_key, _)| *owner_key != owner) + .map(|(_, runtime)| (true, runtime)), + ); + } + let reread = if shared { + host.shared_runtime_catalog_revision().await? + } else { + host.runtime_catalog_revision(owner.clone()).await? + }; + if reread != revision { + revision = reread; + records = host + .runtime_resources(owner.clone()) + .await? + .into_iter() + .map(|runtime| (false, runtime)) + .collect(); + if shared { + records.extend( + host.shared_runtime_resources() + .await? + .into_iter() + .filter(|(owner_key, _)| *owner_key != owner) + .map(|(_, runtime)| (true, runtime)), + ); + } + } + records.sort_by(|left, right| { + left.1 + .id + .cmp(&right.1.id) + .then_with(|| left.0.cmp(&right.0)) + }); + let limit = match page.page_size as usize { + 0 => DEFAULT_PAGE_SIZE, + size => size.min(MAX_PAGE_SIZE), + }; + let binding = CursorBinding { + route: "runtimes", + session_id: caller.session_id.clone(), + profile_epoch: caller.profile_epoch, + grant_revision: caller.grant_revision, + scope: Scope { + own_provider: caller.provider_id.clone(), + // Reused as the shared-catalog marker for this route so a private cursor cannot + // resume a category query, and vice versa. + read_all: shared, + provider_filter: None, + }, + search: None, + }; + let after = if page.cursor.is_empty() { + None + } else { + let (after, issued) = + self.library + .open_cursor(&page.cursor, &binding) + .map_err(|error| match error { + CursorError::Malformed => { + Status::invalid_argument("invalid runtime cursor") + } + CursorError::Stale => super::stale_cursor(), + })?; + if issued != revision { + return Err(super::stale_cursor()); + } + Some(after) + }; + let mut remaining = records + .into_iter() + .filter(|record| after.as_ref().is_none_or(|after| record.1.id > *after)); + let selected = remaining.by_ref().take(limit).collect::>(); + let more = remaining.next().is_some(); + let next_cursor = match selected.last().filter(|_| more) { + Some(last) => self.library.issue_cursor(&binding, revision, &last.1.id), + None => String::new(), + }; + let mut runtimes = Vec::with_capacity(selected.len()); + for (is_shared, record) in selected { + runtimes.push(if is_shared { + Self::runtime_proto_shared(record)? + } else { + self.runtime_proto(&caller, &context, record).await? + }); + } + self.providers + .authorize_resource(page.context.as_ref(), cap::GAME_RUNTIME_READ)?; + Ok(Response::new(RuntimesListReply { + runtimes, + next_cursor, + revision, + })) + } + + pub(super) async fn get_runtime( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + let context = request + .context + .clone() + .ok_or_else(|| Status::unauthenticated("resource context required"))?; + let caller = self + .providers + .authorize_resource(request.context.as_ref(), cap::GAME_RUNTIME_READ)?; + self.providers + .authorize_resource(request.context.as_ref(), cap::FILES_READ)?; + let shared = self.shared_runtime_read(&caller, request.shared_records.as_ref())?; + if !valid_id(&request.resource_id) { + return Err(Status::invalid_argument("runtime id is required")); + } + let host = self.library.host().ok_or_else(unavailable)?; + let owner = mutation_owner(&caller); + if let Some(runtime) = host + .runtime_resource(owner.clone(), request.resource_id.clone()) + .await? + { + if request.expected_revision != 0 && request.expected_revision != runtime.revision { + return Err(Status::aborted("runtime revision changed")); + } + let runtime = self.runtime_proto(&caller, &context, runtime).await?; + self.providers + .authorize_resource(request.context.as_ref(), cap::GAME_RUNTIME_READ)?; + return Ok(Response::new(RuntimeRecordReply { + revision: runtime.revision, + runtime: Some(runtime), + })); + } + if !shared { + return Err(Status::not_found("runtime not found")); + } + let mut matches = host + .shared_runtime_resources() + .await? + .into_iter() + .filter(|(owner_key, runtime)| *owner_key != owner && runtime.id == request.resource_id) + .map(|(_, runtime)| runtime) + .collect::>(); + match matches.len() { + 0 => Err(Status::not_found("runtime not found")), + 1 => { + let runtime = Self::runtime_proto_shared(matches.remove(0))?; + if request.expected_revision != 0 && request.expected_revision != runtime.revision { + return Err(Status::aborted("runtime revision changed")); + } + self.providers + .authorize_resource(request.context.as_ref(), cap::GAME_RUNTIME_READ)?; + Ok(Response::new(RuntimeRecordReply { + revision: runtime.revision, + runtime: Some(runtime), + })) + } + _ => Err(Status::failed_precondition( + "several shared runtimes use this id; list the catalog instead", + )), + } + } + + /// The host-side name/platform/formats identity a runtime request reuses. + fn same_runtime_shape(existing: &RuntimeResource, request: &RuntimeRecord) -> bool { + let mut left = existing.supported_formats.clone(); + left.sort(); + left.dedup(); + let mut right = request.supported_formats.clone(); + right.sort(); + right.dedup(); + existing.name == request.name && existing.platform == request.platform && left == right + } + + /// Lets the user approve one exact program for an owned runtime. The plugin sends a spec and + /// text hints only; every path stays in the host. + pub(super) async fn request_runtime_access( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + let mutation = request + .mutation + .as_ref() + .ok_or_else(|| Status::invalid_argument("mutation is required"))?; + let context = mutation + .context + .as_ref() + .ok_or_else(|| Status::invalid_argument("context is required"))?; + let caller = self + .providers + .authorize_resource(Some(context), cap::GAME_RUNTIME_CREATE)?; + if caller.namespace.is_none() { + return Err(Status::failed_precondition( + "official providers use trusted host adapters", + )); + } + let key = mutation_key(mutation)?; + let runtime_request = request + .runtime + .ok_or_else(|| Status::invalid_argument("runtime is required"))?; + if !runtime_request.executable_handle.is_empty() { + return Err(Status::invalid_argument( + "the host chooses the runtime executable; executable_handle must be empty", + )); + } + runtime_request_shape(&runtime_request, false)?; + if !runtime_request.id.is_empty() && !valid_id(&runtime_request.id) { + return Err(Status::invalid_argument("invalid runtime id")); + } + let hints = request.hints.unwrap_or_default(); + let hints = RuntimeHints { + executable_names: hints.executable_names, + desktop_ids: hints.desktop_ids, + }; + if !hints.validate() { + return Err(Status::invalid_argument("invalid runtime executable hints")); + } + let extensions = runtime_extension_payloads(&runtime_request)?; + let hash = request_hash(&[ + "runtime-request-access", + &runtime_request.id, + &runtime_request.name, + &runtime_request.version, + "", + &runtime_request.platform, + &runtime_request.supported_formats.join("\0"), + &format!("{:?}", runtime_request.argument_template), + &format!("{:?}", extensions), + &hints.executable_names.join("\0"), + &hints.desktop_ids.join("\0"), + &mutation.expected_revision.to_string(), + ]); + { + let lock = self.mutations.lock.lock().await; + if let Some(replay) = self.mutations.replay(&caller, key, hash)? { + let runtime = self + .library + .host() + .ok_or_else(unavailable)? + .runtime_resource(mutation_owner(&caller), replay.resource_id.clone()) + .await? + .ok_or_else(|| Status::not_found("runtime not found"))?; + drop(lock); + return Ok(Response::new(RuntimeMutationReply { + runtime: Some(Self::runtime_proto_shared(runtime)?), + outcome: replay.outcome, + })); + } + } + + let host = self.library.host().ok_or_else(unavailable)?; + let owner = mutation_owner(&caller); + let runtimes = host.runtime_resources(owner.clone()).await?; + let existing = if runtime_request.id.is_empty() { + runtimes + .iter() + .find(|runtime| Self::same_runtime_shape(runtime, &runtime_request)) + .cloned() + } else { + runtimes + .iter() + .find(|runtime| runtime.id == runtime_request.id) + .cloned() + }; + if let Some(current) = existing.as_ref() { + if mutation.expected_revision != 0 && current.revision != mutation.expected_revision { + return Ok(Response::new(RuntimeMutationReply { + runtime: None, + outcome: MutationOutcome::RevisionConflict as i32, + })); + } + let runtime_id = current.id.clone(); + let approval = self + .in_namespace(&caller, move |namespace| { + namespace.runtime_approval_for(&runtime_id) + }) + .await?; + let reserved = self.files.reserved.clone(); + let valid = match approval { + Some(approval) => tokio::task::spawn_blocking(move || { + validate_approval(&approval, &reserved).is_ok() + }) + .await + .unwrap_or(false), + None => { + // A runtime registered from an already approved file handle stays reusable: + // resolve it once with the same checks a launch would apply. + self.resolve_reference_path( + &caller, + current.executable.clone(), + None, + false, + Some(current.id.clone()), + ) + .await + .is_ok() + } + }; + if valid { + let reply = super::mutations::reply( + ¤t.id, + current.revision, + MutationOutcome::AlreadyApplied, + ); + let lock = self.mutations.lock.lock().await; + self.mutations.remember(&caller, key, hash, &reply); + drop(lock); + return Ok(Response::new(RuntimeMutationReply { + runtime: Some(Self::runtime_proto_shared(current.clone())?), + outcome: MutationOutcome::AlreadyApplied as i32, + })); + } + } else if mutation.expected_revision != 0 { + return Ok(Response::new(RuntimeMutationReply { + runtime: None, + outcome: MutationOutcome::RevisionConflict as i32, + })); + } + + let resolver = caller.namespace.as_ref().ok_or_else(|| { + Status::failed_precondition("official providers use trusted host adapters") + })?; + let identity = resolver.identity().clone(); + let _waiting = self + .files + .begin_approval(*resolver.storage_owner().key()) + .ok_or_else(|| Status::aborted("a plugin approval is already waiting for the user"))?; + let approver = self.files.runtime_approver().ok_or_else(|| { + Status::failed_precondition("runtime approval is not available in this build") + })?; + let programs = match self.library.host() { + Some(host) => host.installed_programs().await.unwrap_or_default(), + None => Vec::new(), + }; + let candidates = suggestions(&programs, &hints); + let chosen = tokio::time::timeout( + APPROVAL_TIMEOUT, + approver.choose_executable(RuntimeAccessRequest { + plugin_id: identity.plugin_id.clone(), + publisher_fingerprint: identity.publisher_fingerprint.clone(), + runtime_name: runtime_request.name.clone(), + runtime_version: runtime_request.version.clone(), + platform: runtime_request.platform.clone(), + supported_formats: runtime_request.supported_formats.clone(), + hints: hints.clone(), + candidates, + }), + ) + .await + .map_err(|_| Status::deadline_exceeded("the user did not answer in time"))?? + .ok_or_else(|| { + Status::permission_denied("the user declined to approve a runtime program") + })?; + + // The user took their time: the grants and the account profile may have changed. + let fresh = self + .providers + .authorize_resource(Some(context), cap::GAME_RUNTIME_CREATE)?; + if fresh.profile_epoch != caller.profile_epoch { + return Err(Status::failed_precondition( + "account profile changed while the approval was open", + )); + } + let fresh_identity = fresh + .namespace + .as_ref() + .map(|namespace| namespace.identity().clone()) + .ok_or_else(|| Status::failed_precondition("the plugin identity changed"))?; + if fresh_identity != identity { + return Err(Status::failed_precondition("the plugin identity changed")); + } + let reserved = self.files.reserved.clone(); + let inspected = tokio::task::spawn_blocking(move || inspect_executable(&chosen, &reserved)) + .await + .map_err(|_| Status::internal("the program could not be inspected"))??; + + let mut approval_bytes = [0_u8; 16]; + getrandom::fill(&mut approval_bytes) + .map_err(|_| Status::internal("no source of randomness"))?; + let approval_id: String = approval_bytes + .iter() + .map(|byte| format!("{byte:02x}")) + .collect(); + let runtime_id = match existing.as_ref() { + Some(current) => current.id.clone(), + None if runtime_request.id.is_empty() => format!("runtime-{}", runtime_id()?), + None => runtime_request.id.clone(), + }; + let now = unix_now(); + let approval = RuntimeApproval { + id: approval_id.clone(), + runtime_id: runtime_id.clone(), + path: inspected.path, + volume: inspected.volume, + node: inspected.node, + size: inspected.size, + digest: inspected.digest, + approved_at: now, + revoked_at: None, + }; + let revision = existing + .as_ref() + .map(|current| current.revision.saturating_add(1)) + .unwrap_or(1); + let core = Self::runtime_core( + runtime_request.clone(), + ApprovedFileReference { + approval_id, + relative_path: Vec::new(), + }, + runtime_id.clone(), + revision, + now, + runtime_provenance(&caller), + extensions, + false, + )?; + self.authorize_commit(context, cap::GAME_RUNTIME_CREATE, caller.grant_revision)?; + let result = host.save_runtime_resource(owner.clone(), core).await?; + let (outcome, revision, commit) = mutation_outcome(result); + if !commit { + let reply = super::mutations::reply(&runtime_id, revision, outcome); + return Ok(Response::new(RuntimeMutationReply { + runtime: None, + outcome: reply.outcome, + })); + } + let profiles = self.providers.profiles(); + let epoch = fresh.profile_epoch; + let guard: crate::plugin_host::library::CommitGuard = Box::new(move || { + if profiles.epoch() == epoch { + Ok(()) + } else { + Err(Status::failed_precondition("account profile changed")) + } + }); + self.in_namespace(&fresh, move |namespace| { + namespace.save_runtime_approval(&approval, &guard) + }) + .await?; + let reply = super::mutations::reply(&runtime_id, revision, outcome); + { + let lock = self.mutations.lock.lock().await; + if let Some(replay) = self.mutations.replay(&fresh, key, hash)? { + drop(lock); + let replay_runtime = host + .runtime_resource(owner, replay.resource_id.clone()) + .await? + .ok_or_else(|| Status::not_found("runtime not found"))?; + return Ok(Response::new(RuntimeMutationReply { + runtime: Some(Self::runtime_proto_shared(replay_runtime)?), + outcome: replay.outcome, + })); + } + self.mutations.remember(&fresh, key, hash, &reply); + } + let saved = host + .runtime_resource(owner, runtime_id) + .await? + .ok_or_else(|| Status::internal("saved runtime disappeared"))?; + Ok(Response::new(RuntimeMutationReply { + runtime: Some(Self::runtime_proto_shared(saved)?), + outcome: outcome as i32, + })) + } + + pub(super) async fn register_runtime( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + let mutation = request + .mutation + .as_ref() + .ok_or_else(|| Status::invalid_argument("mutation is required"))?; + let context = mutation + .context + .as_ref() + .ok_or_else(|| Status::invalid_argument("context is required"))?; + let caller = self + .providers + .authorize_resource(Some(context), cap::GAME_RUNTIME_CREATE)?; + let key = mutation_key(mutation)?; + if mutation.expected_revision != 0 { + return Err(Status::invalid_argument( + "runtime registration expected_revision must be 0", + )); + } + let mut runtime_request = request + .runtime + .ok_or_else(|| Status::invalid_argument("runtime is required"))?; + runtime_request_shape(&runtime_request, true)?; + let extensions = runtime_extension_payloads(&runtime_request)?; + let request_id = runtime_request.id.clone(); + let hash = request_hash(&[ + "runtime-register", + &request_id, + &runtime_request.name, + &runtime_request.version, + &runtime_request.executable_handle, + &runtime_request.platform, + &runtime_request.supported_formats.join("\0"), + &format!("{:?}", runtime_request.argument_template), + &format!("{:?}", extensions), + &mutation.expected_revision.to_string(), + ]); + let lock = self.mutations.lock.lock().await; + if let Some(replay) = self.mutations.replay(&caller, key, hash)? { + let runtime = self + .library + .host() + .ok_or_else(unavailable)? + .runtime_resource(mutation_owner(&caller), replay.resource_id.clone()) + .await? + .ok_or_else(|| Status::not_found("runtime not found"))?; + return Ok(Response::new(RuntimeMutationReply { + runtime: Some(self.runtime_proto(&caller, context, runtime).await?), + outcome: replay.outcome, + })); + } + let id = if request_id.is_empty() { + format!("runtime-{}", runtime_id()?) + } else { + request_id + }; + self.providers + .authorize_resource(Some(context), cap::FILES_READ)?; + let executable = self + .capture_reference(&caller, runtime_request.executable_handle.clone(), None) + .await?; + let core = Self::runtime_core( + runtime_request.clone(), + executable, + id.clone(), + 1, + unix_now(), + runtime_provenance(&caller), + extensions, + true, + )?; + let host = self.library.host().ok_or_else(unavailable)?; + self.authorize_commit(context, cap::GAME_RUNTIME_CREATE, caller.grant_revision)?; + self.authorize_commit(context, cap::FILES_READ, caller.grant_revision)?; + let result = host + .save_runtime_resource(mutation_owner(&caller), core) + .await?; + let (outcome, revision, commit) = mutation_outcome(result); + let reply = super::mutations::reply(&id, revision, outcome); + if commit { + self.mutations.remember(&caller, key, hash, &reply); + runtime_request.id = id.clone(); + runtime_request.revision = revision; + runtime_request.observed_at = unix_now(); + let record = self + .library + .host() + .ok_or_else(unavailable)? + .runtime_resource(mutation_owner(&caller), id.clone()) + .await? + .ok_or_else(|| Status::internal("saved runtime disappeared"))?; + drop(lock); + return Ok(Response::new(RuntimeMutationReply { + runtime: Some(self.runtime_proto(&caller, context, record).await?), + outcome: outcome as i32, + })); + } + drop(lock); + Ok(Response::new(RuntimeMutationReply { + runtime: None, + outcome: outcome as i32, + })) + } + + fn validate_package_extensions( + providers: &super::super::provider::ProviderApi, + caller: &ResourceCaller, + extensions: &std::collections::HashMap, + ) -> Result<(), Status> { + let descriptors = providers.extension_schemas_for_provider(&caller.provider_id); + for (namespace, payload) in extensions { + if let Some(descriptor) = descriptors + .iter() + .find(|schema| schema.namespace == *namespace) + { + gamenode_plugin_protocol::extensions::validate_payload_for_schema( + payload, descriptor, + ) + .map_err(|_| { + Status::invalid_argument( + "runtime extension does not match its signed package schema", + ) + })?; + } + } + Ok(()) + } + + pub(super) async fn update_runtime( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + let mutation = request + .mutation + .as_ref() + .ok_or_else(|| Status::invalid_argument("mutation is required"))?; + let context = mutation + .context + .as_ref() + .ok_or_else(|| Status::invalid_argument("context is required"))?; + let caller = self + .providers + .authorize_resource(Some(context), cap::GAME_RUNTIME_UPDATE)?; + let key = mutation_key(mutation)?; + let mut runtime_request = request + .runtime + .ok_or_else(|| Status::invalid_argument("runtime is required"))?; + runtime_request_shape(&runtime_request, false)?; + if !valid_id(&runtime_request.id) || mutation.expected_revision == 0 { + return Err(Status::invalid_argument( + "runtime id and expected_revision are required", + )); + } + let known = [ + "name", + "version", + "executable_handle", + "platform", + "supported_formats", + "argument_template", + "extensions", + ]; + let mut mask = HashSet::new(); + let mut patch_mask = HashSet::new(); + if let Some(patch) = request.extension_patch.as_ref() { + patch_mask.extend(patch.typed_field_mask.iter().map(String::as_str)); + } + if (request.field_mask.is_empty() && request.extension_patch.is_none()) + || request + .field_mask + .iter() + .any(|field| !known.contains(&field.as_str()) || !mask.insert(field.as_str())) + { + return Err(Status::invalid_argument("invalid runtime field_mask")); + } + if mask.contains("executable_handle") && runtime_request.executable_handle.is_empty() { + return Err(Status::invalid_argument( + "executable_handle is required by field_mask", + )); + } + let hash = request_hash(&[ + "runtime-update", + &runtime_request.id, + &mutation.expected_revision.to_string(), + &request.field_mask.join("\0"), + &runtime_request.name, + &runtime_request.version, + &runtime_request.executable_handle, + &runtime_request.platform, + &runtime_request.supported_formats.join("\0"), + &format!("{:?}", runtime_request.argument_template), + &format!("{:?}", runtime_request.extensions), + ]); + let lock = self.mutations.lock.lock().await; + if let Some(replay) = self.mutations.replay(&caller, key, hash)? { + let runtime = self + .library + .host() + .ok_or_else(unavailable)? + .runtime_resource(mutation_owner(&caller), replay.resource_id.clone()) + .await? + .ok_or_else(|| Status::not_found("runtime not found"))?; + return Ok(Response::new(RuntimeMutationReply { + runtime: Some(self.runtime_proto(&caller, context, runtime).await?), + outcome: replay.outcome, + })); + } + let host = self.library.host().ok_or_else(unavailable)?; + let owner = mutation_owner(&caller); + let Some(current) = host + .runtime_resource(owner.clone(), runtime_request.id.clone()) + .await? + else { + return Err(Status::not_found("runtime not found")); + }; + if current.revision != mutation.expected_revision { + return Ok(Response::new(RuntimeMutationReply { + runtime: None, + outcome: MutationOutcome::RevisionConflict as i32, + })); + } + let mut extensions = current.extensions.clone(); + if let Some(patch) = request.extension_patch.as_ref() { + Self::authorize_runtime_namespaces( + &caller, + patch.namespaces.iter().map(|change| &change.namespace), + )?; + let current_wire = RuntimeRecord { + id: current.id.clone(), + name: current.name.clone(), + version: current.version.clone(), + supported_formats: current.supported_formats.clone(), + revision: current.revision, + extensions: runtime_extension_proto(¤t.extensions)?, + ..Default::default() + }; + let proposed_wire = RuntimeRecord { + id: current.id.clone(), + name: runtime_request.name.clone(), + version: runtime_request.version.clone(), + supported_formats: runtime_request.supported_formats.clone(), + extensions: current_wire.extensions.clone(), + ..Default::default() + }; + let applied = gamenode_plugin_protocol::extensions::apply_runtime_patch( + ¤t_wire, + &proposed_wire, + patch, + ) + .map_err(|_| Status::invalid_argument("invalid or stale runtime extension patch"))?; + Self::validate_package_extensions(&self.providers, &caller, &applied.extensions)?; + extensions = runtime_extension_payloads(&applied)?; + runtime_request.name = applied.name; + runtime_request.version = applied.version; + runtime_request.supported_formats = applied.supported_formats; + } else if !runtime_request.extensions.is_empty() { + return Err(Status::invalid_argument( + "runtime extensions require a revision-checked extension_patch", + )); + } + let executable = if mask.contains("executable_handle") { + self.providers + .authorize_resource(Some(context), cap::FILES_READ)?; + Some( + self.capture_reference(&caller, runtime_request.executable_handle.clone(), None) + .await?, + ) + } else { + None + }; + let updated = RuntimeResource { + id: current.id.clone(), + name: if mask.contains("name") || patch_mask.contains("name") { + runtime_request.name + } else { + current.name + }, + version: if mask.contains("version") || patch_mask.contains("version") { + runtime_request.version + } else { + current.version + }, + executable: executable.unwrap_or(current.executable), + platform: if mask.contains("platform") { + runtime_request.platform + } else { + current.platform + }, + supported_formats: if mask.contains("supported_formats") + || patch_mask.contains("supported_formats") + { + runtime_request.supported_formats + } else { + current.supported_formats + }, + launch_arguments: if mask.contains("argument_template") { + core_arguments(&runtime_request.argument_template)? + } else { + current.launch_arguments + }, + extensions, + revision: current.revision.saturating_add(1), + observed_at: unix_now(), + provenance: current.provenance, + }; + if !updated.validate() { + return Err(Status::invalid_argument("invalid runtime resource")); + } + self.authorize_commit(context, cap::GAME_RUNTIME_UPDATE, caller.grant_revision)?; + if mask.contains("executable_handle") { + self.authorize_commit(context, cap::FILES_READ, caller.grant_revision)?; + } + let result = host.save_runtime_resource(owner.clone(), updated).await?; + let (outcome, revision, commit) = mutation_outcome(result); + let reply = super::mutations::reply(&runtime_request.id, revision, outcome); + if commit { + self.mutations.remember(&caller, key, hash, &reply); + runtime_request.revision = revision; + runtime_request.observed_at = unix_now(); + let updated = host + .runtime_resource(owner, runtime_request.id.clone()) + .await? + .ok_or_else(|| Status::internal("updated runtime disappeared"))?; + drop(lock); + return Ok(Response::new(RuntimeMutationReply { + runtime: Some(self.runtime_proto(&caller, context, updated).await?), + outcome: outcome as i32, + })); + } + drop(lock); + Ok(Response::new(RuntimeMutationReply { + runtime: None, + outcome: outcome as i32, + })) + } + + pub(super) async fn remove_runtime( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + let mutation = request + .mutation + .as_ref() + .ok_or_else(|| Status::invalid_argument("mutation is required"))?; + let context = mutation + .context + .as_ref() + .ok_or_else(|| Status::invalid_argument("context is required"))?; + let caller = self + .providers + .authorize_resource(Some(context), cap::GAME_RUNTIME_DELETE)?; + let key = mutation_key(mutation)?; + if !valid_id(&request.resource_id) || mutation.expected_revision == 0 { + return Err(Status::invalid_argument( + "runtime id and expected_revision are required", + )); + } + let hash = request_hash(&[ + "runtime-remove", + &request.resource_id, + &mutation.expected_revision.to_string(), + ]); + let lock = self.mutations.lock.lock().await; + if let Some(replay) = self.mutations.replay(&caller, key, hash)? { + return Ok(Response::new(replay)); + } + let host = self.library.host().ok_or_else(unavailable)?; + let owner = mutation_owner(&caller); + if host + .runtime_resource(owner.clone(), request.resource_id.clone()) + .await? + .is_none() + { + return Err(Status::not_found("runtime not found")); + } + self.authorize_commit(context, cap::GAME_RUNTIME_DELETE, caller.grant_revision)?; + let result = host + .remove_runtime_resource( + owner, + request.resource_id.clone(), + mutation.expected_revision, + ) + .await?; + let (outcome, revision, commit) = mutation_outcome(result); + let reply = super::mutations::reply(&request.resource_id, revision, outcome); + if commit { + self.mutations.remember(&caller, key, hash, &reply); + } + drop(lock); + if commit && caller.namespace.is_some() { + let runtime_id = request.resource_id.clone(); + let _ = self + .in_namespace(&caller, move |namespace| { + namespace.revoke_runtime_approval(&runtime_id) + }) + .await; + } + Ok(Response::new(reply)) + } + + pub(super) async fn register_content( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + let mutation = request + .mutation + .as_ref() + .ok_or_else(|| Status::invalid_argument("mutation is required"))?; + let context = mutation + .context + .as_ref() + .ok_or_else(|| Status::invalid_argument("context is required"))?; + let caller = self + .providers + .authorize_resource(Some(context), cap::DISCOVERY)?; + // A discovery grant authorizes submitting observations, but it does not authorize + // reading a content file. Require the independent file grant before resolving game or + // runtime records, so discovery-only callers cannot probe those namespaces. + self.providers + .authorize_resource(Some(context), cap::FILES_READ)?; + let key = mutation_key(mutation)?; + if !valid_id(&request.installation_id) + || !valid_id(&request.content_kind) + || !valid_id(&request.runtime_id) + || request.supported_platforms.len() > 128 + || request + .supported_platforms + .iter() + .any(|platform| !valid_id(platform)) + { + return Err(Status::invalid_argument("invalid runtime content binding")); + } + let game_id = super::mutations::game_id(&request.game_id)? + .ok_or_else(|| Status::invalid_argument("game_id is required"))?; + let context_target = + self.action_target(&caller, context, &request.game_id, &request.installation_id)?; + let (_entry_key, entry) = context_target; + if entry.game_id != Some(game_id) { + return Err(Status::not_found("library game not found")); + } + let owner = mutation_owner(&caller); + let host = self.library.host().ok_or_else(unavailable)?; + if host + .runtime_resource(owner.clone(), request.runtime_id.clone()) + .await? + .is_none() + { + return Err(Status::not_found("runtime not found")); + } + if !request.content_id.is_empty() && !valid_id(&request.content_id) { + return Err(Status::invalid_argument("invalid content_id")); + } + let all_bindings = host + .runtime_content_bindings(owner.clone(), game_id, request.installation_id.clone()) + .await?; + // A stable content id can have been selected from another runtime's discovery. Accept + // that identity as a new owner-scoped binding after validating this caller's game, + // installation and approved file handle; never read or mutate the foreign binding row. + let requested_content_id = request.content_id.clone(); + let hash = request_hash(&[ + "runtime-content-register", + &game_id.to_string(), + &request.installation_id, + &requested_content_id, + &request.content_handle, + &request.content_kind, + &request.runtime_id, + &request.supported_platforms.join("\0"), + &mutation.expected_revision.to_string(), + ]); + let lock = self.mutations.lock.lock().await; + if let Some(replay) = self.mutations.replay(&caller, key, hash)? { + return Ok(Response::new(replay)); + } + let content_id = if requested_content_id.is_empty() { + format!("content-{}", runtime_id()?) + } else { + requested_content_id + }; + let content = self + .capture_reference( + &caller, + request.content_handle.clone(), + Some((game_id, request.installation_id.clone())), + ) + .await?; + let rows = all_bindings + .into_iter() + .filter(|binding| binding.content_id == content_id) + .collect::>(); + if rows.len() > MAX_BINDINGS_PER_ENTRY { + return Err(Status::resource_exhausted( + "too many runtime content bindings", + )); + } + let existing = rows + .iter() + .find(|binding| binding.runtime_id == request.runtime_id) + .cloned(); + if existing + .as_ref() + .map(|binding| binding.revision) + .unwrap_or(0) + != mutation.expected_revision + { + return Ok(Response::new(super::mutations::reply( + &content_id, + existing.map(|binding| binding.revision).unwrap_or(0), + MutationOutcome::RevisionConflict, + ))); + } + let binding_revision = mutation.expected_revision.saturating_add(1); + let binding = RuntimeContentBinding { + game_id, + installation_id: request.installation_id.clone(), + content_id: content_id.clone(), + content: content.clone(), + content_kind: request.content_kind.clone(), + runtime_id: request.runtime_id.clone(), + supported_platforms: request.supported_platforms.clone(), + revision: binding_revision, + }; + if !binding.validate() { + return Err(Status::invalid_argument("invalid runtime content binding")); + } + self.authorize_commit(context, cap::DISCOVERY, caller.grant_revision)?; + self.authorize_commit(context, cap::FILES_READ, caller.grant_revision)?; + // A move/rename updates the current location for every runtime binding of this stable + // content id, preserving the identity and the other selectable runtimes. + let saved = host.save_runtime_content_binding(owner, binding).await?; + let (outcome, revision, commit) = mutation_outcome(saved); + let reply = super::mutations::reply(&content_id, revision, outcome); + if commit { + self.mutations.remember(&caller, key, hash, &reply); + } + drop(lock); + Ok(Response::new(reply)) + } + + pub(super) async fn watch_runtimes( + &self, + request: Request, + ) -> Result>, Status> { + let request = request.into_inner(); + let caller = self + .providers + .authorize_resource(request.context.as_ref(), cap::GAME_RUNTIME_READ)?; + self.providers + .authorize_resource(request.context.as_ref(), cap::FILES_READ)?; + let shared = self.shared_runtime_read(&caller, request.shared_records.as_ref())?; + let host = self.library.host().ok_or_else(unavailable)?; + let owner = mutation_owner(&caller); + let slot = self.watch_slot(&caller.session_id)?; + let initial_revision = runtime_catalog_release(&host, &owner, shared).await?; + if request.after_revision > initial_revision { + return Err(Status::invalid_argument( + "runtime watch revision is in the future", + )); + } + let initial = runtime_catalog_records(&host, &owner, shared).await?; + let shared_recipient = caller + .namespace + .as_ref() + .map(|namespace| namespace.identity().clone()); + let shared_fields = SHARED_RUNTIME_FIELDS + .iter() + .map(|field| (*field).to_owned()) + .collect::>(); + let authorizer = self.shared_authorizer.clone(); + let (sender, receiver) = mpsc::channel(32); + let providers = self.providers.clone(); + let resource = self.clone(); + let context = request.context.unwrap_or_default(); + let resource_id = request.resource_id; + tokio::spawn(async move { + let _slot = slot; + let mut last_revision = request.after_revision; + let mut last = initial; + if last_revision < initial_revision { + let event = RuntimeRecordEvent { + revision: initial_revision, + event_type: "reset".into(), + runtime: None, + }; + if sender.send(Ok(event)).await.is_err() { + return; + } + for (is_shared, runtime) in &last { + if !resource_id.is_empty() && runtime.id != resource_id { + continue; + } + match runtime_event_record( + &resource, + &caller, + &context, + *is_shared, + runtime.clone(), + ) + .await + { + Ok(runtime) => { + if sender + .send(Ok(RuntimeRecordEvent { + revision: initial_revision, + event_type: "upserted".into(), + runtime: Some(runtime), + })) + .await + .is_err() + { + return; + } + } + Err(error) => { + let _ = sender.send(Err(error)).await; + return; + } + } + } + last_revision = initial_revision; + } + let mut recheck = tokio::time::interval(WATCH_RECHECK); + let mut poll = tokio::time::interval(WATCH_POLL); + loop { + tokio::select! { + _ = recheck.tick() => { + if let Err(error) = providers.authorize_resource(Some(&context), cap::GAME_RUNTIME_READ) + .and_then(|_| providers.authorize_resource(Some(&context), cap::FILES_READ)) { + let _ = sender.send(Err(error)).await; + return; + } + if shared && !shared_category_allowed(&authorizer, shared_recipient.as_ref(), &shared_fields) { + let _ = sender.send(Err(Status::permission_denied( + "common runtime catalog access is not granted", + ))).await; + return; + } + } + _ = poll.tick() => { + let revision = match runtime_catalog_release(&host, &owner, shared).await { + Ok(revision) => revision, + Err(error) => { let _ = sender.send(Err(error)).await; return; } + }; + if revision == last_revision { continue; } + let current = match runtime_catalog_records(&host, &owner, shared).await { + Ok(records) => records, + Err(error) => { let _ = sender.send(Err(error)).await; return; } + }; + let removed = last.iter().any(|old| !current.iter().any(|new| new.0 == old.0 && new.1.id == old.1.id)); + if removed + && sender.send(Ok(RuntimeRecordEvent { revision, event_type: "reset".into(), runtime: None })).await.is_err() { return; } + for (is_shared, runtime) in ¤t { + let changed = last.iter().find(|old| old.0 == *is_shared && old.1.id == runtime.id).is_none_or(|old| old.1.revision != runtime.revision); + if !changed || (!resource_id.is_empty() && runtime.id != resource_id) { continue; } + match runtime_event_record(&resource, &caller, &context, *is_shared, runtime.clone()).await { + Ok(runtime) => { + if sender.send(Ok(RuntimeRecordEvent { revision, event_type: "upserted".into(), runtime: Some(runtime) })).await.is_err() { return; } + } + Err(error) => { let _ = sender.send(Err(error)).await; return; } + } + } + if current.iter().all(|(is_shared, runtime)| last.iter().any(|old| old.0 == *is_shared && old.1.id == runtime.id && old.1.revision == runtime.revision)) { + let _ = sender.send(Ok(RuntimeRecordEvent { revision, event_type: "bindings_changed".into(), runtime: None })).await; + } + last = current; + last_revision = revision; + } + } + } + }); + Ok(Response::new(Box::pin(ReceiverStream::new(receiver)))) + } +} + +async fn runtime_catalog_release( + host: &std::sync::Arc, + owner: &str, + shared: bool, +) -> Result { + if shared { + host.shared_runtime_catalog_revision().await + } else { + host.runtime_catalog_revision(owner.to_owned()).await + } +} + +async fn runtime_catalog_records( + host: &std::sync::Arc, + owner: &str, + shared: bool, +) -> Result, Status> { + let mut records = host + .runtime_resources(owner.to_owned()) + .await? + .into_iter() + .map(|runtime| (false, runtime)) + .collect::>(); + if shared { + records.extend( + host.shared_runtime_resources() + .await? + .into_iter() + .filter(|(owner_key, _)| owner_key != owner) + .map(|(_, runtime)| (true, runtime)), + ); + } + records.sort_by(|left, right| { + left.1 + .id + .cmp(&right.1.id) + .then_with(|| left.0.cmp(&right.0)) + }); + Ok(records) +} + +async fn runtime_event_record( + resource: &ResourceApi, + caller: &ResourceCaller, + context: &ServiceContext, + shared: bool, + runtime: RuntimeResource, +) -> Result { + if shared { + ResourceApi::runtime_proto_shared(runtime) + } else { + resource.runtime_proto(caller, context, runtime).await + } +} + +fn shared_category_allowed( + authorizer: &std::sync::Arc, + recipient: Option<&crate::plugin_host::grants::PluginIdentity>, + fields: &BTreeSet, +) -> bool { + recipient.is_some_and(|recipient| { + authorizer + .common_category(recipient, CommonDataCategory::RuntimeCatalog, fields) + .allowed + }) +} diff --git a/crates/app/src/plugin_host/resources/saves.rs b/crates/app/src/plugin_host/resources/saves.rs new file mode 100644 index 000000000..cc9fe6908 --- /dev/null +++ b/crates/app/src/plugin_host/resources/saves.rs @@ -0,0 +1,981 @@ +//! The `Saves` service: save profiles contributed by plugins (task 13.1, design section 12). +//! +//! A profile is configuration kept in the contributing plugin's own store (see +//! `plugin_host::saves`). Its folders are folders the user already approved for the same plugin +//! and installation (task 6.2), named by the handles the plugin got; the rules only narrow inside +//! them. Nothing here reads a file, and no permission here authorizes reading, backing up or +//! restoring one. +//! +//! The grants are `game.saves.read`, `.create`, `.update` and `.delete`, independent of each +//! other. A plugin reaches another plugin's profile only through a provisional grant the host +//! holds for that profile and operation ([`SaveAccess`]); it never changes the folders of a +//! profile it did not create, because they are the other plugin's approved folders. + +use gamenode_plugin_protocol::{capability as cap, proto::*}; +use tonic::{Request, Response, Status}; + +use super::mutations::{game_id, mutation_key, reply, request_hash}; +use super::{ResourceApi, Served}; +use crate::plugin_host::files::FileAccess; +use crate::plugin_host::library::LibraryFeed; +use crate::plugin_host::provider::ResourceCaller; +use crate::plugin_host::saves::{ + self as saves, Directory, ForeignGrant, MAX_DIRECTORIES, MAX_PROFILES_PER_INSTALLATION, + MAX_PROFILES_PER_PLUGIN, access, +}; +use crate::plugin_host::storage::{Namespace, ProfileWrite}; +use gamenode_platform::plugin_storage::SaveProfileRow; + +const DEFAULT_PAGE: usize = 50; +const MAX_PAGE: usize = 200; +const MAX_SELECTED: usize = 64; +const MAX_ID_BYTES: usize = 128; + +pub const OWN_PROFILES: &str = + "this plugin's own profiles; another plugin's only through a grant for that profile"; + +/// The `Saves` methods this build serves, for `DescribeApi`. +pub const SERVED: &[Served] = &[ + Served::new("ListProfiles", cap::GAME_SAVES_READ, true, OWN_PROFILES), + Served::new("GetProfile", cap::GAME_SAVES_READ, false, OWN_PROFILES), + Served::new("CreateProfile", cap::GAME_SAVES_CREATE, false, OWN_PROFILES), + Served::new("UpdateProfile", cap::GAME_SAVES_UPDATE, false, OWN_PROFILES), + Served::new("RemoveProfile", cap::GAME_SAVES_DELETE, false, OWN_PROFILES), +]; + +/// Fields an update may name in its mask. Identity, installation, game and provenance are not +/// among them: a profile that moved would be a different profile. +const PATCHABLE: &[&str] = &[ + "name", + "directories", + "runtime_id", + "format_id", + "format_version", + "descriptive_metadata", + "shared_resources", +]; + +fn profile_id(text: &str) -> Result<&str, Status> { + if text.is_empty() || text.len() > MAX_ID_BYTES || text.chars().any(char::is_control) { + return Err(Status::invalid_argument( + "profile_id is required: 1 to 128 bytes", + )); + } + Ok(text) +} + +fn not_found() -> Status { + Status::not_found("save profile not found") +} + +/// Whose a profile in a reply is. +struct Owner { + plugin_id: String, +} + +/// Resolves what a plugin sent as folders into stored folders. Runs on the namespace worker. +fn resolve_directories( + files: &FileAccess, + namespace: &mut Namespace<'_>, + session: &str, + installation_id: &str, + directories: &[SaveDirectory], +) -> Result, Status> { + if directories.is_empty() || directories.len() > MAX_DIRECTORIES { + return Err(Status::invalid_argument(format!( + "a profile has 1 to {MAX_DIRECTORIES} directories" + ))); + } + let mut resolved: Vec = Vec::new(); + for directory in directories { + // A malformed handle, another session's, a revoked approval's and an unknown one are the + // same answer, as for file access. + let (approval_id, path) = files + .open_handle(session, &directory.approved_resource_handle) + .ok_or_else(|| Status::not_found("file handle not found"))?; + let approval = namespace + .approval(&approval_id)? + .filter(|approval| approval.revoked_at.is_none()) + .ok_or_else(|| Status::not_found("file handle not found"))?; + if approval.installation_id != installation_id { + return Err(Status::permission_denied( + "this folder was approved for another library entry", + )); + } + if resolved + .iter() + .any(|seen| seen.approval_id == approval_id && seen.path == path) + { + return Err(Status::invalid_argument("a directory is listed twice")); + } + resolved.push(Directory { + approval_id, + path, + display_name: saves::check_display_name(&directory.display_name)?, + naming_patterns: saves::check_patterns(&directory.naming_patterns)?, + }); + } + Ok(resolved) +} + +/// A stored profile as a plugin sees it. `handles` is the session whose folder handles to issue +/// (an own profile whose approvals still stand); a folder whose approval was revoked, or any +/// folder of another plugin's profile, comes with no handle: its folder is not reachable. +fn to_proto( + row: &SaveProfileRow, + owner: &Owner, + feed: &LibraryFeed, + handles: Option<(&FileAccess, &str, &mut Namespace<'_>)>, +) -> Result { + let mut directories = Vec::new(); + let mut handles = handles; + for directory in saves::directories_from_json(&row.directories) { + let handle = match handles.as_mut() { + Some((files, session, namespace)) => { + let active = namespace + .approval(&directory.approval_id)? + .is_some_and(|approval| { + approval.revoked_at.is_none() + && approval.installation_id == row.installation_id + }); + if active { + files.seal_handle(session, &directory.approval_id, &directory.path) + } else { + String::new() + } + } + None => String::new(), + }; + directories.push(SaveDirectory { + approved_resource_handle: handle, + display_name: directory.display_name, + naming_patterns: directory.naming_patterns, + }); + } + let mut shared_resources = Vec::new(); + for resource in crate::plugin_host::shared_resources::resources_from_json(&row.shared_resources) + { + let (handle, consent) = match handles.as_mut() { + Some((files, session, namespace)) => { + let active = namespace + .approval(&resource.approval_id)? + .is_some_and(|approval| approval.revoked_at.is_none()); + let record = namespace.shared_resource_consent(&row.id, &resource.resource_id)?; + let consent = match crate::plugin_host::shared_resources::reply_state( + record.as_ref(), + &resource, + ) { + crate::plugin_host::shared_resources::ConsentState::Current => { + match super::files::open_approval_inspect( + files, + feed, + namespace, + &resource.approval_id, + resource.path.clone(), + ) { + Ok(Ok(opened)) => match crate::plugin_host::shared_resources::scope_of( + feed, + &opened.approval, + ) { + Ok(scope) => { + crate::plugin_host::shared_resources::reply_state_with_scope( + record.as_ref(), + &resource, + &scope, + ) + } + Err(_) => crate::plugin_host::shared_resources::ConsentState::Stale, + }, + _ => crate::plugin_host::shared_resources::ConsentState::Stale, + } + } + state => state, + }; + ( + if active { + files.seal_handle(session, &resource.approval_id, &resource.path) + } else { + String::new() + }, + consent, + ) + } + None => ( + String::new(), + crate::plugin_host::shared_resources::ConsentState::Pending, + ), + }; + shared_resources.push(SharedResourceDeclaration { + resource_id: resource.resource_id, + approved_resource_handle: handle, + display_name: resource.display_name, + consent: consent.proto(), + }); + } + Ok(SaveProfile { + profile_id: row.id.clone(), + game_id: row.game_id.clone(), + installation_id: row.installation_id.clone(), + name: row.name.clone(), + directories, + runtime_id: row.runtime_id.clone(), + format_id: row.format_id.clone(), + format_version: row.format_version, + descriptive_metadata: saves::metadata_struct(&row.metadata), + creator_plugin_id: owner.plugin_id.clone(), + revision: row.revision, + shared_resources, + }) +} + +fn no_categories(selector: Option<&CommonDataSelector>) -> Result<(), Status> { + match selector { + Some(selector) if !selector.categories.is_empty() => Err(Status::unimplemented( + "common-data categories are not available for Saves", + )), + Some(selector) if selector.selected_record_ids.len() > MAX_SELECTED => { + Err(Status::invalid_argument("too many selected records")) + } + _ => Ok(()), + } +} + +impl ResourceApi { + /// The caller's plugin identity: the authenticated plugin and its pinned publisher. + fn saves_identity(caller: &ResourceCaller) -> Result<(String, String), Status> { + let identity = caller + .namespace + .as_ref() + .ok_or_else(|| { + Status::failed_precondition("official providers use trusted host adapters") + })? + .identity(); + Ok(( + identity.plugin_id.clone(), + identity.publisher_fingerprint.clone(), + )) + } + + /// Another plugin's profile `id`, if this caller holds a grant for `operation` on it. + fn foreign_grant( + &self, + caller: &ResourceCaller, + id: &str, + operation: u8, + ) -> Result, Status> { + let (plugin_id, publisher) = Self::saves_identity(caller)?; + Ok(self.saves.grant_for(&plugin_id, &publisher, id, operation)) + } + + /// Runs `work` on the namespace of the plugin that created a profile this caller was granted. + async fn in_creator( + &self, + grant: &ForeignGrant, + work: impl FnOnce(&mut Namespace<'_>) -> Result + Send + 'static, + ) -> Result { + let profiles = self.providers.profiles(); + let resolver = + profiles.resolver(&grant.creator_plugin_id, &grant.creator_publisher, None)?; + self.storage + .run_for_host(&resolver, profiles.epoch(), work) + .await + } + + pub(super) async fn list_save_profiles( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + let caller = self + .providers + .authorize_resource(request.context.as_ref(), cap::GAME_SAVES_READ)?; + no_categories(request.shared_records.as_ref())?; + let wanted_game = game_id(&request.game_id)?; + let size = match request.page_size as usize { + 0 => DEFAULT_PAGE, + size => size.min(MAX_PAGE), + }; + let (plugin_id, _) = Self::saves_identity(&caller)?; + let (files, session) = (self.files.clone(), caller.session_id.clone()); + let feed = self.library.clone(); + let (installation, game, after) = ( + request.installation_id.clone(), + wanted_game.map(|id| id.to_string()), + request.cursor.clone(), + ); + let owner = Owner { + plugin_id: plugin_id.clone(), + }; + let (mut profiles, next, revision) = self + .in_namespace(&caller, move |namespace| { + let mut rows: Vec<_> = namespace + .save_profiles()? + .into_iter() + .filter(|row| installation.is_empty() || row.installation_id == installation) + .filter(|row| game.as_ref().is_none_or(|game| row.game_id == *game)) + .filter(|row| { + after.is_empty() || format!("{}|{}", row.installation_id, row.id) > after + }) + .collect(); + let more = rows.len() > size; + rows.truncate(size); + let next = if more { + rows.last() + .map(|row| format!("{}|{}", row.installation_id, row.id)) + .unwrap_or_default() + } else { + String::new() + }; + let profiles = rows + .iter() + .map(|row| to_proto(row, &owner, &feed, Some((&files, &session, namespace)))) + .collect::, _>>()?; + Ok((profiles, next, namespace.revision()?)) + }) + .await?; + + // Profiles of other plugins that were granted and named: only on the first page. + if request.cursor.is_empty() + && let Some(selector) = &request.shared_records + { + for id in &selector.selected_record_ids { + if profiles.iter().any(|profile| profile.profile_id == *id) { + continue; + } + let Some(grant) = self.foreign_grant(&caller, id, access::READ)? else { + continue; + }; + if let Some(profile) = self.foreign_profile(&grant).await? { + let matches = (request.installation_id.is_empty() + || profile.installation_id == request.installation_id) + && wanted_game.is_none_or(|game| profile.game_id == game.to_string()); + if matches { + profiles.push(profile); + } + } + } + } + // The grants are checked once more before the answer leaves. + self.providers + .authorize_resource(request.context.as_ref(), cap::GAME_SAVES_READ)?; + Ok(Response::new(SaveProfileListReply { + profiles, + next_cursor: next, + revision, + })) + } + + /// The profile a foreign grant names, as the grantee sees it (no folder handles). + async fn foreign_profile(&self, grant: &ForeignGrant) -> Result, Status> { + let id = grant.profile_id.clone(); + let owner = Owner { + plugin_id: grant.creator_plugin_id.clone(), + }; + let feed = self.library.clone(); + self.in_creator(grant, move |namespace| { + namespace + .save_profile(&id)? + .map(|row| to_proto(&row, &owner, &feed, None)) + .transpose() + }) + .await + } + + pub(super) async fn get_save_profile( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + let caller = self + .providers + .authorize_resource(request.context.as_ref(), cap::GAME_SAVES_READ)?; + no_categories(request.shared_records.as_ref())?; + let id = profile_id(&request.profile_id)?.to_owned(); + let wanted_game = game_id(&request.game_id)?.map(|id| id.to_string()); + let (plugin_id, _) = Self::saves_identity(&caller)?; + let (files, session) = (self.files.clone(), caller.session_id.clone()); + let feed = self.library.clone(); + let owner = Owner { plugin_id }; + let lookup = id.clone(); + let own = self + .in_namespace(&caller, move |namespace| { + let Some(row) = namespace.save_profile(&lookup)? else { + return Ok(None); + }; + let profile = to_proto(&row, &owner, &feed, Some((&files, &session, namespace)))?; + Ok(Some((profile, namespace.revision()?))) + }) + .await?; + let (profile, revision) = match own { + Some(found) => found, + None => { + let grant = self + .foreign_grant(&caller, &id, access::READ)? + .ok_or_else(not_found)?; + let profile = self.foreign_profile(&grant).await?.ok_or_else(not_found)?; + let revision = profile.revision; + (profile, revision) + } + }; + if wanted_game.is_some_and(|game| profile.game_id != game) { + return Err(not_found()); + } + self.providers + .authorize_resource(request.context.as_ref(), cap::GAME_SAVES_READ)?; + Ok(Response::new(SaveProfileReply { + profile: Some(profile), + revision, + })) + } + + pub(super) async fn create_save_profile( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + let mutation = request + .mutation + .as_ref() + .ok_or_else(|| Status::invalid_argument("mutation is required"))?; + let caller = self + .providers + .authorize_resource(mutation.context.as_ref(), cap::GAME_SAVES_CREATE)?; + let key = mutation_key(mutation)?; + let profile = request + .profile + .as_ref() + .ok_or_else(|| Status::invalid_argument("profile is required"))?; + if mutation.expected_revision != 0 { + return Err(Status::invalid_argument( + "expected_revision must be 0 to create a profile", + )); + } + if !profile.profile_id.is_empty() + || !profile.creator_plugin_id.is_empty() + || profile.revision != 0 + { + return Err(Status::invalid_argument( + "profile_id, creator_plugin_id and revision are set by the host", + )); + } + let name = saves::check_name("name", &profile.name)?; + let runtime_id = saves::check_identifier("runtime_id", &profile.runtime_id)?; + let format_id = saves::check_identifier("format_id", &profile.format_id)?; + let metadata = saves::check_metadata(profile.descriptive_metadata.as_ref())?; + if profile.installation_id.is_empty() || profile.installation_id.len() > MAX_ID_BYTES { + return Err(Status::invalid_argument( + "installation_id is required: 1 to 128 bytes", + )); + } + if profile.directories.is_empty() || profile.directories.len() > MAX_DIRECTORIES { + return Err(Status::invalid_argument(format!( + "a profile has 1 to {MAX_DIRECTORIES} directories" + ))); + } + // The profile is for one of this plugin's own library entries. + let (_, entry) = self.action_target( + &caller, + &mutation.context.clone().unwrap_or_default(), + &profile.game_id, + &profile.installation_id, + )?; + let game = entry.game_id.map(|id| id.to_string()).unwrap_or_default(); + let id = saves::new_profile_id()?; + + let mut parts: Vec = vec![ + "save-profile-create".into(), + profile.installation_id.clone(), + profile.game_id.clone(), + name.clone(), + runtime_id.clone(), + format_id.clone(), + profile.format_version.to_string(), + metadata.clone(), + ]; + for directory in &profile.directories { + parts.push(directory.approved_resource_handle.clone()); + parts.push(directory.display_name.clone()); + parts.push(directory.naming_patterns.join("\u{0}")); + } + for resource in &profile.shared_resources { + parts.push(resource.resource_id.clone()); + parts.push(resource.approved_resource_handle.clone()); + parts.push(resource.display_name.clone()); + } + let hash = request_hash(&parts.iter().map(String::as_str).collect::>()); + + let _serial = self.mutations.lock.lock().await; + if let Some(original) = self.mutations.replay(&caller, key, hash)? { + return Ok(Response::new(from_stored(original))); + } + let context = mutation.context.clone().unwrap_or_default(); + let guard = self.guard(context, cap::GAME_SAVES_CREATE, caller.grant_revision); + let (files, session) = (self.files.clone(), caller.session_id.clone()); + let feed = self.library.clone(); + let directories = profile.directories.clone(); + let shared_declarations = profile.shared_resources.clone(); + let row = SaveProfileRow { + id: id.clone(), + installation_id: entry.installation_id.clone(), + game_id: game, + name, + runtime_id, + format_id, + format_version: profile.format_version, + metadata, + directories: String::new(), + shared_resources: String::new(), + revision: 0, + created_at: 0, + }; + let written = self + .in_namespace(&caller, move |namespace| { + let existing = namespace.save_profiles()?; + if existing.len() >= MAX_PROFILES_PER_PLUGIN + || existing + .iter() + .filter(|row| row.installation_id == entry.installation_id) + .count() + >= MAX_PROFILES_PER_INSTALLATION + { + return Err(Status::resource_exhausted(format!( + "a plugin keeps at most {MAX_PROFILES_PER_INSTALLATION} save profiles per \ + game entry and {MAX_PROFILES_PER_PLUGIN} in all" + ))); + } + let resolved = resolve_directories( + &files, + namespace, + &session, + &row.installation_id, + &directories, + )?; + let shared = crate::plugin_host::shared_resources::resolve_declarations( + &files, + &feed, + namespace, + &session, + None, + &row.installation_id, + &row.runtime_id, + &shared_declarations, + &existing, + )?; + let row = SaveProfileRow { + directories: saves::directories_json(&resolved), + shared_resources: crate::plugin_host::shared_resources::resources_json(&shared), + created_at: namespace.now(), + ..row + }; + namespace.put_save_profile(row, 0, &guard) + }) + .await?; + let answer = match written { + ProfileWrite::Applied { revision } => SaveProfileMutationReply { + profile_id: id, + revision, + outcome: MutationOutcome::Applied as i32, + }, + ProfileWrite::NameTaken => { + return Err(Status::already_exists( + "this game entry already has a profile with that name", + )); + } + ProfileWrite::Conflict { .. } | ProfileWrite::NotFound => { + return Err(Status::aborted( + "the profile could not be created; try again", + )); + } + }; + self.mutations.remember( + &caller, + key, + hash, + &reply( + &answer.profile_id, + answer.revision, + MutationOutcome::Applied, + ), + ); + Ok(Response::new(answer)) + } + + pub(super) async fn update_save_profile( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + let mutation = request + .mutation + .as_ref() + .ok_or_else(|| Status::invalid_argument("mutation is required"))?; + let caller = self + .providers + .authorize_resource(mutation.context.as_ref(), cap::GAME_SAVES_UPDATE)?; + let key = mutation_key(mutation)?; + let id = profile_id(&request.profile_id)?.to_owned(); + if mutation.expected_revision == 0 { + return Err(Status::invalid_argument( + "expected_revision is required to update a profile", + )); + } + let patch = request + .patch + .as_ref() + .ok_or_else(|| Status::invalid_argument("patch is required"))?; + let new = patch.profile.clone().unwrap_or_default(); + if patch.field_mask.is_empty() { + return Err(Status::invalid_argument("patch.field_mask is empty")); + } + let field_mask = patch.field_mask.clone(); + for path in &field_mask { + if !PATCHABLE.contains(&path.as_str()) { + return Err(Status::invalid_argument(format!( + "{path:?} cannot be updated; name, directories, runtime_id, format_id, \ + format_version, descriptive_metadata and shared_resources can" + ))); + } + } + let touches = move |field: &str| field_mask.iter().any(|path| path == field); + // What the patch sets is checked now, before anything is read or locked. + let name = touches("name") + .then(|| saves::check_name("name", &new.name)) + .transpose()?; + let runtime_id = touches("runtime_id") + .then(|| saves::check_identifier("runtime_id", &new.runtime_id)) + .transpose()?; + let format_id = touches("format_id") + .then(|| saves::check_identifier("format_id", &new.format_id)) + .transpose()?; + let metadata = touches("descriptive_metadata") + .then(|| saves::check_metadata(new.descriptive_metadata.as_ref())) + .transpose()?; + let directories_given = touches("directories"); + if directories_given + && (new.directories.is_empty() || new.directories.len() > MAX_DIRECTORIES) + { + return Err(Status::invalid_argument(format!( + "a profile has 1 to {MAX_DIRECTORIES} directories" + ))); + } + let shared_given = touches("shared_resources"); + if shared_given + && new.shared_resources.len() + > crate::plugin_host::shared_resources::MAX_SHARED_RESOURCES + { + return Err(Status::invalid_argument(format!( + "a profile declares at most {} shared resources", + crate::plugin_host::shared_resources::MAX_SHARED_RESOURCES + ))); + } + let mut parts: Vec = vec![ + "save-profile-update".into(), + id.clone(), + mutation.expected_revision.to_string(), + patch.field_mask.join(","), + name.clone().unwrap_or_default(), + runtime_id.clone().unwrap_or_default(), + format_id.clone().unwrap_or_default(), + new.format_version.to_string(), + metadata.clone().unwrap_or_default(), + ]; + for directory in &new.directories { + parts.push(directory.approved_resource_handle.clone()); + parts.push(directory.display_name.clone()); + parts.push(directory.naming_patterns.join("\u{0}")); + } + for resource in &new.shared_resources { + parts.push(resource.resource_id.clone()); + parts.push(resource.approved_resource_handle.clone()); + parts.push(resource.display_name.clone()); + } + let hash = request_hash(&parts.iter().map(String::as_str).collect::>()); + + let _serial = self.mutations.lock.lock().await; + if let Some(original) = self.mutations.replay(&caller, key, hash)? { + return Ok(Response::new(from_stored(original))); + } + let context = mutation.context.clone().unwrap_or_default(); + let guard = self.guard(context, cap::GAME_SAVES_UPDATE, caller.grant_revision); + let expected = mutation.expected_revision; + let format_version = touches("format_version").then_some(new.format_version); + let new_directories = new.directories.clone(); + let new_shared = new.shared_resources.clone(); + let (files, session) = (self.files.clone(), caller.session_id.clone()); + let feed = self.library.clone(); + let runtime_for_shared = runtime_id.clone(); + + // The plugin's own profile first; then, for another's, the grant for this operation. + let lookup = id.clone(); + let own = self + .in_namespace(&caller, move |namespace| { + Ok(namespace.save_profile(&lookup)?.is_some()) + }) + .await?; + let apply = + move |row: SaveProfileRow, + directories: Option>, + shared: Option>| + -> SaveProfileRow { + SaveProfileRow { + name: name.unwrap_or(row.name), + runtime_id: runtime_id.clone().unwrap_or(row.runtime_id), + format_id: format_id.unwrap_or(row.format_id), + format_version: format_version.unwrap_or(row.format_version), + metadata: metadata.unwrap_or(row.metadata), + directories: directories + .map(|directories| saves::directories_json(&directories)) + .unwrap_or(row.directories), + shared_resources: shared + .map(|shared| crate::plugin_host::shared_resources::resources_json(&shared)) + .unwrap_or(row.shared_resources), + ..row + } + }; + let written = if own { + let lookup = id.clone(); + self.in_namespace(&caller, move |namespace| { + let row = namespace.save_profile(&lookup)?.ok_or_else(not_found)?; + if touches("runtime_id") + && !shared_given + && !crate::plugin_host::shared_resources::resources_from_json( + &row.shared_resources, + ) + .is_empty() + { + return Err(Status::failed_precondition( + "shared resources must be declared again when the runtime binding changes", + )); + } + let directories = if directories_given { + Some(resolve_directories( + &files, + namespace, + &session, + &row.installation_id, + &new_directories, + )?) + } else { + None + }; + let shared = if shared_given { + let existing = namespace.save_profiles()?; + let runtime = runtime_for_shared.as_deref().unwrap_or(&row.runtime_id); + Some(crate::plugin_host::shared_resources::resolve_declarations( + &files, + &feed, + namespace, + &session, + Some(&row.id), + &row.installation_id, + runtime, + &new_shared, + &existing, + )?) + } else { + None + }; + namespace.put_save_profile(apply(row, directories, shared), expected, &guard) + }) + .await? + } else { + let grant = self + .foreign_grant(&caller, &id, access::UPDATE)? + .ok_or_else(not_found)?; + if directories_given { + // The folders are the creator's own approved folders; a grantee cannot widen, + // narrow or replace them. + return Err(Status::permission_denied( + "the directories of a profile can be changed only by the plugin that made it", + )); + } + if shared_given { + return Err(Status::permission_denied( + "the shared resources of a profile can be changed only by the plugin that made it", + )); + } + let lookup = id.clone(); + self.in_creator(&grant, move |namespace| { + let row = namespace.save_profile(&lookup)?.ok_or_else(not_found)?; + namespace.put_save_profile(apply(row, None, None), expected, &guard) + }) + .await? + }; + let answer = Self::profile_outcome(&id, written)?; + // Only a change that was made is remembered: a stale revision may be retried. + if answer_outcome(&answer) == MutationOutcome::Applied { + self.mutations.remember( + &caller, + key, + hash, + &reply( + &answer.profile_id, + answer.revision, + MutationOutcome::Applied, + ), + ); + } + Ok(Response::new(answer)) + } + + pub(super) async fn remove_save_profile( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + let mutation = request + .mutation + .as_ref() + .ok_or_else(|| Status::invalid_argument("mutation is required"))?; + let caller = self + .providers + .authorize_resource(mutation.context.as_ref(), cap::GAME_SAVES_DELETE)?; + let key = mutation_key(mutation)?; + let id = profile_id(&request.profile_id)?.to_owned(); + let wanted_game = game_id(&request.game_id)?.map(|id| id.to_string()); + if mutation.expected_revision == 0 { + return Err(Status::invalid_argument( + "expected_revision is required to remove a profile", + )); + } + let hash = request_hash(&[ + "save-profile-remove", + &id, + &request.game_id, + &mutation.expected_revision.to_string(), + ]); + + let _serial = self.mutations.lock.lock().await; + if let Some(original) = self.mutations.replay(&caller, key, hash)? { + return Ok(Response::new(from_stored(original))); + } + let context = mutation.context.clone().unwrap_or_default(); + let guard = self.guard(context, cap::GAME_SAVES_DELETE, caller.grant_revision); + let expected = mutation.expected_revision; + let (lookup, game) = (id.clone(), wanted_game.clone()); + let own = self + .in_namespace(&caller, move |namespace| { + Ok(namespace + .save_profile(&lookup)? + .filter(|row| game.as_ref().is_none_or(|game| row.game_id == *game)) + .is_some()) + }) + .await?; + // Removing a profile never touches a file: the folders and the archives stay where the + // user and the backup history keep them. + let written = if own { + let lookup = id.clone(); + self.in_namespace(&caller, move |namespace| { + namespace.remove_save_profile(&lookup, expected, &guard) + }) + .await? + } else { + let grant = self + .foreign_grant(&caller, &id, access::DELETE)? + .ok_or_else(not_found)?; + let (lookup, game) = (id.clone(), wanted_game); + self.in_creator(&grant, move |namespace| { + let matches = namespace + .save_profile(&lookup)? + .is_some_and(|row| game.as_ref().is_none_or(|game| row.game_id == *game)); + if !matches { + return Ok(ProfileWrite::NotFound); + } + namespace.remove_save_profile(&lookup, expected, &guard) + }) + .await? + }; + let answer = Self::profile_outcome(&id, written)?; + // Only a change that was made is remembered: a stale revision may be retried. + if answer_outcome(&answer) == MutationOutcome::Applied { + self.mutations.remember( + &caller, + key, + hash, + &reply( + &answer.profile_id, + answer.revision, + MutationOutcome::Applied, + ), + ); + } + Ok(Response::new(answer)) + } + + /// The reply for an update or removal, or the status for what stopped it. A stale revision + /// is an outcome, not an error, so the plugin can read the profile and try again. + fn profile_outcome( + id: &str, + written: ProfileWrite, + ) -> Result { + Ok(match written { + ProfileWrite::Applied { revision } => SaveProfileMutationReply { + profile_id: id.to_owned(), + revision, + outcome: MutationOutcome::Applied as i32, + }, + ProfileWrite::Conflict { current } => SaveProfileMutationReply { + profile_id: id.to_owned(), + revision: current, + outcome: MutationOutcome::RevisionConflict as i32, + }, + ProfileWrite::NameTaken => { + return Err(Status::already_exists( + "this game entry already has a profile with that name", + )); + } + ProfileWrite::NotFound => return Err(not_found()), + }) + } +} + +/// The outcome a retry is answered with: what the first call stored, in the reply's own shape. +fn from_stored(stored: MutationReply) -> SaveProfileMutationReply { + SaveProfileMutationReply { + profile_id: stored.resource_id, + revision: stored.revision, + outcome: stored.outcome, + } +} + +fn answer_outcome(answer: &SaveProfileMutationReply) -> MutationOutcome { + MutationOutcome::try_from(answer.outcome).unwrap_or(MutationOutcome::Applied) +} + +#[tonic::async_trait] +impl saves_server::Saves for ResourceApi { + async fn list_profiles( + &self, + request: Request, + ) -> Result, Status> { + self.list_save_profiles(request).await + } + + async fn get_profile( + &self, + request: Request, + ) -> Result, Status> { + self.get_save_profile(request).await + } + + async fn create_profile( + &self, + request: Request, + ) -> Result, Status> { + self.create_save_profile(request).await + } + + async fn update_profile( + &self, + request: Request, + ) -> Result, Status> { + self.update_save_profile(request).await + } + + async fn remove_profile( + &self, + request: Request, + ) -> Result, Status> { + self.remove_save_profile(request).await + } +} diff --git a/crates/app/src/plugin_host/resources/storage.rs b/crates/app/src/plugin_host/resources/storage.rs new file mode 100644 index 000000000..380a2bda3 --- /dev/null +++ b/crates/app/src/plugin_host/resources/storage.rs @@ -0,0 +1,260 @@ +//! Private key/value storage of `ResourceHost`: `StorageGet`, `StoragePut`, `StorageDelete`. +//! +//! The caller's namespace is the host-authenticated plugin/publisher/profile identity +//! ([`crate::plugin_host::storage`]); a request names only a key. Reading needs +//! `storage.read`, writing `storage.write`, deleting `storage.delete`, and a write that asks for +//! `PERSISTENT` durability also needs `storage.persist`: without it the call is denied, never +//! quietly kept in memory. Writes and deletes carry an idempotency key and the key's expected +//! revision (0 for a key that does not exist), and commit under a recheck of the caller's +//! permissions. + +use gamenode_plugin_protocol::{capability as cap, proto::*}; +use sha2::{Digest, Sha256}; +use tonic::{Request, Response, Status}; + +use super::ResourceApi; +use super::mutations::{mutation_key, reply, request_hash}; +use crate::plugin_host::provider::ResourceCaller; +use crate::plugin_host::storage::{ + DeleteOutcome, Durability, MAX_KEY_BYTES, MAX_TTL_SECONDS, MAX_VALUE_BYTES, Namespace, + PutOutcome, QUOTA_BYTES, +}; + +fn storage_key(key: &str) -> Result { + if key.is_empty() || key.len() > MAX_KEY_BYTES || key.chars().any(char::is_control) { + return Err(Status::invalid_argument(format!( + "key is required: 1 to {MAX_KEY_BYTES} bytes without control characters" + ))); + } + Ok(key.to_owned()) +} + +fn proto_durability(durability: Durability) -> StorageDurability { + match durability { + Durability::SessionOnly => StorageDurability::SessionOnly, + Durability::Persistent => StorageDurability::Persistent, + } +} + +impl ResourceApi { + /// Runs `work` on the caller's namespace on a blocking worker. + pub(super) async fn in_namespace( + &self, + caller: &ResourceCaller, + work: impl FnOnce(&mut Namespace<'_>) -> Result + Send + 'static, + ) -> Result { + let providers = self.providers.clone(); + self.storage + .run(caller, move |id| providers.session_is_open(id), work) + .await + } + + /// Runs host-initiated user actions in the same private namespace without pretending they + /// came from a live plugin session. The caller must be built from the current profile's + /// authenticated identity and grants. + pub(super) async fn in_host_namespace( + &self, + caller: &ResourceCaller, + work: impl FnOnce(&mut Namespace<'_>) -> Result + Send + 'static, + ) -> Result { + let resolver = caller.namespace.clone().ok_or_else(|| { + Status::failed_precondition("official providers use trusted host adapters") + })?; + self.storage + .run_for_host(&resolver, caller.profile_epoch, work) + .await + } + + pub(super) async fn get_stored( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + let caller = self + .providers + .authorize_resource(request.context.as_ref(), cap::STORAGE_READ)?; + let key = storage_key(&request.key)?; + let found = self + .in_namespace(&caller, move |namespace| namespace.get(&key)) + .await?; + // The value was read for a call that may since have lost its permission. + self.providers + .authorize_resource(request.context.as_ref(), cap::STORAGE_READ)?; + Ok(Response::new(match found { + None => StorageGetReply { + found: false, + ..StorageGetReply::default() + }, + Some(found) => StorageGetReply { + value: found.value, + revision: found.revision, + found: true, + durability: proto_durability(found.durability) as i32, + expires_at: found.expires_at.unwrap_or(0), + }, + })) + } + + pub(super) async fn put_stored( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + let mutation = request + .mutation + .as_ref() + .ok_or_else(|| Status::invalid_argument("mutation is required"))?; + let context = mutation.context.clone().unwrap_or_default(); + let caller = self + .providers + .authorize_resource(Some(&context), cap::STORAGE_WRITE)?; + let idempotency = mutation_key(mutation)?.to_owned(); + let key = storage_key(&request.key)?; + let durability = match StorageDurability::try_from(request.durability) { + Ok(StorageDurability::SessionOnly) => Durability::SessionOnly, + Ok(StorageDurability::Persistent) => Durability::Persistent, + _ => { + return Err(Status::invalid_argument( + "durability is required: SESSION_ONLY or PERSISTENT", + )); + } + }; + if durability == Durability::Persistent { + // A missing storage.persist is PERMISSION_DENIED, never a silent downgrade. + self.providers + .authorize_resource(Some(&context), cap::STORAGE_PERSIST)?; + } + if request.value.len() > MAX_VALUE_BYTES { + return Err(Status::invalid_argument(format!( + "value is larger than {MAX_VALUE_BYTES} bytes" + ))); + } + if request.ttl_seconds > MAX_TTL_SECONDS { + return Err(Status::invalid_argument(format!( + "ttl_seconds is longer than {MAX_TTL_SECONDS} (30 days)" + ))); + } + let hash = request_hash(&[ + "storage.put", + &key, + &mutation.expected_revision.to_string(), + if durability == Durability::Persistent { + "persistent" + } else { + "session" + }, + &request.ttl_seconds.to_string(), + &format!("{:x}", Sha256::digest(&request.value)), + ]); + let write_guard = self.guard(context.clone(), cap::STORAGE_WRITE, caller.grant_revision); + let persist_guard = self.guard(context, cap::STORAGE_PERSIST, caller.grant_revision); + let mutations = self.mutations.clone(); + let remember_as = caller.clone(); + let expected = mutation.expected_revision; + let ttl = request.ttl_seconds; + let value = request.value; + let answered = self + .in_namespace(&caller, move |namespace| { + let id = key.clone(); + if let Some((original, expires_at)) = + mutations.replay_with(&remember_as, &idempotency, hash)? + { + let usage = namespace.usage(durability)?; + return Ok(StorageMutationReply { + revision: original.revision, + usage_bytes: usage, + quota_bytes: QUOTA_BYTES, + outcome: original.outcome, + durability: proto_durability(durability) as i32, + expires_at, + }); + } + let guard: crate::plugin_host::library::CommitGuard = Box::new(move || { + write_guard()?; + if durability == Durability::Persistent { + persist_guard()?; + } + Ok(()) + }); + match namespace.put(&key, value, durability, ttl, expected, &guard)? { + PutOutcome::Applied { + revision, + expires_at, + usage, + } => { + let answer = reply(&id, revision, MutationOutcome::Applied); + let expires = expires_at.unwrap_or(0); + mutations.remember_with(&remember_as, &idempotency, hash, &answer, expires); + Ok(StorageMutationReply { + revision, + usage_bytes: usage, + quota_bytes: QUOTA_BYTES, + outcome: MutationOutcome::Applied as i32, + durability: proto_durability(durability) as i32, + expires_at: expires, + }) + } + PutOutcome::Conflict { current } => Ok(StorageMutationReply { + revision: current, + usage_bytes: namespace.usage(durability)?, + quota_bytes: QUOTA_BYTES, + outcome: MutationOutcome::RevisionConflict as i32, + durability: proto_durability(durability) as i32, + expires_at: 0, + }), + } + }) + .await?; + Ok(Response::new(answered)) + } + + pub(super) async fn delete_stored( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + let mutation = request + .mutation + .as_ref() + .ok_or_else(|| Status::invalid_argument("mutation is required"))?; + let context = mutation.context.clone().unwrap_or_default(); + let caller = self + .providers + .authorize_resource(Some(&context), cap::STORAGE_DELETE)?; + let idempotency = mutation_key(mutation)?.to_owned(); + let key = storage_key(&request.key)?; + let hash = request_hash(&[ + "storage.delete", + &key, + &mutation.expected_revision.to_string(), + ]); + let guard = self.guard(context, cap::STORAGE_DELETE, caller.grant_revision); + let mutations = self.mutations.clone(); + let remember_as = caller.clone(); + let expected = mutation.expected_revision; + let answered = self + .in_namespace(&caller, move |namespace| { + if let Some((original, _)) = + mutations.replay_with(&remember_as, &idempotency, hash)? + { + return Ok(original); + } + let (outcome, revision, commit) = match namespace.delete(&key, expected, &guard)? { + DeleteOutcome::Deleted { revision } => { + (MutationOutcome::Applied, revision, true) + } + DeleteOutcome::Absent => (MutationOutcome::AlreadyApplied, 0, true), + DeleteOutcome::Conflict { current } => { + (MutationOutcome::RevisionConflict, current, false) + } + }; + let answer = reply(&key, revision, outcome); + if commit { + mutations.remember_with(&remember_as, &idempotency, hash, &answer, 0); + } + Ok(answer) + }) + .await?; + Ok(Response::new(answered)) + } +} diff --git a/crates/app/src/plugin_host/resources/tests.rs b/crates/app/src/plugin_host/resources/tests.rs new file mode 100644 index 000000000..b917b7603 --- /dev/null +++ b/crates/app/src/plugin_host/resources/tests.rs @@ -0,0 +1,3016 @@ +//! ResourceHost library reads over the real local socket, with the SDK as the client. + +use super::*; +use crate::plugin_host::files::FileAccess; +use crate::plugin_host::library::{ + CatalogGame, CommitGuard, FavoriteWrite, InstallState, LibraryHost, LibrarySource, MatchWrite, + StoredArtwork, +}; +use crate::plugin_host::network::NetworkAccess; +use crate::plugin_host::notifications::Notifications; +use crate::plugin_host::provider::{HostServices, Lease, Registration, RegistrationOrigin}; +use crate::plugin_host::storage::PluginStorage; +use gamenode_core::library::{ArtworkWrite, DisplayWrite}; +use gamenode_platform::plugin_artwork::Prepared; +use gamenode_platform::plugin_files::Reserved; +use gamenode_plugin_sdk::{HostClient, Launch, Session, SessionOptions}; +use resource_host_client::ResourceHostClient; +use resource_host_server::ResourceHost; +use std::collections::BTreeMap; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use tonic::Code; +use tonic::transport::Channel; + +mod artwork_handles; +mod backups; +mod data; +mod declared_locations; +mod diagnostics; +mod files; +mod fingerprints; +mod games; +mod jobs; +mod libraries; +mod locations; +mod network; +mod notifications; +mod observations; +mod performance; +mod persistence; +mod ports; +mod runtimes; +mod saves; +mod sdk; +mod sdk_actions; +mod sdk_data_exchange; +mod sdk_extension_data; +mod sdk_utilities; +mod storage; +mod tools; + +#[path = "../../../../plugin-sdk/examples/action_recipes.rs"] +mod action_recipes; + +struct NoServices; + +#[tonic::async_trait] +impl HostServices for NoServices { + async fn context(&self, _: Lease) -> Result { + Err(Status::unimplemented("fixture")) + } + async fn account(&self, _: Lease, _: account_request::Action) -> Result { + Err(Status::unimplemented("fixture")) + } + async fn secret(&self, _: Lease, _: SecretRequest) -> Result { + Err(Status::unimplemented("fixture")) + } + async fn login(&self, _: Lease, _: LoginRequest) -> Result { + Err(Status::unimplemented("fixture")) + } + async fn actions(&self, _: Lease, _: ActionDeclaration) -> Result { + Err(Status::unimplemented("fixture")) + } +} + +struct Fixture { + api: ProviderApi, + feed: Arc, + storage: Arc, + files: Arc, + network: Arc, + fetcher: Arc, + notifications: Arc, + /// The jobs plugins started; tests start some from the host side. + jobs: Jobs, + /// The intents and the dialog behind game launches and installs. + intents: Arc, + /// The grants for other plugins' save profiles. + saves: Arc, + /// The fingerprints of approved places. + snapshots: Arc, + /// Host-owned lease coordinator shared by launches and backup jobs. + leases: Arc, + /// Platform process inspection used by external runtime-use checks. + processes: Option>, + /// Shared observations inserted by source fixtures for cross-plugin read tests. + data_broker: Arc, + /// The host-owned durable public pool; durable records stay in `data_dir` after restart. + shared_pool: Arc, + /// The application data folder the pool file lives in. + data_dir: std::path::PathBuf, + /// Host-owned cross-plugin consent store used by producer/consumer fixtures. + shared_policies: Arc, + /// The time the notification rate limit sees; tests move it. + notice_clock: Arc, + notices: Arc, + /// The seconds the storage clock reads; tests move it to expire values. + clock: Arc, + plugin_data: std::path::PathBuf, + endpoint: std::path::PathBuf, + capabilities: Vec<&'static str>, + host: HostClient, + resource_api: Arc, + _commands: tonic::Streaming, + _server: crate::plugin_host::PluginApiServer, + _temp: tempfile::TempDir, +} + +impl Fixture { + /// A third-party provider `fixture` signed in as account `a`, negotiating API 1.6. + async fn new(grants: &[&'static str]) -> Self { + Self::build(grants, true).await + } + + async fn build(grants: &[&'static str], api_1_6: bool) -> Self { + Self::start(grants, api_1_6, None).await + } + + /// Like [`new`](Self::new) over the plugin data folder of an earlier fixture, as after a + /// restart of the host: durable values are still there, session-only ones are not. + async fn restarted(grants: &[&'static str], plugin_data: std::path::PathBuf) -> Self { + Self::start(grants, true, Some(plugin_data)).await + } + + async fn start( + grants: &[&'static str], + api_1_6: bool, + plugin_data: Option, + ) -> Self { + Self::start_with_target(grants, api_1_6, plugin_data, None).await + } + + async fn start_with_target( + grants: &[&'static str], + api_1_6: bool, + plugin_data: Option, + target: Option, + ) -> Self { + let temp = tempfile::tempdir().unwrap(); + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(temp.path(), std::fs::Permissions::from_mode(0o700)).unwrap(); + let endpoint = temp.path().join("plugins.sock"); + let plugin_data = plugin_data.unwrap_or_else(|| temp.path().join("plugin-data")); + let clock = Arc::new(std::sync::atomic::AtomicI64::new(1_000_000)); + let storage = Arc::new(PluginStorage::new(&plugin_data).with_clock({ + let clock = clock.clone(); + move || clock.load(Ordering::SeqCst) + })); + // The host's data folder is reserved: no file handle reaches it. + std::fs::create_dir_all(&plugin_data).unwrap(); + let files = Arc::new(FileAccess::new(Reserved::new(std::slice::from_ref( + &plugin_data, + )))); + // Fetches go to a scripted stand-in; the origins plugins may reach start empty. + let fetcher = Arc::new(network::FakeFetcher::default()); + let network = Arc::new(NetworkAccess::new(fetcher.clone())); + // Notifications go to a collector; the rate limit follows a clock the tests move. + let notice_base = std::time::Instant::now(); + let notice_clock = Arc::new(std::sync::atomic::AtomicU64::new(0)); + let notifications = Arc::new({ + let clock = notice_clock.clone(); + Notifications::default().with_clock(move || { + notice_base + Duration::from_millis(clock.load(Ordering::SeqCst)) + }) + }); + let notices = Arc::new(notifications::Collected::default()); + notifications.set_sink(notices.clone()); + let data_broker = Arc::new(crate::plugin_host::shared_data::DataBroker::new()); + let data_dir = temp.path().to_path_buf(); + let shared_pool = Arc::new(crate::plugin_host::shared_pool::DurableSharedPool::new( + &data_dir, + )); + let root = crate::plugin_host::PluginApi { + storage: storage.clone(), + files: files.clone(), + network: network.clone(), + notifications: notifications.clone(), + data_broker: data_broker.clone(), + shared_pool: shared_pool.clone(), + ..Default::default() + }; + let shared_policies = root.shared_policies.clone(); + root.set_state_layout(crate::plugin_host::profile::PluginStateLayout::new( + &plugin_data, + )); + let jobs = root.jobs.clone(); + let intents = root.intents.clone(); + let saves = root.saves.clone(); + let snapshots = root.fingerprints.clone(); + let leases = root.leases.clone(); + let processes = root.processes.clone(); + let api = root.providers.clone(); + let feed = root.library.clone(); + api.profiles().update(Some("a"), true); + let extension_session = target.is_some(); + let mut capabilities = vec![cap::CONTEXT]; + capabilities.extend_from_slice(grants); + let registration_id = if extension_session { + crate::plugin_host::provider::extension_registration_id("fixture.plugin") + } else { + "fixture".into() + }; + api.register(Registration { + declared_developer: "Fixture developer".into(), + package_digest: vec![7; 32], + provider_id: registration_id.clone(), + plugin_id: "fixture.plugin".into(), + kind: if extension_session { + crate::plugin_host::provider::RegistrationKind::Extension + } else { + crate::plugin_host::provider::RegistrationKind::Provider + }, + origin: RegistrationOrigin::ThirdParty { + publisher_fingerprint: "ab".repeat(32), + }, + capabilities: capabilities.iter().map(|s| (*s).into()).collect(), + shared_catalog: false, + playtime: Default::default(), + services: Arc::new(NoServices), + }) + .unwrap(); + let launch = match &target { + Some(target) => { + api.begin_extension_launch(®istration_id, api.profiles().epoch(), target.clone()) + } + None => api.begin_launch(®istration_id), + } + .unwrap(); + let credential = launch + .credential + .as_bytes() + .as_chunks::<2>() + .0 + .iter() + .map(|s| u8::from_str_radix(std::str::from_utf8(s).unwrap(), 16).unwrap()) + .collect(); + let server = crate::plugin_host::PluginApiServer::start( + &tokio::runtime::Handle::current(), + &endpoint, + root, + ) + .unwrap(); + let resource_api = server.resource_api(); + let client_launch = Launch { + endpoint: endpoint.clone(), + credential, + operation_id: "launch".into(), + }; + let options = if api_1_6 { + SessionOptions { + min_api_major: 1, + min_api_minor: cap::THIRD_PARTY_API_MINOR, + max_api_major: 1, + max_api_minor: gamenode_plugin_protocol::API_MINOR, + session_kind: if extension_session { + SessionKind::Extension + } else { + SessionKind::Unspecified + }, + target_game: target, + ..SessionOptions::default() + } + } else { + SessionOptions::default() + }; + let session = Session::open_with_options( + client_launch, + "fixture.plugin", + if extension_session { "" } else { "fixture" }, + "1.0", + &capabilities, + options, + ) + .await + .unwrap(); + launch.ready.await.unwrap(); + Self { + api, + feed, + storage, + files, + network, + fetcher, + notifications, + jobs, + intents, + saves, + snapshots, + leases, + processes, + notice_clock, + notices, + data_broker, + shared_pool, + data_dir, + shared_policies, + clock, + plugin_data, + endpoint, + capabilities: capabilities.clone(), + host: session.host, + resource_api, + _commands: session.commands, + _server: server, + _temp: temp, + } + } + + fn client(&self) -> ResourceHostClient { + self.host.resource_client() + } + + fn context(&self) -> ServiceContext { + self.host.resource_context().unwrap().clone() + } + + /// Syncs library rows and gives each the id `id-`. + fn library(&self, rows: &[(&str, Option, &str)]) { + let missing = self.feed.sync( + rows.iter() + .map(|(key, game_id, name)| LibrarySource { + entry_key: (*key).into(), + provider_id: key.split(':').next().unwrap().into(), + game_id: *game_id, + name: (*name).into(), + install_state: InstallState::Installed, + display_name: None, + metadata_revision: 0, + artwork_revision: 0, + install_dir: String::new(), + detected_target: None, + }) + .collect(), + ); + let ids = missing + .iter() + .map(|key| (key.clone(), format!("id-{key}"))) + .collect(); + self.feed.assign_ids(&missing, ids); + } + + fn list_request(&self, page_size: u32, cursor: &str, provider_id: &str) -> LibraryListRequest { + LibraryListRequest { + page: Some(PageRequest { + context: Some(self.context()), + cursor: cursor.into(), + page_size, + common_data_categories: None, + }), + provider_id: provider_id.into(), + search: String::new(), + } + } + + async fn list(&self, provider_id: &str) -> Result { + self.client() + .library_list(self.list_request(0, "", provider_id)) + .await + .map(Response::into_inner) + } + + async fn get(&self, installation_id: &str, game_id: &str) -> Result { + self.client() + .library_get(LibraryGetRequest { + context: Some(self.context()), + game_id: game_id.into(), + installation_id: installation_id.into(), + common_data_categories: None, + }) + .await + .map(|reply| reply.into_inner().entry.unwrap()) + } + + async fn watch(&self, after_revision: u64) -> Result, Status> { + self.client() + .library_watch(LibraryWatchRequest { + context: Some(self.context()), + after_revision, + provider_id: String::new(), + common_data_categories: None, + }) + .await + .map(Response::into_inner) + } +} + +fn names(reply: &LibraryListReply) -> Vec<&str> { + reply.entries.iter().map(|e| e.name.as_str()).collect() +} + +async fn next(stream: &mut tonic::Streaming) -> Result { + tokio::time::timeout(Duration::from_secs(5), stream.message()) + .await + .expect("an event in time") + .map(|event| event.expect("the stream is open")) +} + +const SHARED: &[(&str, Option, &str)] = &[ + ("fixture:1", Some(7), "Portal 2"), + ("fixture:2", None, "Homebrew"), + ("steam:620", Some(7), "Portal 2"), + ("steam:570", None, "Dota 2"), +]; + +#[tokio::test] +async fn own_provider_reads_never_disclose_another_providers_entries() { + let fixture = Fixture::new(&[cap::LIBRARY_READ]).await; + fixture.library(SHARED); + + let reply = fixture.list("").await.unwrap(); + assert_eq!(names(&reply), ["Portal 2", "Homebrew"]); + assert!(reply.entries.iter().all(|e| e.provider_id == "fixture")); + assert_eq!(reply.revision, 1); + // Naming the other provider does not widen the scope. + assert!(fixture.list("steam").await.unwrap().entries.is_empty()); + // A foreign installation id is indistinguishable from an unknown one. + for id in ["id-steam:620", "id-nope"] { + let status = fixture.get(id, "").await.unwrap_err(); + assert_eq!(status.code(), Code::NotFound, "{id}"); + assert_eq!(status.message(), "library entry not found"); + } + // Asking by game finds only the caller's own installation of it. + let own = fixture.get("", "7").await.unwrap(); + assert_eq!(own.installation_id, "id-fixture:1"); +} + +#[tokio::test] +async fn the_whole_library_needs_its_own_grant() { + let fixture = Fixture::new(&[cap::LIBRARY_READ, cap::LIBRARY_READ_ALL]).await; + fixture.library(SHARED); + + assert_eq!(fixture.list("").await.unwrap().entries.len(), 4); + let steam = fixture.list("steam").await.unwrap(); + assert_eq!(names(&steam), ["Dota 2", "Portal 2"]); + assert_eq!( + fixture.get("id-steam:570", "").await.unwrap().name, + "Dota 2" + ); + // Two installations of game 7 are visible now, so a game id alone is ambiguous. + let status = fixture.get("", "7").await.unwrap_err(); + assert_eq!(status.code(), Code::FailedPrecondition); +} + +#[tokio::test] +async fn game_and_installation_identities_stay_separate() { + let fixture = Fixture::new(&[cap::LIBRARY_READ]).await; + fixture.library(SHARED); + + // Unmatched: empty game id, stable installation id. + let homebrew = fixture.get("id-fixture:2", "").await.unwrap(); + assert_eq!(homebrew.game_id, ""); + assert_eq!(homebrew.install_state, "installed"); + // Naming both requires them to agree. + assert_eq!( + fixture.get("id-fixture:1", "8").await.unwrap_err().code(), + Code::NotFound + ); + assert_eq!(fixture.get("id-fixture:1", "7").await.unwrap().game_id, "7"); + assert_eq!( + fixture.get("", "seven").await.unwrap_err().code(), + Code::InvalidArgument + ); + assert_eq!( + fixture.get("", "").await.unwrap_err().code(), + Code::InvalidArgument + ); + + // A rescan that matches the homebrew entry keeps its installation id. + fixture.library(&[ + ("fixture:1", Some(7), "Portal 2"), + ("fixture:2", Some(99), "Homebrew"), + ]); + let matched = fixture.get("", "99").await.unwrap(); + assert_eq!(matched.installation_id, homebrew.installation_id); + assert!(matched.revision > homebrew.revision); +} + +#[tokio::test] +async fn pages_are_bounded_and_a_stale_cursor_must_restart_the_list() { + let fixture = Fixture::new(&[cap::LIBRARY_READ]).await; + let rows: Vec<(String, Option, String)> = (0..250) + .map(|i| (format!("fixture:{i:03}"), None, format!("Game {i:03}"))) + .collect(); + let borrowed: Vec<(&str, Option, &str)> = rows + .iter() + .map(|(k, g, n)| (k.as_str(), *g, n.as_str())) + .collect(); + fixture.library(&borrowed); + let mut client = fixture.client(); + + let first = client + .library_list(fixture.list_request(1000, "", "")) + .await + .unwrap() + .into_inner(); + assert_eq!(first.entries.len(), MAX_PAGE_SIZE, "clamped to the maximum"); + let rest = client + .library_list(fixture.list_request(1000, &first.next_cursor, "")) + .await + .unwrap() + .into_inner(); + assert_eq!(rest.entries.len(), 50); + assert!(rest.next_cursor.is_empty()); + assert!(first.entries.last().unwrap().installation_id < rest.entries[0].installation_id); + let default = client + .library_list(fixture.list_request(0, "", "")) + .await + .unwrap() + .into_inner(); + assert_eq!(default.entries.len(), DEFAULT_PAGE_SIZE); + + // The cursor belongs to its query: another provider filter cannot reuse it. + let status = client + .library_list(fixture.list_request(10, &default.next_cursor, "fixture")) + .await + .unwrap_err(); + assert_eq!(status.code(), Code::FailedPrecondition); + // A forged cursor is invalid, not stale. + let status = client + .library_list(fixture.list_request(10, "00.00", "")) + .await + .unwrap_err(); + assert_eq!(status.code(), Code::InvalidArgument); + + // The library changes: the next page is refused without entries. + fixture.library(&borrowed[..249]); + let status = client + .library_list(fixture.list_request(10, &default.next_cursor, "")) + .await + .unwrap_err(); + assert_eq!(status.code(), Code::FailedPrecondition); + assert!(status.message().contains("restart the list")); +} + +#[tokio::test] +async fn common_data_projections_are_refused_rather_than_narrowed() { + let fixture = Fixture::new(&[cap::LIBRARY_READ]).await; + let mut request = fixture.list_request(10, "", ""); + request.page.as_mut().unwrap().common_data_categories = Some(CommonDataSelector { + categories: vec![CommonDataCategory::GamePaths as i32], + selected_record_ids: vec![], + }); + let status = fixture.client().library_list(request).await.unwrap_err(); + assert_eq!(status.code(), Code::Unimplemented); + // An empty selector is the default private query. + let mut request = fixture.list_request(10, "", ""); + request.page.as_mut().unwrap().common_data_categories = Some(CommonDataSelector::default()); + assert!(fixture.client().library_list(request).await.is_ok()); +} + +#[tokio::test] +async fn only_the_sessions_resource_context_with_a_grant_and_a_profile_is_accepted() { + let fixture = Fixture::new(&[cap::LIBRARY_READ]).await; + fixture.library(SHARED); + let mut client = fixture.client(); + let attempt = |context: Option| LibraryGetRequest { + context, + game_id: String::new(), + installation_id: "id-fixture:1".into(), + common_data_categories: None, + }; + + let status = client.library_get(attempt(None)).await.unwrap_err(); + assert_eq!(status.code(), Code::Unauthenticated); + // The launch context is not a resource context. + let status = client + .library_get(attempt(Some(fixture.host.context().clone()))) + .await + .unwrap_err(); + assert_eq!(status.code(), Code::FailedPrecondition); + let mut forged = fixture.context(); + forged.operation_id = "guessed".into(); + let status = client.library_get(attempt(Some(forged))).await.unwrap_err(); + assert_eq!(status.code(), Code::FailedPrecondition); + let mut wrong = fixture.context(); + wrong.session_credential = vec![0; 32]; + let status = client.library_get(attempt(Some(wrong))).await.unwrap_err(); + assert_eq!(status.code(), Code::PermissionDenied); + let mut other_provider = fixture.context(); + other_provider.provider_id = "steam".into(); + let status = client + .library_get(attempt(Some(other_provider))) + .await + .unwrap_err(); + assert_eq!(status.code(), Code::PermissionDenied); + + // Without a signed-in account the service is unavailable, not denied. + fixture.api.profiles().update(None, false); + let status = client + .library_get(attempt(Some(fixture.context()))) + .await + .unwrap_err(); + assert_eq!(status.code(), Code::Unavailable); + // Another account is another profile: the old context is stale. + fixture.api.profiles().update(Some("b"), true); + let status = client + .library_get(attempt(Some(fixture.context()))) + .await + .unwrap_err(); + assert_eq!(status.code(), Code::FailedPrecondition); +} + +#[tokio::test] +async fn library_reads_require_the_library_grant() { + let fixture = Fixture::new(&[]).await; + fixture.library(SHARED); + let status = fixture.list("").await.unwrap_err(); + assert_eq!(status.code(), Code::PermissionDenied); + let audit = fixture.api.authorization_audit(); + assert!( + audit + .iter() + .any(|event| event.permission_id == cap::LIBRARY_READ) + ); +} + +#[tokio::test] +async fn sessions_before_api_1_6_get_no_resource_context() { + let fixture = Fixture::build(&[], false).await; + assert!(fixture.host.resource_context().is_none()); +} + +#[tokio::test] +async fn watch_resumes_filters_by_scope_and_ends_on_revocation() { + let fixture = Fixture::new(&[cap::LIBRARY_READ]).await; + fixture.library(&[("fixture:1", None, "A")]); + fixture.library(&[("fixture:1", Some(3), "A"), ("steam:1", None, "S")]); + + // Resume after revision 1: the retained change to the own entry, not the foreign one. + let mut stream = fixture.watch(1).await.unwrap(); + let event = next(&mut stream).await.unwrap(); + assert_eq!((event.revision, event.event_type.as_str()), (2, "upserted")); + assert_eq!(event.entry.as_ref().unwrap().game_id, "3"); + + // Live: a foreign change is skipped, the own removal arrives. + fixture.library(&[("fixture:1", Some(3), "A"), ("steam:1", None, "S2")]); + fixture.library(&[("steam:1", None, "S2")]); + // Revision 3 was the foreign entry getting its id, 4 its rename, 5 the own removal. + let event = next(&mut stream).await.unwrap(); + assert_eq!((event.revision, event.event_type.as_str()), (5, "removed")); + assert_eq!( + event.entry.as_ref().unwrap().installation_id, + "id-fixture:1" + ); + + // Revoking the grant ends the stream with a denial. + fixture + .api + .revoke_session_permission("fixture", cap::LIBRARY_READ) + .await; + fixture.library(&[("fixture:9", None, "Z")]); + let status = next(&mut stream).await.unwrap_err(); + assert_eq!(status.code(), Code::PermissionDenied); +} + +#[tokio::test] +async fn watch_positions_outside_the_history_must_resync() { + let fixture = Fixture::new(&[cap::LIBRARY_READ]).await; + for i in 0..(crate::plugin_host::library::HISTORY_EVENTS as u64 + 2) { + fixture.library(&[("fixture:1", Some(i + 1), "A")]); + } + let status = fixture.watch(1).await.unwrap_err(); + assert_eq!(status.code(), Code::FailedPrecondition); + let status = fixture.watch(10_000).await.unwrap_err(); + assert_eq!(status.code(), Code::OutOfRange); + // Zero starts at the current revision with no backlog. + let mut stream = fixture.watch(0).await.unwrap(); + fixture.library(&[("fixture:1", None, "A")]); + assert_eq!(next(&mut stream).await.unwrap().entry.unwrap().game_id, ""); +} + +#[tokio::test] +async fn a_session_may_hold_only_a_bounded_number_of_watches() { + let fixture = Fixture::new(&[cap::LIBRARY_READ]).await; + let service = ResourceApi::new( + fixture.api.clone(), + fixture.feed.clone(), + fixture.storage.clone(), + fixture.files.clone(), + fixture.network.clone(), + fixture.notifications.clone(), + fixture.jobs.clone(), + fixture.intents.clone(), + fixture.saves.clone(), + fixture.snapshots.clone(), + fixture.leases.clone(), + fixture.processes.clone(), + ); + let request = || { + Request::new(LibraryWatchRequest { + context: Some(fixture.context()), + after_revision: 0, + provider_id: String::new(), + common_data_categories: None, + }) + }; + let mut open = Vec::new(); + for _ in 0..MAX_WATCHES_PER_SESSION { + open.push(service.library_watch(request()).await.unwrap()); + } + let status = service.library_watch(request()).await.err().unwrap(); + assert_eq!(status.code(), Code::ResourceExhausted); + // Closing one frees its slot once its task notices. + drop(open.pop()); + let deadline = tokio::time::Instant::now() + Duration::from_secs(5); + loop { + match service.library_watch(request()).await { + Ok(_) => break, + Err(_) if tokio::time::Instant::now() < deadline => { + tokio::time::sleep(Duration::from_millis(20)).await + } + Err(status) => panic!("{status:?}"), + } + } +} + +#[tokio::test] +async fn custom_launch_without_its_own_grant_is_denied_and_describe_lists_the_routes() { + let fixture = Fixture::new(&[cap::LIBRARY_READ]).await; + let status = fixture + .client() + .games_propose_custom_launch(CustomLaunchRequest { + context: Some(fixture.context()), + ..CustomLaunchRequest::default() + }) + .await + .unwrap_err(); + assert_eq!(status.code(), Code::PermissionDenied); + let status = fixture + .client() + .games_request_custom_launch(CustomLaunchRequest { + context: Some(fixture.context()), + recipe_id: "recipe-without-grant".into(), + recipe_revision: 1, + ..CustomLaunchRequest::default() + }) + .await + .unwrap_err(); + assert_eq!(status.code(), Code::PermissionDenied); + let described = fixture.host.describe_api().await.unwrap(); + let resource: Vec<_> = described + .methods + .iter() + .filter(|method| method.service == "ResourceHost") + .map(|method| (method.method.as_str(), method.max_page_size)) + .collect(); + assert_eq!( + resource, + [ + ("PortsList", MAX_PAGE_SIZE as u32), + ("PortsDetail", 0), + ("PortsRequestInstall", 0), + ("ToolsList", MAX_PAGE_SIZE as u32), + ("ToolsRequestApply", 0), + ("ToolsRequestRemove", 0), + ("BackupsList", MAX_PAGE_SIZE as u32), + ("BackupsRequestCreate", 0), + ("BackupsRequestRestore", 0), + ("StorageDiagnosticsPublishBenchmark", 0), + ("StorageDiagnosticsPublishSmart", 0), + ("ComputerPublishHardware", 0), + ("GamePresencePublish", 0), + ("GamePresenceClear", 0), + ("GamePerformancePublishSamples", 0), + ("GamePerformanceEndSeries", 0), + ("LibrariesList", MAX_PAGE_SIZE as u32), + ("LibrariesGet", 0), + ("LibrariesWatch", 0), + ("LibrariesCreate", 0), + ("LibrariesUpdate", 0), + ("LibrariesRemove", 0), + ("LibrariesAddRoot", 0), + ("LibrariesUpdateRoot", 0), + ("LibrariesRemoveRoot", 0), + ("LibraryList", MAX_PAGE_SIZE as u32), + ("LibraryGet", 0), + ("LibraryWatch", 0), + ("RuntimesList", MAX_PAGE_SIZE as u32), + ("RuntimesGet", 0), + ("RuntimesWatch", 0), + ("RuntimesRequestAccess", 0), + ("RuntimesRegister", 0), + ("RuntimesUpdate", 0), + ("RuntimesRemove", 0), + ("GamesRegisterContent", 0), + ("MetadataUpdate", 0), + ("FavoritesList", MAX_PAGE_SIZE as u32), + ("FavoritesSet", 0), + ("MatchingSearch", 0), + ("MatchingAssign", 0), + ("ArtworkRead", 0), + ("ArtworkSet", 0), + ("StorageGet", 0), + ("StoragePut", 0), + ("StorageDelete", 0), + ("PersistenceGetUsage", 0), + ("PersistenceListEntries", MAX_PAGE_SIZE as u32), + ("PersistenceDeleteEntries", 0), + ("PersistenceClear", 0), + ("PersistenceSetRetentionPolicy", 0), + ("FilesRequestAccess", 0), + ("FilesList", MAX_PAGE_SIZE as u32), + ("FilesRead", 0), + ("FilesWrite", 0), + ("FilesDelete", 0), + ("NetworkFetch", 0), + ("NotificationsPublish", 0), + ("GamesRequestLaunch", 0), + ("GamesProposeCustomLaunch", 0), + ("GamesRequestCustomLaunch", 0), + ("GamesRemoveCustomLaunch", 0), + ("GamesRequestInstall", 0), + ("JobsGet", 0), + ("JobsWatch", 0), + ("JobsCancel", 0), + ("DataPublish", 0), + ("DataGet", 0), + ("DataList", MAX_PAGE_SIZE as u32), + ("DataWatch", 0), + ] + ); + // `DescribeApi` is a set: advertising the same route twice would make a client see two + // conflicting descriptions of it. + let mut routes: Vec<_> = described + .methods + .iter() + .map(|method| (method.service.as_str(), method.method.as_str())) + .collect(); + let advertised = routes.len(); + routes.sort_unstable(); + routes.dedup(); + assert_eq!(advertised, routes.len(), "DescribeApi repeats a route"); + // A job needs the permission of the operation that made it, so the jobs methods name none. + assert!( + described + .methods + .iter() + .filter(|method| method.method.starts_with("Jobs")) + .all(|method| method.permissions.is_empty()) + ); +} + +/// The protocol carries routes this build has not mounted. They must stay invisible in +/// `DescribeApi` and answer `UNIMPLEMENTED`, never a partial success or a permission error. +#[tokio::test] +async fn deferred_plugin_routes_are_unadvertised_and_unimplemented() { + let fixture = Fixture::new(&[cap::LIBRARY_READ]).await; + let described = fixture.host.describe_api().await.unwrap(); + assert!( + !described + .methods + .iter() + .any(|advertised| advertised.service == "PluginHost" + && advertised.method == "SubmitDiscovery"), + "the legacy discovery route was advertised" + ); + // The unary discovery route remains for API 1.1 clients but reports that it is not mounted: + // full providers submit discovery through the exchange stream. + let status = crate::plugin_host::plugin_host_server::PluginHost::submit_discovery( + &crate::plugin_host::PluginApi::default(), + tonic::Request::new(gamenode_plugin_protocol::proto::SubmitDiscoveryRequest::default()), + ) + .await + .unwrap_err(); + assert_eq!(status.code(), Code::Unimplemented); +} + +// ---- Display metadata and favorites (task 5.2) ---- + +/// An entry's explicit match: the game, whether the user made it, and the entry revision. +type FakeMatch = (Option, bool, u64); + +/// An in-memory engine side: display overrides by entry key and favorite state by +/// `(provider, game)`. A game is "matched" for a provider when it has a row here. +#[derive(Default)] +struct FakeHost { + port_support: AtomicBool, + port_records: Mutex>, + port_reviews: Mutex>, + port_gate: tokio::sync::Notify, + port_effects: AtomicUsize, + port_declined: AtomicBool, + tool_support: AtomicBool, + tool_reviews: Mutex>, + tool_gate: tokio::sync::Notify, + tool_effects: AtomicUsize, + tool_declined: AtomicBool, + backup: Mutex>, + scan_roots: Mutex>>, + names: Mutex, u64)>>, + games: Mutex>, + /// State-changing writes that reached the host. + writes: AtomicUsize, + /// Revokes a permission right before the commit guard runs, as a race would. + revoke_before_commit: Mutex>, + /// What the server's catalog knows, in answer order. + catalog: Mutex>, + catalog_down: AtomicBool, + searches: AtomicUsize, + /// Games the device knows without a search, and games a search offered. + known: Mutex>, + offered: Mutex>, + /// Explicit matches by entry key: game, whether the user made it, entry revision. + matches: Mutex>, + /// Cover overrides by entry key: the stored picture (`None` once cleared) and its revision. + covers: Mutex, u64)>>, + /// The covers of the games entries are matched to, by entry key. + game_covers: Mutex>>, + /// Entries the library was asked to open: the entry key and whether it was an install. + opened: Mutex>, + /// The code the next opening fails with, if any. + open_fails: Mutex>, + /// What a launch would start now; tests change it to change the target. + launch_target: std::sync::atomic::AtomicU64, + custom_launch_recipes: + Mutex>, + launch_recipe_selections: Mutex>, + custom_launch_dispatches: Mutex>, + /// The approved detected executable a parameter-only or mod-layer overlay starts. + detected_launch_command: Mutex>, + custom_launch_gate: Mutex>>, + custom_launch_entered: tokio::sync::Notify, + runtime_resources: Mutex>, + runtime_bindings: + Mutex>>, + /// Monotonic catalog revision for runtime list/watch fixtures. + runtime_catalog_revision: std::sync::atomic::AtomicU64, + /// The official installed-program inventory the runtime picker reads. + installed_programs: Mutex>, + inventory_down: AtomicBool, +} + +impl FakeHost { + fn seed_runtime_resource( + &self, + owner_key: String, + runtime: gamenode_core::library::RuntimeResource, + ) { + self.runtime_resources + .lock() + .unwrap() + .insert((owner_key, runtime.id.clone()), runtime); + self.runtime_catalog_revision.fetch_add(1, Ordering::SeqCst); + } + + fn hook(&self) -> Option<(ProviderApi, &'static str)> { + self.revoke_before_commit + .lock() + .unwrap_or_else(|p| p.into_inner()) + .clone() + } + + fn name_of(&self, key: &str) -> Option<(Option, u64)> { + self.names.lock().unwrap().get(key).cloned() + } +} + +#[tonic::async_trait] +impl LibraryHost for FakeHost { + fn ports_supported(&self) -> bool { + self.port_support.load(Ordering::SeqCst) + } + async fn ports_catalog(&self, detail: Option) -> Result, Status> { + let records = self + .port_records + .lock() + .unwrap() + .iter() + .filter(|p| detail.as_ref().is_none_or(|id| *id == p.port_id)) + .cloned() + .collect::>(); + if detail.is_some() && records.is_empty() { + return Err(Status::not_found("port not found")); + } + Ok(records) + } + async fn request_port( + &self, + port: String, + review: gamenode_core::ports::view::PortPluginRequest, + check: crate::plugin_host::jobs::Fence, + ) -> Result<(), Status> { + if !self + .port_records + .lock() + .unwrap() + .iter() + .any(|r| r.port_id == port) + { + return Err(Status::not_found("port not found")); + } + let check_before = check.clone(); + tokio::task::spawn_blocking(move || check_before()) + .await + .unwrap()?; + self.port_reviews.lock().unwrap().push(review); + self.port_gate.notified().await; + tokio::task::spawn_blocking(move || check()) + .await + .unwrap()?; + if self.port_declined.load(Ordering::SeqCst) { + return Err(Status::cancelled("declined")); + } + self.port_effects.fetch_add(1, Ordering::SeqCst); + Ok(()) + } + + fn tools_supported(&self) -> bool { + self.tool_support.load(Ordering::SeqCst) + } + async fn tools_list(&self, _: String) -> Result, Status> { + Ok(gamenode_core::tools::builtin_tools() + .into_iter() + .map(|d| ToolRecord { + tool_id: d.id.as_str().into(), + name: d.name, + version: "fixture-v1".into(), + availability: if self.tools_supported() { + "available" + } else { + "unavailable" + } + .into(), + }) + .collect()) + } + async fn request_tool( + &self, + key: String, + tool: String, + review: gamenode_core::tools::ToolPluginRequest, + check: crate::plugin_host::jobs::Fence, + ) -> Result<(), Status> { + check()?; + self.tool_reviews + .lock() + .unwrap() + .push((key, tool, review.remove)); + self.tool_gate.notified().await; + check()?; + if self.tool_declined.load(Ordering::SeqCst) { + return Err(Status::cancelled("declined")); + } + self.tool_effects.fetch_add(1, Ordering::SeqCst); + Ok(()) + } + + async fn backup_context( + &self, + _: String, + ) -> Result { + self.backup + .lock() + .unwrap() + .clone() + .ok_or_else(|| Status::unavailable("backup engine unavailable")) + } + fn plugin_roots_supported(&self) -> bool { + true + } + fn set_plugin_roots( + &self, + owner: String, + roots: Vec, + ) -> Result<(), Status> { + self.scan_roots.lock().unwrap().insert(owner, roots); + Ok(()) + } + + async fn open_entry(&self, entry_key: String, install: bool) -> Result<(), Status> { + if let Some(code) = *self.open_fails.lock().unwrap() { + return Err(Status::new(code, "the provider could not do that")); + } + self.opened.lock().unwrap().push((entry_key, install)); + Ok(()) + } + + async fn launch_fingerprint(&self, _entry_key: String) -> Result { + Ok(self.launch_target.load(Ordering::SeqCst)) + } + + async fn launch_target_revision(&self, _entry_key: String) -> Result { + Ok(1) + } + + async fn runtime_resource( + &self, + owner_key: String, + runtime_id: String, + ) -> Result, Status> { + Ok(self + .runtime_resources + .lock() + .unwrap() + .get(&(owner_key, runtime_id)) + .cloned()) + } + + async fn runtime_resources( + &self, + owner_key: String, + ) -> Result, Status> { + Ok(self + .runtime_resources + .lock() + .unwrap() + .iter() + .filter(|((owner, _), _)| *owner == owner_key) + .map(|(_, runtime)| runtime.clone()) + .collect()) + } + + async fn shared_runtime_resources( + &self, + ) -> Result, Status> { + Ok(self + .runtime_resources + .lock() + .unwrap() + .iter() + .map(|((owner, _), runtime)| (owner.clone(), runtime.clone())) + .collect()) + } + + async fn runtime_catalog_revision(&self, _owner_key: String) -> Result { + Ok(self.runtime_catalog_revision.load(Ordering::SeqCst)) + } + + async fn shared_runtime_catalog_revision(&self) -> Result { + Ok(self.runtime_catalog_revision.load(Ordering::SeqCst)) + } + + async fn runtime_availability( + &self, + owner_key: Option, + installation_ids: Vec, + ) -> Result, Status> { + let resources = self.runtime_resources.lock().unwrap(); + let bindings = self.runtime_bindings.lock().unwrap(); + let mut availability = Vec::new(); + for ((owner, game_id, _), rows) in bindings.iter() { + if owner_key.as_ref().is_some_and(|key| key != owner) { + continue; + } + for row in rows.iter().filter(|row| { + row.game_id == *game_id && installation_ids.contains(&row.installation_id) + }) { + let runtime = resources.get(&(owner.clone(), row.runtime_id.clone())); + availability.push(gamenode_core::library::RuntimeAvailabilityEntry { + installation_id: row.installation_id.clone(), + content_id: row.content_id.clone(), + content_kind: row.content_kind.clone(), + runtime_id: row.runtime_id.clone(), + runtime_name: runtime + .map(|runtime| runtime.name.clone()) + .unwrap_or_default(), + platform: runtime + .map(|runtime| runtime.platform.clone()) + .or_else(|| row.supported_platforms.first().cloned()) + .unwrap_or_default(), + publisher_id: runtime + .map(|runtime| runtime.provenance.plugin_id.clone()) + .unwrap_or_default(), + revision: row.revision, + }); + } + } + Ok(availability) + } + + async fn installed_programs( + &self, + ) -> Result, Status> { + if self.inventory_down.load(Ordering::SeqCst) { + return Err(Status::unavailable("PackageKit is unavailable")); + } + Ok(self.installed_programs.lock().unwrap().clone()) + } + + async fn save_runtime_resource( + &self, + owner_key: String, + runtime: gamenode_core::library::RuntimeResource, + ) -> Result { + use gamenode_core::library::RuntimeMutation; + let mut resources = self.runtime_resources.lock().unwrap(); + let key = (owner_key, runtime.id.clone()); + let current = resources.get(&key).map(|resource| resource.revision); + if current.unwrap_or(0).saturating_add(1) != runtime.revision { + return Ok(RuntimeMutation::Conflict { + current: current.unwrap_or(0), + }); + } + let revision = runtime.revision; + resources.insert(key, runtime); + self.runtime_catalog_revision.fetch_add(1, Ordering::SeqCst); + Ok(RuntimeMutation::Applied { revision }) + } + + async fn runtime_content_bindings( + &self, + owner_key: String, + game_id: u64, + installation_id: String, + ) -> Result, Status> { + Ok(self + .runtime_bindings + .lock() + .unwrap() + .get(&(owner_key, game_id, installation_id)) + .cloned() + .unwrap_or_default()) + } + + async fn save_runtime_content_binding( + &self, + owner_key: String, + binding: gamenode_core::library::RuntimeContentBinding, + ) -> Result { + use gamenode_core::library::RuntimeMutation; + let key = (owner_key, binding.game_id, binding.installation_id.clone()); + let mut bindings = self.runtime_bindings.lock().unwrap(); + let rows = bindings.entry(key).or_default(); + let current = rows + .iter() + .find(|row| { + row.content_id == binding.content_id && row.runtime_id == binding.runtime_id + }) + .map(|row| row.revision); + if current.unwrap_or(0).saturating_add(1) != binding.revision { + return Ok(RuntimeMutation::Conflict { + current: current.unwrap_or(0), + }); + } + let revision = binding.revision; + if let Some(existing) = rows.iter_mut().find(|row| { + row.content_id == binding.content_id && row.runtime_id == binding.runtime_id + }) { + *existing = binding; + } else { + rows.push(binding); + } + Ok(RuntimeMutation::Applied { revision }) + } + + async fn custom_launch_recipe( + &self, + owner_key: String, + recipe_id: String, + ) -> Result, Status> { + Ok(self + .custom_launch_recipes + .lock() + .unwrap() + .get(&(owner_key, recipe_id)) + .cloned()) + } + + async fn save_custom_launch_recipe( + &self, + owner_key: String, + recipe: gamenode_core::library::CustomLaunchRecipe, + ) -> Result { + use gamenode_core::library::CustomLaunchMutation; + let mut recipes = self.custom_launch_recipes.lock().unwrap(); + let key = (owner_key, recipe.recipe_id.clone()); + if let Some(current) = recipes.get(&key) { + return Ok(CustomLaunchMutation::Conflict { + current: current.revision, + }); + } + let revision = recipe.revision; + recipes.insert(key, recipe); + Ok(CustomLaunchMutation::Applied { revision }) + } + + async fn remove_custom_launch_recipe( + &self, + owner_key: String, + recipe_id: String, + expected_revision: u64, + ) -> Result { + use gamenode_core::library::CustomLaunchMutation; + let mut recipes = self.custom_launch_recipes.lock().unwrap(); + let key = (owner_key, recipe_id); + let Some(current) = recipes.get(&key) else { + return Ok(CustomLaunchMutation::Missing); + }; + if current.revision != expected_revision { + return Ok(CustomLaunchMutation::Conflict { + current: current.revision, + }); + } + let revision = current.revision.saturating_add(1); + recipes.remove(&key); + Ok(CustomLaunchMutation::Applied { revision }) + } + + async fn launch_recipe_selection( + &self, + entry_key: String, + ) -> Result, Status> { + Ok(self + .launch_recipe_selections + .lock() + .unwrap() + .get(&entry_key) + .cloned()) + } + + async fn approve_launch_recipe_plan( + &self, + entry_key: String, + recipe_id: String, + recipe_revision: u64, + target_revision: u64, + fingerprint: String, + ) -> Result { + use gamenode_core::library::LaunchRecipeSelectionWrite; + let mut selections = self.launch_recipe_selections.lock().unwrap(); + let Some(selection) = selections.get_mut(&entry_key) else { + return Ok(LaunchRecipeSelectionWrite::RecipeMissing); + }; + if selection.recipe_id != recipe_id + || selection.recipe_revision != recipe_revision + || selection.base_target_revision != target_revision + { + return Ok(LaunchRecipeSelectionWrite::Conflict); + } + selection.approved_plan_fingerprint = fingerprint; + Ok(LaunchRecipeSelectionWrite::Applied) + } + + async fn detected_launch( + &self, + _entry_key: String, + _expected_revision: u64, + ) -> Result { + self.detected_launch_command + .lock() + .unwrap() + .clone() + .ok_or_else(|| { + Status::failed_precondition("the fixture has no detected executable target") + }) + } + + async fn prepare_custom_launch( + &self, + recipe: gamenode_core::library::CustomLaunchRecipe, + _executable_path: Option, + working_directory_path: Option, + runtime: Option, + ) -> Result { + use crate::plugin_host::library::CustomLaunchDispatch; + if !recipe.uri.is_empty() { + let environment = recipe.effective_environment(); + return Ok(CustomLaunchDispatch::Uri { + uri: url::Url::parse(&recipe.uri) + .map_err(|_| Status::invalid_argument("invalid launch URI"))?, + arguments: recipe.effective_arguments(), + working_directory: working_directory_path.unwrap_or_default(), + environment, + }); + } + if let Some(runtime) = runtime { + use gamenode_core::library::RuntimeArgumentTemplate; + + let environment = recipe.effective_environment(); + let mut arguments = runtime + .arguments + .iter() + .map(|argument| match argument { + RuntimeArgumentTemplate::Literal(value) => Ok(value.clone()), + RuntimeArgumentTemplate::ContentPath => runtime + .content_path + .clone() + .ok_or_else(|| Status::failed_precondition("content path is unavailable")), + }) + .collect::, _>>()?; + arguments.extend(recipe.effective_arguments()); + return Ok(CustomLaunchDispatch::Runtime { + command: gamenode_core::drm_free::CustomLaunchCommand { + executable: runtime.executable, + file_identity: "fixture-runtime-identity".into(), + arguments, + working_directory: working_directory_path.unwrap_or_default(), + environment, + }, + runtime_id: runtime.runtime_id, + runtime_version: runtime.version, + runtime_revision: runtime.runtime_revision, + content_id: runtime.content_id, + binding_revision: runtime.binding_revision, + lease_keys: runtime.lease_keys, + }); + } + Err(Status::unimplemented("fixture supports URI recipes only")) + } + + async fn launch_custom( + &self, + dispatch: crate::plugin_host::library::CustomLaunchDispatch, + ) -> Result<(), Status> { + let gate = self.custom_launch_gate.lock().unwrap().clone(); + if let Some(gate) = gate { + self.custom_launch_entered.notify_one(); + gate.notified().await; + } + self.custom_launch_dispatches.lock().unwrap().push(dispatch); + Ok(()) + } + + fn favorites(&self, provider_id: &str) -> Vec<(u64, bool)> { + self.games + .lock() + .unwrap() + .iter() + .filter(|((provider, _), _)| provider == provider_id) + .map(|((_, game), favorite)| (*game, *favorite)) + .collect() + } + + fn set_favorite( + &self, + provider_id: &str, + game_id: u64, + favorite: bool, + guard: &dyn Fn() -> Result<(), Status>, + ) -> Result { + if let Some((api, permission)) = self.hook() { + tokio::task::block_in_place(|| { + tokio::runtime::Handle::current() + .block_on(api.revoke_session_permission("fixture", permission)) + }); + } + guard()?; + let mut games = self.games.lock().unwrap(); + let Some(current) = games.get_mut(&(provider_id.to_owned(), game_id)) else { + return Ok(FavoriteWrite::NoMatchedEntry); + }; + if *current == favorite { + return Ok(FavoriteWrite::AlreadyApplied); + } + *current = favorite; + self.writes.fetch_add(1, Ordering::SeqCst); + Ok(FavoriteWrite::Applied) + } + + async fn search_catalog( + &self, + query: String, + limit: usize, + ) -> Result, Status> { + self.searches.fetch_add(1, Ordering::SeqCst); + if self.catalog_down.load(Ordering::SeqCst) { + return Err(Status::unavailable("the GameNode catalog could not answer")); + } + let found: Vec<_> = self + .catalog + .lock() + .unwrap() + .iter() + .filter(|game| game.name.to_lowercase().contains(&query.to_lowercase())) + .take(limit) + .cloned() + .collect(); + self.offered + .lock() + .unwrap() + .extend(found.iter().map(|game| game.id)); + Ok(found) + } + + fn assign_match( + &self, + entry_key: &str, + game_id: u64, + expected_revision: u64, + guard: &dyn Fn() -> Result<(), Status>, + ) -> Result { + if let Some((api, permission)) = self.hook() { + tokio::task::block_in_place(|| { + tokio::runtime::Handle::current() + .block_on(api.revoke_session_permission("fixture", permission)) + }); + } + guard()?; + let mut matches = self.matches.lock().unwrap(); + let (game, by_user, revision) = matches.get(entry_key).copied().unwrap_or((None, false, 1)); + if game == Some(game_id) { + return Ok(MatchWrite::AlreadyApplied { revision }); + } + if expected_revision != revision { + return Ok(MatchWrite::Conflict { current: revision }); + } + if !self.known.lock().unwrap().contains(&game_id) + && !self.offered.lock().unwrap().contains(&game_id) + { + return Ok(MatchWrite::UnknownGame); + } + if by_user { + return Ok(MatchWrite::UserChoice); + } + matches.insert(entry_key.to_owned(), (Some(game_id), false, revision + 1)); + self.writes.fetch_add(1, Ordering::SeqCst); + Ok(MatchWrite::Applied { + revision: revision + 1, + }) + } + + async fn read_artwork( + &self, + entry_key: String, + max_bytes: u64, + ) -> Result { + let covers = self.covers.lock().unwrap(); + let (bytes, media_type, revision) = match covers.get(&entry_key) { + Some((Some(image), revision)) => (image.bytes.clone(), image.media_type, *revision), + other => { + let revision = other.map_or(0, |(_, revision)| *revision); + let game = self.game_covers.lock().unwrap().get(&entry_key).cloned(); + ( + game.ok_or_else(|| Status::not_found("the entry has no cover"))?, + "image/jpeg", + revision, + ) + } + }; + if bytes.len() as u64 > max_bytes { + return Err(Status::resource_exhausted( + "the cover is larger than max_bytes", + )); + } + Ok(StoredArtwork { + bytes, + media_type, + revision, + }) + } + + async fn set_artwork( + &self, + entry_key: String, + expected_revision: u64, + image: Option, + guard: CommitGuard, + ) -> Result { + if let Some((api, permission)) = self.hook() { + api.revoke_session_permission("fixture", permission).await; + } + guard()?; + let mut covers = self.covers.lock().unwrap(); + let (current, revision) = covers.get(&entry_key).cloned().unwrap_or((None, 0)); + if revision != expected_revision { + return Ok(ArtworkWrite::Conflict { current: revision }); + } + if current == image { + return Ok(ArtworkWrite::Unchanged { revision }); + } + covers.insert(entry_key, (image, revision + 1)); + self.writes.fetch_add(1, Ordering::SeqCst); + Ok(ArtworkWrite::Applied { + revision: revision + 1, + replaced: None, + }) + } + + async fn set_display_name( + &self, + entry_key: String, + expected_revision: u64, + display_name: Option, + guard: CommitGuard, + ) -> Result { + if let Some((api, permission)) = self.hook() { + api.revoke_session_permission("fixture", permission).await; + } + guard()?; + let mut names = self.names.lock().unwrap(); + let (current, revision) = names.get(&entry_key).cloned().unwrap_or((None, 0)); + if revision != expected_revision { + return Ok(DisplayWrite::Conflict { current: revision }); + } + if current == display_name { + return Ok(DisplayWrite::Unchanged { revision }); + } + names.insert(entry_key, (display_name, revision + 1)); + self.writes.fetch_add(1, Ordering::SeqCst); + Ok(DisplayWrite::Applied { + revision: revision + 1, + }) + } +} + +impl Fixture { + /// Connects a fresh `FakeHost` as the engine side. + fn with_host(&self) -> Arc { + let host = Arc::new(FakeHost::default()); + self.feed.set_host(host.clone()); + host + } + + fn mutation(&self, key: &str, expected_revision: u64) -> MutationContext { + MutationContext { + context: Some(self.context()), + operation_id: String::new(), + idempotency_key: key.into(), + expected_revision, + } + } + + async fn set_name( + &self, + key: &str, + expected_revision: u64, + installation_id: &str, + game_id: &str, + fields: &[(&str, &str)], + ) -> Result { + self.client() + .metadata_update(MetadataUpdateRequest { + mutation: Some(self.mutation(key, expected_revision)), + game_id: game_id.into(), + installation_id: installation_id.into(), + display_fields: fields + .iter() + .map(|(name, value)| ((*name).into(), (*value).into())) + .collect(), + }) + .await + .map(Response::into_inner) + } + + /// Sets the display name of `id-fixture:1` with the given key and expected revision. + async fn rename(&self, key: &str, expected: u64, name: &str) -> Result { + self.set_name(key, expected, "id-fixture:1", "", &[("display_name", name)]) + .await + } + + async fn favorite( + &self, + key: &str, + expected_revision: u64, + profile_id: &str, + game_id: &str, + favorite: bool, + ) -> Result { + self.client() + .favorites_set(FavoritesSetRequest { + mutation: Some(self.mutation(key, expected_revision)), + profile_id: profile_id.into(), + game_id: game_id.into(), + favorite, + }) + .await + .map(Response::into_inner) + } + + fn favorites_request( + &self, + page_size: u32, + cursor: &str, + profile_id: &str, + ) -> FavoritesListRequest { + FavoritesListRequest { + page: Some(PageRequest { + context: Some(self.context()), + cursor: cursor.into(), + page_size, + common_data_categories: None, + }), + profile_id: profile_id.into(), + } + } + + async fn favorites( + &self, + page_size: u32, + cursor: &str, + profile_id: &str, + ) -> Result { + self.client() + .favorites_list(self.favorites_request(page_size, cursor, profile_id)) + .await + .map(Response::into_inner) + } +} + +fn outcome(reply: &MutationReply) -> MutationOutcome { + MutationOutcome::try_from(reply.outcome).unwrap() +} + +fn games(reply: &FavoritesListReply) -> Vec<(&str, bool)> { + reply + .entries + .iter() + .map(|entry| (entry.game_id.as_str(), entry.favorite)) + .collect() +} + +#[tokio::test] +async fn display_names_are_applied_once_idempotent_and_guarded_by_their_revision() { + let fixture = Fixture::new(&[cap::LIBRARY_METADATA_WRITE]).await; + fixture.library(SHARED); + let host = fixture.with_host(); + + let first = fixture.rename("k1", 0, "Portal Two").await.unwrap(); + assert_eq!(outcome(&first), MutationOutcome::Applied); + assert_eq!( + (first.resource_id.as_str(), first.revision), + ("id-fixture:1", 1) + ); + assert_eq!( + host.name_of("fixture:1"), + Some((Some("Portal Two".into()), 1)) + ); + + // The same key with the same request returns the original outcome without writing again. + assert_eq!(fixture.rename("k1", 0, "Portal Two").await.unwrap(), first); + assert_eq!(host.writes.load(Ordering::SeqCst), 1); + // The same key for another request is refused, whatever its content. + for other in [ + rename_request(&fixture, "k1", 1, "Other"), + rename_request(&fixture, "k1", 0, "Portal 2"), + ] { + let status = other.await.unwrap_err(); + assert_eq!(status.code(), Code::FailedPrecondition); + } + + // A new key writing the value that is already there changes nothing. + let unchanged = fixture.rename("k2", 1, "Portal Two").await.unwrap(); + assert_eq!(outcome(&unchanged), MutationOutcome::AlreadyApplied); + assert_eq!(unchanged.revision, 1); + + // An obsolete revision reports the current one and never overwrites the newer value. + let conflict = fixture.rename("k3", 0, "Stale write").await.unwrap(); + assert_eq!(outcome(&conflict), MutationOutcome::RevisionConflict); + assert_eq!(conflict.revision, 1); + assert_eq!( + host.name_of("fixture:1"), + Some((Some("Portal Two".into()), 1)) + ); + // A conflict is not a committed outcome: its key can be used again after re-reading. + let retried = fixture.rename("k3", 1, "Stale write").await.unwrap(); + assert_eq!( + (outcome(&retried), retried.revision), + (MutationOutcome::Applied, 2) + ); + + // An empty (or blank) value restores the detected name; the revision keeps counting. + let reset = fixture.rename("k4", 2, " ").await.unwrap(); + assert_eq!( + (outcome(&reset), reset.revision), + (MutationOutcome::Applied, 3) + ); + assert_eq!(host.name_of("fixture:1"), Some((None, 3))); + assert_eq!(host.writes.load(Ordering::SeqCst), 3); +} + +/// A rename that has not been awaited yet, so a loop can drive several. +async fn rename_request( + fixture: &Fixture, + key: &str, + expected: u64, + name: &str, +) -> Result { + fixture.rename(key, expected, name).await +} + +#[tokio::test] +async fn display_metadata_requests_are_validated_before_anything_is_written() { + let fixture = Fixture::new(&[cap::LIBRARY_METADATA_WRITE]).await; + fixture.library(SHARED); + let host = fixture.with_host(); + let invalid = |status: Status, what: &str| { + assert_eq!(status.code(), Code::InvalidArgument, "{what}: {status:?}"); + }; + + let status = fixture + .client() + .metadata_update(MetadataUpdateRequest { + mutation: None, + installation_id: "id-fixture:1".into(), + ..Default::default() + }) + .await + .unwrap_err(); + invalid(status, "missing mutation"); + for key in ["", "has\ncontrol", &"k".repeat(129)] { + let status = fixture.rename(key, 0, "Name").await.unwrap_err(); + invalid(status, "idempotency key"); + } + let mut long_operation = fixture.mutation("k", 0); + long_operation.operation_id = "o".repeat(129); + let status = fixture + .client() + .metadata_update(MetadataUpdateRequest { + mutation: Some(long_operation), + installation_id: "id-fixture:1".into(), + display_fields: HashMap::from([("display_name".to_owned(), "N".to_owned())]), + ..Default::default() + }) + .await + .unwrap_err(); + invalid(status, "operation id"); + + let status = fixture + .set_name("a", 0, "id-fixture:1", "", &[]) + .await + .unwrap_err(); + invalid(status, "no fields"); + let status = fixture + .set_name("b", 0, "id-fixture:1", "", &[("sort_title", "x")]) + .await + .unwrap_err(); + invalid(status, "unknown field"); + assert!(status_message_names(&fixture, "c", "sort_title").await); + let status = fixture + .set_name( + "d", + 0, + "id-fixture:1", + "", + &[("display_name", "ok"), ("notes", "x")], + ) + .await + .unwrap_err(); + invalid(status, "a writable field next to an unknown one"); + invalid( + fixture.rename("e", 0, &"x".repeat(257)).await.unwrap_err(), + "257 bytes", + ); + invalid( + fixture.rename("f", 0, "tab\there").await.unwrap_err(), + "control characters", + ); + invalid( + fixture + .set_name("g", 0, "", "", &[("display_name", "N")]) + .await + .unwrap_err(), + "no installation", + ); + invalid( + fixture + .set_name("h", 0, "id-fixture:1", "seven", &[("display_name", "N")]) + .await + .unwrap_err(), + "game id", + ); + assert_eq!(host.writes.load(Ordering::SeqCst), 0); + assert!(host.name_of("fixture:1").is_none()); + + // The longest accepted name is 256 bytes, and surrounding blanks are trimmed. + let longest = "x".repeat(256); + let reply = fixture + .rename("i", 0, &format!(" {longest} ")) + .await + .unwrap(); + assert_eq!(outcome(&reply), MutationOutcome::Applied); + assert_eq!(host.name_of("fixture:1").unwrap().0, Some(longest)); +} + +/// The error for a non-writable field names it and the one writable field. +async fn status_message_names(fixture: &Fixture, key: &str, field: &str) -> bool { + let status = fixture + .set_name(key, 0, "id-fixture:1", "", &[(field, "x")]) + .await + .unwrap_err(); + status.message().contains(field) && status.message().contains("display_name") +} + +#[tokio::test] +async fn display_metadata_writes_never_reach_another_providers_entries() { + let fixture = Fixture::new(&[ + cap::LIBRARY_METADATA_WRITE, + cap::LIBRARY_READ, + cap::LIBRARY_READ_ALL, + ]) + .await; + fixture.library(SHARED); + let host = fixture.with_host(); + // Reading the whole library does not make another provider's entry writable, and the + // refusal is the same as for an installation that does not exist. + assert_eq!( + fixture.get("id-steam:620", "").await.unwrap().name, + "Portal 2" + ); + for id in ["id-steam:620", "id-steam:570", "id-nope"] { + let status = fixture + .set_name("k", 0, id, "", &[("display_name", "Mine")]) + .await + .unwrap_err(); + assert_eq!(status.code(), Code::NotFound, "{id}"); + assert_eq!(status.message(), "library entry not found"); + } + // A game id that disagrees with the installation names no entry; one that agrees works. + let status = fixture + .set_name("k", 0, "id-fixture:1", "8", &[("display_name", "Mine")]) + .await + .unwrap_err(); + assert_eq!(status.code(), Code::NotFound); + let reply = fixture + .set_name("k", 0, "id-fixture:1", "7", &[("display_name", "Mine")]) + .await + .unwrap(); + assert_eq!(outcome(&reply), MutationOutcome::Applied); + assert_eq!(host.writes.load(Ordering::SeqCst), 1); + assert!(host.name_of("steam:620").is_none()); +} + +#[tokio::test] +async fn display_metadata_needs_its_grant_and_the_engine_side() { + let fixture = Fixture::new(&[cap::LIBRARY_READ]).await; + fixture.library(SHARED); + let host = fixture.with_host(); + let status = fixture.rename("k", 0, "Mine").await.unwrap_err(); + assert_eq!(status.code(), Code::PermissionDenied); + assert!( + fixture + .api + .authorization_audit() + .iter() + .any(|event| event.permission_id == cap::LIBRARY_METADATA_WRITE) + ); + assert_eq!(host.writes.load(Ordering::SeqCst), 0); + + // With the grant but no engine side connected, the service is unavailable. + let fixture = Fixture::new(&[cap::LIBRARY_METADATA_WRITE]).await; + fixture.library(SHARED); + let status = fixture.rename("k", 0, "Mine").await.unwrap_err(); + assert_eq!(status.code(), Code::Unavailable); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_display_name_is_not_committed_when_authorization_is_lost_before_commit() { + // The permission itself is revoked between the check and the commit. + let fixture = Fixture::new(&[cap::LIBRARY_METADATA_WRITE]).await; + fixture.library(SHARED); + let host = fixture.with_host(); + *host.revoke_before_commit.lock().unwrap() = + Some((fixture.api.clone(), cap::LIBRARY_METADATA_WRITE)); + let status = fixture.rename("k", 0, "Mine").await.unwrap_err(); + assert_eq!(status.code(), Code::PermissionDenied); + assert_eq!(host.writes.load(Ordering::SeqCst), 0); + assert!(host.name_of("fixture:1").is_none()); + + // Any other grant change moves the grant revision, which also stops the commit. + let fixture = Fixture::new(&[cap::LIBRARY_METADATA_WRITE, cap::LIBRARY_READ]).await; + fixture.library(SHARED); + let host = fixture.with_host(); + *host.revoke_before_commit.lock().unwrap() = Some((fixture.api.clone(), cap::LIBRARY_READ)); + let status = fixture.rename("k", 0, "Mine").await.unwrap_err(); + assert_eq!(status.code(), Code::FailedPrecondition); + assert!(status.message().contains("permissions changed")); + assert_eq!(host.writes.load(Ordering::SeqCst), 0); +} + +#[tokio::test] +async fn favorites_list_shows_only_games_matched_by_the_callers_own_entries() { + let fixture = Fixture::new(&[cap::FAVORITES_READ, cap::LIBRARY_READ]).await; + fixture.library(SHARED); + let host = fixture.with_host(); + { + let mut games = host.games.lock().unwrap(); + for (provider, game, favorite) in [ + ("fixture", 7, true), + ("fixture", 12, true), + ("fixture", 9, false), + ("steam", 5, true), + ("steam", 7, true), + ] { + games.insert((provider.to_owned(), game), favorite); + } + } + + // Numeric order, no other provider's games, and no revision to guard favorites with. + let reply = fixture.favorites(0, "", "").await.unwrap(); + assert_eq!(games(&reply), [("7", true), ("9", false), ("12", true)]); + assert!(reply.entries.iter().all(|entry| entry.revision == 0)); + assert_eq!(reply.revision, fixture.feed.revision()); + assert!(reply.next_cursor.is_empty()); + // An empty selector is the default query; a named profile must be the active one. + let mut request = fixture.favorites_request(0, "", ""); + request.page.as_mut().unwrap().common_data_categories = Some(CommonDataSelector::default()); + assert!(fixture.client().favorites_list(request).await.is_ok()); + let mut request = fixture.favorites_request(0, "", ""); + request.page.as_mut().unwrap().common_data_categories = Some(CommonDataSelector { + categories: vec![CommonDataCategory::GamePaths as i32], + selected_record_ids: vec![], + }); + let status = fixture.client().favorites_list(request).await.unwrap_err(); + assert_eq!(status.code(), Code::Unimplemented); + let active = crate::plugin_host::profile::profile_id_for_account("a"); + assert!(fixture.favorites(0, "", &active).await.is_ok()); + for wrong in [ + "nope".to_owned(), + crate::plugin_host::profile::profile_id_for_account("b"), + ] { + let status = fixture.favorites(0, "", &wrong).await.unwrap_err(); + assert_eq!(status.code(), Code::FailedPrecondition, "{wrong}"); + } + + // Pages continue after the last game id. + let first = fixture.favorites(2, "", "").await.unwrap(); + assert_eq!(games(&first), [("7", true), ("9", false)]); + assert!(!first.next_cursor.is_empty()); + let second = fixture.favorites(2, &first.next_cursor, "").await.unwrap(); + assert_eq!(games(&second), [("12", true)]); + assert!(second.next_cursor.is_empty()); + let exact = fixture.favorites(3, "", "").await.unwrap(); + assert!( + exact.next_cursor.is_empty(), + "no cursor after the last entry" + ); +} + +#[tokio::test] +async fn favorites_cursors_are_bound_to_their_list_and_the_library_revision() { + let fixture = Fixture::new(&[cap::FAVORITES_READ, cap::LIBRARY_READ]).await; + fixture.library(SHARED); + let host = fixture.with_host(); + for game in [1, 2, 3] { + host.games + .lock() + .unwrap() + .insert(("fixture".to_owned(), game), false); + } + let favorites = fixture.favorites(1, "", "").await.unwrap(); + let library = fixture + .client() + .library_list(fixture.list_request(1, "", "")) + .await + .unwrap() + .into_inner(); + assert!(!favorites.next_cursor.is_empty() && !library.next_cursor.is_empty()); + + // Neither list accepts the other's cursor. + let status = fixture + .favorites(1, &library.next_cursor, "") + .await + .unwrap_err(); + assert_eq!(status.code(), Code::FailedPrecondition); + let status = fixture + .client() + .library_list(fixture.list_request(1, &favorites.next_cursor, "")) + .await + .unwrap_err(); + assert_eq!(status.code(), Code::FailedPrecondition); + // A forged cursor is not a cursor. + let status = fixture.favorites(1, "00.00", "").await.unwrap_err(); + assert_eq!(status.code(), Code::InvalidArgument); + + // The library changing makes the cursor stale and returns no entries. + assert!( + fixture + .favorites(1, &favorites.next_cursor, "") + .await + .is_ok() + ); + fixture.library(&SHARED[..3]); + let status = fixture + .favorites(1, &favorites.next_cursor, "") + .await + .unwrap_err(); + assert_eq!(status.code(), Code::FailedPrecondition); + assert!(status.message().contains("restart the list")); +} + +#[tokio::test] +async fn favorites_list_needs_its_grant_and_the_engine_side() { + let fixture = Fixture::new(&[cap::LIBRARY_READ]).await; + fixture.library(SHARED); + fixture.with_host(); + let status = fixture.favorites(0, "", "").await.unwrap_err(); + assert_eq!(status.code(), Code::PermissionDenied); + assert!( + fixture + .api + .authorization_audit() + .iter() + .any(|event| event.permission_id == cap::FAVORITES_READ) + ); + + let fixture = Fixture::new(&[cap::FAVORITES_READ]).await; + let status = fixture.favorites(0, "", "").await.unwrap_err(); + assert_eq!(status.code(), Code::Unavailable); + let status = fixture + .client() + .favorites_list(FavoritesListRequest::default()) + .await + .unwrap_err(); + assert_eq!(status.code(), Code::InvalidArgument, "page is required"); +} + +#[tokio::test] +async fn favorites_are_set_on_the_game_idempotently_for_own_matched_entries_only() { + let fixture = Fixture::new(&[cap::FAVORITES_WRITE]).await; + fixture.library(SHARED); + let host = fixture.with_host(); + { + let mut games = host.games.lock().unwrap(); + games.insert(("fixture".to_owned(), 7), false); + // Only another provider's entry is matched to game 9. + games.insert(("steam".to_owned(), 9), false); + } + + let applied = fixture.favorite("k1", 0, "", "7", true).await.unwrap(); + assert_eq!(outcome(&applied), MutationOutcome::Applied); + assert_eq!((applied.resource_id.as_str(), applied.revision), ("7", 0)); + assert_eq!(host.favorites("fixture"), [(7, true)]); + // The same key and request returns the original outcome and writes nothing more. + assert_eq!( + fixture.favorite("k1", 0, "", "7", true).await.unwrap(), + applied + ); + assert_eq!(host.writes.load(Ordering::SeqCst), 1); + // Another request with that key is refused. + let status = fixture.favorite("k1", 0, "", "7", false).await.unwrap_err(); + assert_eq!(status.code(), Code::FailedPrecondition); + assert_eq!(host.favorites("fixture"), [(7, true)]); + // A new key for the state that already holds changes nothing. + let same = fixture.favorite("k2", 0, "", "7", true).await.unwrap(); + assert_eq!(outcome(&same), MutationOutcome::AlreadyApplied); + let off = fixture.favorite("k3", 0, "", "7", false).await.unwrap(); + assert_eq!(outcome(&off), MutationOutcome::Applied); + assert_eq!(host.writes.load(Ordering::SeqCst), 2); + + // No own entry matched: unknown game and another provider's game look the same. + for game in ["8", "9"] { + let status = fixture.favorite("k4", 0, "", game, true).await.unwrap_err(); + assert_eq!(status.code(), Code::NotFound, "{game}"); + } + assert_eq!(host.favorites("steam"), [(9, false)]); + + // Shape checks. + let invalid = |status: Status, what: &str| { + assert_eq!(status.code(), Code::InvalidArgument, "{what}: {status:?}"); + }; + invalid( + fixture.favorite("k5", 1, "", "7", true).await.unwrap_err(), + "favorites carry no revision", + ); + invalid( + fixture.favorite("", 0, "", "7", true).await.unwrap_err(), + "key", + ); + invalid( + fixture.favorite("k6", 0, "", "", true).await.unwrap_err(), + "game id", + ); + invalid( + fixture + .favorite("k7", 0, "", "seven", true) + .await + .unwrap_err(), + "game id", + ); + let status = fixture + .client() + .favorites_set(FavoritesSetRequest::default()) + .await + .unwrap_err(); + invalid(status, "missing mutation"); + let status = fixture + .favorite("k8", 0, "nope", "7", true) + .await + .unwrap_err(); + assert_eq!(status.code(), Code::FailedPrecondition); + let active = crate::plugin_host::profile::profile_id_for_account("a"); + assert!(fixture.favorite("k9", 0, &active, "7", true).await.is_ok()); + assert_eq!(host.writes.load(Ordering::SeqCst), 3); +} + +#[tokio::test] +async fn favorites_set_needs_its_grant_and_the_engine_side() { + let fixture = Fixture::new(&[cap::FAVORITES_READ]).await; + fixture.library(SHARED); + let host = fixture.with_host(); + host.games + .lock() + .unwrap() + .insert(("fixture".to_owned(), 7), false); + let status = fixture.favorite("k", 0, "", "7", true).await.unwrap_err(); + assert_eq!(status.code(), Code::PermissionDenied); + assert!( + fixture + .api + .authorization_audit() + .iter() + .any(|event| event.permission_id == cap::FAVORITES_WRITE) + ); + assert_eq!(host.favorites("fixture"), [(7, false)]); + + let fixture = Fixture::new(&[cap::FAVORITES_WRITE]).await; + let status = fixture.favorite("k", 0, "", "7", true).await.unwrap_err(); + assert_eq!(status.code(), Code::Unavailable); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_favorite_is_not_committed_when_authorization_is_lost_before_commit() { + let fixture = Fixture::new(&[cap::FAVORITES_WRITE]).await; + fixture.library(SHARED); + let host = fixture.with_host(); + host.games + .lock() + .unwrap() + .insert(("fixture".to_owned(), 7), false); + *host.revoke_before_commit.lock().unwrap() = Some((fixture.api.clone(), cap::FAVORITES_WRITE)); + let status = fixture.favorite("k", 0, "", "7", true).await.unwrap_err(); + assert_eq!(status.code(), Code::PermissionDenied); + assert_eq!(host.favorites("fixture"), [(7, false)]); + assert_eq!(host.writes.load(Ordering::SeqCst), 0); +} + +// ---- Matching (task 5.3) ---- + +fn catalog_game(id: u64, name: &str, year: Option) -> CatalogGame { + CatalogGame { + id, + name: name.into(), + release_year: year, + } +} + +impl Fixture { + async fn search(&self, query: &str, page_size: u32) -> Result { + self.client() + .matching_search(MatchingSearchRequest { + context: Some(self.context()), + query: query.into(), + platform: String::new(), + page_size, + cursor: String::new(), + }) + .await + .map(Response::into_inner) + } + + async fn assign_request( + &self, + key: &str, + expected_revision: u64, + installation_id: &str, + game_id: &str, + ) -> Result { + self.assign_with(MatchingAssignRequest { + mutation: Some(self.mutation(key, expected_revision)), + installation_id: installation_id.into(), + gamenode_game_id: game_id.into(), + ..MatchingAssignRequest::default() + }) + .await + } + + async fn assign_with(&self, request: MatchingAssignRequest) -> Result { + self.client() + .matching_assign(request) + .await + .map(Response::into_inner) + } + + /// Assigns game `game` to `id-fixture:2` with a key and expected revision. + async fn assign(&self, key: &str, expected: u64, game: &str) -> Result { + self.assign_request(key, expected, "id-fixture:2", game) + .await + } +} + +#[tokio::test] +async fn a_catalog_search_returns_a_bounded_page_of_typed_candidates() { + let fixture = Fixture::new(&[cap::MATCHING_READ]).await; + let host = fixture.with_host(); + *host.catalog.lock().unwrap() = (1..=60) + .map(|id| catalog_game(id, &format!("Portal {id}"), (id % 2 == 0).then_some(2007))) + .chain([catalog_game(900, "Dota 2", Some(2013))]) + .collect(); + + let found = fixture.search(" dota ", 0).await.unwrap(); + assert_eq!( + found.candidates, + [MatchCandidate { + game_id: "900".into(), + title: "Dota 2".into(), + platform: String::new(), + confidence: String::new(), + release_year: 2013, + }] + ); + assert_eq!(found.next_cursor, ""); + + // The default page is 20, the largest 50, and a smaller request is honored. + assert_eq!( + fixture.search("portal", 0).await.unwrap().candidates.len(), + 20 + ); + assert_eq!( + fixture.search("portal", 7).await.unwrap().candidates.len(), + 7 + ); + assert_eq!( + fixture + .search("portal", 5_000) + .await + .unwrap() + .candidates + .len(), + 50 + ); + // An unknown release year is 0, never made up. + let unknown = fixture.search("Portal 1", 1).await.unwrap(); + assert_eq!(unknown.candidates[0].release_year, 0); + let none = fixture.search("zzz", 0).await.unwrap(); + assert!(none.candidates.is_empty()); +} + +#[tokio::test] +async fn catalog_search_requests_are_validated_before_the_catalog_is_asked() { + let fixture = Fixture::new(&[cap::MATCHING_READ]).await; + let host = fixture.with_host(); + let invalid = |status: Status, what: &str| { + assert_eq!(status.code(), Code::InvalidArgument, "{what}: {status:?}"); + }; + invalid(fixture.search("", 0).await.unwrap_err(), "empty query"); + invalid(fixture.search(" ", 0).await.unwrap_err(), "blank query"); + invalid( + fixture.search(&"a".repeat(129), 0).await.unwrap_err(), + "long query", + ); + invalid( + fixture.search("po\u{7}rtal", 0).await.unwrap_err(), + "control character", + ); + assert!(fixture.search(&"a".repeat(128), 0).await.is_ok()); + let before = host.searches.load(Ordering::SeqCst); + for (platform, cursor) in [("pc", ""), ("", "next")] { + let status = fixture + .client() + .matching_search(MatchingSearchRequest { + context: Some(fixture.context()), + query: "portal".into(), + platform: platform.into(), + page_size: 0, + cursor: cursor.into(), + }) + .await + .unwrap_err(); + invalid(status, "reserved field"); + } + assert_eq!(host.searches.load(Ordering::SeqCst), before); +} + +#[tokio::test] +async fn an_unavailable_catalog_is_unavailable_not_empty() { + let fixture = Fixture::new(&[cap::MATCHING_READ]).await; + // No engine side at all. + let status = fixture.search("portal", 0).await.unwrap_err(); + assert_eq!(status.code(), Code::Unavailable); + // The engine could not reach the catalog. + let host = fixture.with_host(); + host.catalog_down.store(true, Ordering::SeqCst); + let status = fixture.search("portal", 0).await.unwrap_err(); + assert_eq!(status.code(), Code::Unavailable); + host.catalog_down.store(false, Ordering::SeqCst); + assert!( + fixture + .search("portal", 0) + .await + .unwrap() + .candidates + .is_empty() + ); +} + +#[tokio::test] +async fn catalog_searches_need_the_grant_and_are_rate_limited() { + let fixture = Fixture::new(&[cap::LIBRARY_READ]).await; + fixture.with_host(); + let status = fixture.search("portal", 0).await.unwrap_err(); + assert_eq!(status.code(), Code::PermissionDenied); + assert!( + fixture + .api + .authorization_audit() + .iter() + .any(|event| event.permission_id == cap::MATCHING_READ) + ); + + let fixture = Fixture::new(&[cap::MATCHING_READ]).await; + let host = fixture.with_host(); + for _ in 0..SEARCHES_PER_WINDOW_FOR_TEST { + fixture.search("portal", 0).await.unwrap(); + } + let status = fixture.search("portal", 0).await.unwrap_err(); + assert_eq!(status.code(), Code::ResourceExhausted); + assert_eq!( + host.searches.load(Ordering::SeqCst), + SEARCHES_PER_WINDOW_FOR_TEST, + "a limited search never reaches the catalog" + ); +} + +const SEARCHES_PER_WINDOW_FOR_TEST: usize = super::matching::SEARCHES_PER_WINDOW; + +#[tokio::test] +async fn an_own_entry_is_assigned_once_idempotently_and_guarded_by_its_revision() { + let fixture = Fixture::new(&[cap::MATCHING_WRITE]).await; + fixture.library(SHARED); + let host = fixture.with_host(); + host.known.lock().unwrap().extend([7, 8]); + + let first = fixture.assign("k1", 1, "7").await.unwrap(); + assert_eq!(outcome(&first), MutationOutcome::Applied); + assert_eq!( + (first.resource_id.as_str(), first.revision), + ("id-fixture:2", 2) + ); + // The same key and request returns the original outcome without writing again. + assert_eq!(fixture.assign("k1", 1, "7").await.unwrap(), first); + assert_eq!(host.writes.load(Ordering::SeqCst), 1); + // The same key for another request is refused. + for other in [fixture.assign("k1", 1, "8"), fixture.assign("k1", 2, "7")] { + assert_eq!(other.await.unwrap_err().code(), Code::FailedPrecondition); + } + // A new key for the state that already holds changes nothing, whatever revision it names. + let same = fixture.assign("k2", 2, "7").await.unwrap(); + assert_eq!(outcome(&same), MutationOutcome::AlreadyApplied); + assert_eq!(same.revision, 2); + + // A stale revision reports the current one and writes nothing; it is not remembered, so the + // same key can retry with the right revision. + let stale = fixture.assign("k3", 1, "8").await.unwrap(); + assert_eq!(outcome(&stale), MutationOutcome::RevisionConflict); + assert_eq!(stale.revision, 2); + assert_eq!(host.writes.load(Ordering::SeqCst), 1); + let retried = fixture.assign("k3", 2, "8").await.unwrap(); + assert_eq!(outcome(&retried), MutationOutcome::Applied); + assert_eq!(retried.revision, 3); +} + +#[tokio::test] +async fn a_game_must_be_known_or_found_by_a_search_before_it_is_assigned() { + let fixture = Fixture::new(&[cap::MATCHING_READ, cap::MATCHING_WRITE]).await; + fixture.library(SHARED); + let host = fixture.with_host(); + *host.catalog.lock().unwrap() = vec![catalog_game(40, "Defense of the Ancients", None)]; + + let status = fixture.assign("k1", 1, "40").await.unwrap_err(); + assert_eq!(status.code(), Code::NotFound); + assert_eq!(host.writes.load(Ordering::SeqCst), 0); + fixture.search("defense", 0).await.unwrap(); + let applied = fixture.assign("k1", 1, "40").await.unwrap(); + assert_eq!(outcome(&applied), MutationOutcome::Applied); +} + +#[tokio::test] +async fn a_match_the_user_chose_is_not_replaced_and_the_refusal_is_not_remembered() { + let fixture = Fixture::new(&[cap::MATCHING_WRITE]).await; + fixture.library(SHARED); + let host = fixture.with_host(); + host.known.lock().unwrap().extend([7, 8]); + host.matches + .lock() + .unwrap() + .insert("fixture:2".to_owned(), (Some(7), true, 1)); + + let status = fixture.assign("k1", 1, "8").await.unwrap_err(); + assert_eq!(status.code(), Code::FailedPrecondition); + assert_eq!(host.writes.load(Ordering::SeqCst), 0); + // Choosing the game the user already chose changes nothing. + let same = fixture.assign("k2", 1, "7").await.unwrap(); + assert_eq!(outcome(&same), MutationOutcome::AlreadyApplied); + // When the user lets go (the choice is removed) the same key is not poisoned. + host.matches.lock().unwrap().remove("fixture:2"); + let applied = fixture.assign("k1", 1, "8").await.unwrap(); + assert_eq!(outcome(&applied), MutationOutcome::Applied); +} + +#[tokio::test] +async fn only_own_entries_are_assigned_even_with_whole_library_reads() { + let fixture = Fixture::new(&[cap::MATCHING_WRITE, cap::LIBRARY_READ_ALL]).await; + fixture.library(SHARED); + let host = fixture.with_host(); + host.known.lock().unwrap().insert(7); + for installation in ["id-steam:570", "id-steam:620", "id-fixture:nope", "nope"] { + let status = fixture + .assign_request("k", 1, installation, "7") + .await + .unwrap_err(); + assert_eq!(status.code(), Code::NotFound, "{installation}"); + } + assert_eq!(host.writes.load(Ordering::SeqCst), 0); + assert!(host.matches.lock().unwrap().is_empty()); +} + +#[tokio::test] +async fn assign_requests_are_validated_before_anything_is_written() { + let fixture = Fixture::new(&[cap::MATCHING_WRITE]).await; + fixture.library(SHARED); + let host = fixture.with_host(); + host.known.lock().unwrap().insert(7); + let invalid = |status: Status, what: &str| { + assert_eq!(status.code(), Code::InvalidArgument, "{what}: {status:?}"); + }; + invalid(fixture.assign("", 1, "7").await.unwrap_err(), "key"); + invalid(fixture.assign("k", 1, "").await.unwrap_err(), "game id"); + invalid( + fixture.assign("k", 1, "seven").await.unwrap_err(), + "game id", + ); + invalid( + fixture.assign_request("k", 1, "", "7").await.unwrap_err(), + "installation id", + ); + invalid( + fixture + .assign_request("k", 1, &"i".repeat(129), "7") + .await + .unwrap_err(), + "installation id length", + ); + for (provider, game) in [("fixture", ""), ("", "2")] { + let status = fixture + .assign_with(MatchingAssignRequest { + mutation: Some(fixture.mutation("k", 1)), + provider_id: provider.into(), + provider_game_id: game.into(), + gamenode_game_id: "7".into(), + installation_id: "id-fixture:2".into(), + }) + .await + .unwrap_err(); + invalid(status, "reserved fields"); + } + invalid( + fixture + .client() + .matching_assign(MatchingAssignRequest::default()) + .await + .unwrap_err(), + "missing mutation", + ); + assert_eq!(host.writes.load(Ordering::SeqCst), 0); +} + +#[tokio::test] +async fn assign_needs_its_grant_and_the_engine_side() { + let fixture = Fixture::new(&[cap::MATCHING_READ]).await; + fixture.library(SHARED); + let host = fixture.with_host(); + host.known.lock().unwrap().insert(7); + let status = fixture.assign("k", 1, "7").await.unwrap_err(); + assert_eq!(status.code(), Code::PermissionDenied); + assert!( + fixture + .api + .authorization_audit() + .iter() + .any(|event| event.permission_id == cap::MATCHING_WRITE) + ); + assert_eq!(host.writes.load(Ordering::SeqCst), 0); + + let fixture = Fixture::new(&[cap::MATCHING_WRITE]).await; + fixture.library(SHARED); + let status = fixture.assign("k", 1, "7").await.unwrap_err(); + assert_eq!(status.code(), Code::Unavailable); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_match_is_not_committed_when_authorization_is_lost_before_commit() { + let fixture = Fixture::new(&[cap::MATCHING_WRITE]).await; + fixture.library(SHARED); + let host = fixture.with_host(); + host.known.lock().unwrap().insert(7); + *host.revoke_before_commit.lock().unwrap() = Some((fixture.api.clone(), cap::MATCHING_WRITE)); + let status = fixture.assign("k", 1, "7").await.unwrap_err(); + assert_eq!(status.code(), Code::PermissionDenied); + assert_eq!(host.writes.load(Ordering::SeqCst), 0); + assert!(host.matches.lock().unwrap().is_empty()); +} + +// ---- Artwork (task 5.4) ---- + +fn png(width: u32, height: u32) -> Vec { + let mut out = Vec::new(); + image::DynamicImage::ImageRgb8(image::RgbImage::from_pixel( + width, + height, + image::Rgb([20, 120, 220]), + )) + .write_with_encoder(image::codecs::png::PngEncoder::new(&mut out)) + .unwrap(); + out +} + +impl Fixture { + async fn set_cover( + &self, + key: &str, + expected_revision: u64, + installation_id: &str, + image: Vec, + media_type: &str, + ) -> Result { + self.set_cover_with(ArtworkSetRequest { + mutation: Some(self.mutation(key, expected_revision)), + installation_id: installation_id.into(), + encoded_image: image, + media_type: media_type.into(), + ..ArtworkSetRequest::default() + }) + .await + } + + async fn set_cover_with(&self, request: ArtworkSetRequest) -> Result { + self.client() + .artwork_set(request) + .await + .map(Response::into_inner) + } + + async fn read_cover( + &self, + installation_id: &str, + max_bytes: u64, + ) -> Result { + self.client() + .artwork_read(ArtworkReadRequest { + context: Some(self.context()), + installation_id: installation_id.into(), + max_bytes, + ..ArtworkReadRequest::default() + }) + .await + .map(Response::into_inner) + } +} + +#[tokio::test] +async fn an_own_entrys_cover_is_set_once_idempotently_and_guarded_by_its_revision() { + let fixture = Fixture::new(&[cap::ARTWORK_WRITE]).await; + fixture.library(SHARED); + let host = fixture.with_host(); + + let applied = fixture + .set_cover("k1", 0, "id-fixture:1", png(900, 1200), "image/png") + .await + .unwrap(); + assert_eq!( + ( + applied.resource_id.as_str(), + applied.revision, + applied.outcome + ), + ("id-fixture:1", 1, MutationOutcome::Applied as i32) + ); + // The host stored its own smaller, re-encoded picture, not the plugin's bytes. + let stored = host.covers.lock().unwrap()["fixture:1"].0.clone().unwrap(); + assert_eq!((stored.width, stored.height), (600, 800)); + assert_eq!(stored.media_type, "image/jpeg"); + + // The same key and request replays the first answer without another write. + let again = fixture + .set_cover("k1", 0, "id-fixture:1", png(900, 1200), "image/png") + .await + .unwrap(); + assert_eq!(again, applied); + assert_eq!(host.writes.load(Ordering::SeqCst), 1); + // The same key for another picture is refused. + let status = fixture + .set_cover("k1", 0, "id-fixture:1", png(10, 10), "image/png") + .await + .unwrap_err(); + assert_eq!(status.code(), Code::FailedPrecondition); + + // A stale revision conflicts and writes nothing; the refusal is not remembered. + let conflict = fixture + .set_cover("k2", 0, "id-fixture:1", png(40, 60), "image/png") + .await + .unwrap(); + assert_eq!( + (conflict.revision, conflict.outcome), + (1, MutationOutcome::RevisionConflict as i32) + ); + assert_eq!(host.writes.load(Ordering::SeqCst), 1); + let retried = fixture + .set_cover("k2", 1, "id-fixture:1", png(40, 60), "image/png") + .await + .unwrap(); + assert_eq!( + (retried.revision, retried.outcome), + (2, MutationOutcome::Applied as i32) + ); + // Setting what the entry already has is already applied. + let same = fixture + .set_cover("k3", 2, "id-fixture:1", png(40, 60), "image/png") + .await + .unwrap(); + assert_eq!( + (same.revision, same.outcome), + (2, MutationOutcome::AlreadyApplied as i32) + ); +} + +#[tokio::test] +async fn an_empty_image_restores_the_games_own_cover() { + let fixture = Fixture::new(&[cap::ARTWORK_WRITE, cap::ARTWORK_READ]).await; + fixture.library(SHARED); + let host = fixture.with_host(); + host.game_covers + .lock() + .unwrap() + .insert("fixture:1".into(), b"game cover".to_vec()); + fixture + .set_cover("k1", 0, "id-fixture:1", png(40, 60), "image/png") + .await + .unwrap(); + let cleared = fixture + .set_cover("k2", 1, "id-fixture:1", Vec::new(), "") + .await + .unwrap(); + assert_eq!( + (cleared.revision, cleared.outcome), + (2, MutationOutcome::Applied as i32) + ); + let read = fixture.read_cover("id-fixture:1", 0).await.unwrap(); + assert_eq!(read.encoded_image, b"game cover"); + // Clearing again changes nothing. + let again = fixture + .set_cover("k3", 2, "id-fixture:1", Vec::new(), "") + .await + .unwrap(); + assert_eq!(again.outcome, MutationOutcome::AlreadyApplied as i32); + // A media type with nothing to describe is a mistake, not a clear. + let status = fixture + .set_cover("k4", 2, "id-fixture:1", Vec::new(), "image/png") + .await + .unwrap_err(); + assert_eq!(status.code(), Code::InvalidArgument); +} + +#[tokio::test] +async fn bad_images_never_reach_the_engine() { + let fixture = Fixture::new(&[cap::ARTWORK_WRITE]).await; + fixture.library(SHARED); + let host = fixture.with_host(); + let heavy = { + let mut out = Vec::new(); + image::DynamicImage::ImageLuma8(image::GrayImage::new(4097, 4097)) + .write_with_encoder(image::codecs::png::PngEncoder::new(&mut out)) + .unwrap(); + out + }; + let mut half = png(64, 64); + half.truncate(half.len() / 2); + let mut oversized = png(8, 8); + oversized.resize(gamenode_platform::plugin_artwork::MAX_INPUT_BYTES + 1, 0); + let cases: Vec<(&str, Vec, &str)> = vec![ + ( + "not an image", + b"#!/bin/sh\nrm -rf /\n".to_vec(), + "image/png", + ), + ( + "svg", + b"".to_vec(), + "image/svg+xml", + ), + ("lying about the type", png(8, 8), "image/jpeg"), + ("no type", png(8, 8), ""), + ("truncated", half, "image/png"), + ("too many pixels", heavy, "image/png"), + ("too many bytes", oversized, "image/png"), + ]; + for (index, (what, bytes, media_type)) in cases.into_iter().enumerate() { + let status = fixture + .set_cover( + &format!("bad-{index}"), + 0, + "id-fixture:1", + bytes, + media_type, + ) + .await + .unwrap_err(); + assert_eq!(status.code(), Code::InvalidArgument, "{what}: {status}"); + } + assert_eq!(host.writes.load(Ordering::SeqCst), 0); + assert!(host.covers.lock().unwrap().is_empty()); +} + +#[tokio::test] +async fn covers_are_set_only_on_own_entries_that_exist() { + let fixture = Fixture::new(&[cap::ARTWORK_WRITE, cap::LIBRARY_READ_ALL]).await; + fixture.library(SHARED); + let host = fixture.with_host(); + // Another provider's entry and an unknown one are the same refusal, even with whole-library + // reads; the image is not even decoded. + for (key, id) in [("a", "id-steam:620"), ("b", "id-nope")] { + let status = fixture + .set_cover(key, 0, id, png(40, 60), "image/png") + .await + .unwrap_err(); + assert_eq!(status.code(), Code::NotFound, "{id}"); + } + // A game id the entry is not matched to does not name it either. + let status = fixture + .set_cover_with(ArtworkSetRequest { + mutation: Some(fixture.mutation("c", 0)), + installation_id: "id-fixture:1".into(), + game_id: "999".into(), + encoded_image: png(40, 60), + media_type: "image/png".into(), + ..ArtworkSetRequest::default() + }) + .await + .unwrap_err(); + assert_eq!(status.code(), Code::NotFound); + // Naming the game it is matched to is fine. + fixture + .set_cover_with(ArtworkSetRequest { + mutation: Some(fixture.mutation("d", 0)), + installation_id: "id-fixture:1".into(), + game_id: "7".into(), + encoded_image: png(40, 60), + media_type: "image/png".into(), + ..ArtworkSetRequest::default() + }) + .await + .unwrap(); + assert_eq!(host.writes.load(Ordering::SeqCst), 1); + assert_eq!(host.covers.lock().unwrap().len(), 1); +} + +#[tokio::test] +async fn cover_set_requests_are_validated_before_anything_is_written() { + let fixture = Fixture::new(&[cap::ARTWORK_WRITE]).await; + fixture.library(SHARED); + let host = fixture.with_host(); + let base = |mutation: Option| ArtworkSetRequest { + mutation, + installation_id: "id-fixture:1".into(), + encoded_image: png(8, 8), + media_type: "image/png".into(), + ..ArtworkSetRequest::default() + }; + let cases = vec![ + ("no mutation", base(None)), + ("no key", base(Some(fixture.mutation("", 0)))), + ( + "no installation", + ArtworkSetRequest { + installation_id: String::new(), + ..base(Some(fixture.mutation("k", 0))) + }, + ), + ( + "long installation", + ArtworkSetRequest { + installation_id: "x".repeat(129), + ..base(Some(fixture.mutation("k", 0))) + }, + ), + ( + "another kind", + ArtworkSetRequest { + artwork_kind: "banner".into(), + ..base(Some(fixture.mutation("k", 0))) + }, + ), + ( + "bad game id", + ArtworkSetRequest { + game_id: "seven".into(), + ..base(Some(fixture.mutation("k", 0))) + }, + ), + ]; + for (what, request) in cases { + let status = fixture.set_cover_with(request).await.unwrap_err(); + assert_eq!(status.code(), Code::InvalidArgument, "{what}: {status}"); + } + // "cover" is the one kind there is. + fixture + .set_cover_with(ArtworkSetRequest { + artwork_kind: "cover".into(), + ..base(Some(fixture.mutation("ok", 0))) + }) + .await + .unwrap(); + assert_eq!(host.writes.load(Ordering::SeqCst), 1); +} + +#[tokio::test] +async fn cover_calls_need_their_grants_and_the_engine_side() { + let fixture = Fixture::new(&[cap::ARTWORK_READ]).await; + fixture.library(SHARED); + let host = fixture.with_host(); + let status = fixture + .set_cover("k", 0, "id-fixture:1", png(8, 8), "image/png") + .await + .unwrap_err(); + assert_eq!(status.code(), Code::PermissionDenied); + assert!( + fixture + .api + .authorization_audit() + .iter() + .any(|event| event.permission_id == cap::ARTWORK_WRITE) + ); + assert_eq!(host.writes.load(Ordering::SeqCst), 0); + + let fixture = Fixture::new(&[cap::ARTWORK_WRITE]).await; + fixture.library(SHARED); + let status = fixture.read_cover("id-fixture:1", 0).await.unwrap_err(); + assert_eq!(status.code(), Code::PermissionDenied); + let status = fixture + .set_cover("k", 0, "id-fixture:1", png(8, 8), "image/png") + .await + .unwrap_err(); + assert_eq!(status.code(), Code::Unavailable); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_cover_is_not_committed_when_authorization_is_lost_before_commit() { + let fixture = Fixture::new(&[cap::ARTWORK_WRITE]).await; + fixture.library(SHARED); + let host = fixture.with_host(); + *host.revoke_before_commit.lock().unwrap() = Some((fixture.api.clone(), cap::ARTWORK_WRITE)); + let status = fixture + .set_cover("k", 0, "id-fixture:1", png(40, 60), "image/png") + .await + .unwrap_err(); + assert_eq!(status.code(), Code::PermissionDenied); + assert_eq!(host.writes.load(Ordering::SeqCst), 0); + assert!(host.covers.lock().unwrap().is_empty()); +} + +#[tokio::test] +async fn an_own_entrys_cover_is_read_within_the_callers_budget() { + let fixture = Fixture::new(&[cap::ARTWORK_READ, cap::LIBRARY_READ_ALL]).await; + fixture.library(SHARED); + let host = fixture.with_host(); + host.game_covers + .lock() + .unwrap() + .insert("fixture:1".into(), b"0123456789".to_vec()); + host.game_covers + .lock() + .unwrap() + .insert("steam:620".into(), b"foreign".to_vec()); + + let read = fixture.read_cover("id-fixture:1", 0).await.unwrap(); + assert_eq!( + ( + read.encoded_image.as_slice(), + read.media_type.as_str(), + read.byte_length, + read.revision + ), + (b"0123456789".as_slice(), "image/jpeg", 10, 0) + ); + assert_eq!( + fixture + .read_cover("id-fixture:1", 10) + .await + .unwrap() + .byte_length, + 10 + ); + let status = fixture.read_cover("id-fixture:1", 9).await.unwrap_err(); + assert_eq!(status.code(), Code::ResourceExhausted); + // An entry with no cover on this device, another provider's entry and an unknown one. + let status = fixture.read_cover("id-fixture:2", 0).await.unwrap_err(); + assert_eq!(status.code(), Code::NotFound); + for id in ["id-steam:620", "id-nope"] { + let status = fixture.read_cover(id, 0).await.unwrap_err(); + assert_eq!(status.code(), Code::NotFound, "{id}"); + } + let status = fixture + .client() + .artwork_read(ArtworkReadRequest { + context: Some(fixture.context()), + installation_id: "id-fixture:1".into(), + artwork_kind: "screenshot".into(), + ..ArtworkReadRequest::default() + }) + .await + .unwrap_err(); + assert_eq!(status.code(), Code::InvalidArgument); +} + +#[tokio::test] +async fn the_cover_a_plugin_set_is_what_it_reads_back_with_its_revision() { + let fixture = Fixture::new(&[cap::ARTWORK_READ, cap::ARTWORK_WRITE]).await; + fixture.library(SHARED); + fixture.with_host(); + fixture + .set_cover("k", 0, "id-fixture:1", png(300, 300), "image/png") + .await + .unwrap(); + let read = fixture.read_cover("id-fixture:1", 0).await.unwrap(); + assert_eq!((read.media_type.as_str(), read.revision), ("image/jpeg", 1)); + let decoded = image::load_from_memory(&read.encoded_image).unwrap(); + assert_eq!((decoded.width(), decoded.height()), (300, 300)); +} diff --git a/crates/app/src/plugin_host/resources/tests/artwork_handles.rs b/crates/app/src/plugin_host/resources/tests/artwork_handles.rs new file mode 100644 index 000000000..e5f1da769 --- /dev/null +++ b/crates/app/src/plugin_host/resources/tests/artwork_handles.rs @@ -0,0 +1,450 @@ +//! `ArtworkSet` with an approved file-handle reference (task 6.6): a picture the plugin may read +//! becomes the cover of its own entry, and nothing else can, over the real local socket. + +use super::*; +use gamenode_platform::plugin_artwork::MAX_INPUT_BYTES; + +const GRANTS: &[&str] = &[ + cap::ARTWORK_WRITE, + cap::ARTWORK_READ, + cap::FILES_READ, + cap::FILES_WRITE, +]; + +impl Fixture { + async fn set_cover_from( + &self, + key: &str, + installation_id: &str, + handle: &str, + media_type: &str, + ) -> Result { + self.set_cover_with(ArtworkSetRequest { + mutation: Some(self.mutation(key, 0)), + installation_id: installation_id.into(), + file_handle: handle.into(), + media_type: media_type.into(), + ..ArtworkSetRequest::default() + }) + .await + } +} + +/// A fixture with two own entries, each in its own folder, the first one approved for reading. +async fn ready( + files: &[(&str, &[u8])], +) -> ( + Fixture, + std::sync::Arc, + std::path::PathBuf, + String, +) { + let fixture = Fixture::new(GRANTS).await; + let one = fixture.game_dir("one", files); + let two = fixture.game_dir("two", &[("other.png", &png(40, 40))]); + fixture.library_in(&[ + ("fixture:1", Some(7), "One", &one), + ("fixture:2", Some(8), "Two", &two), + ]); + let host = fixture.with_host(); + fixture.user_approving(&one); + let root = fixture + .root_handle("id-fixture:1", &["read", "write"]) + .await; + (fixture, host, one, root) +} + +fn code(result: Result) -> Code { + result.unwrap_err().code() +} + +#[tokio::test] +async fn a_picture_from_an_approved_file_becomes_the_cover_like_inline_bytes() { + let picture = png(900, 1200); + let (fixture, host, _dir, root) = ready(&[("cover.png", &picture)]).await; + let file = fixture.child(&root, "cover.png").await; + + let applied = fixture + .set_cover_from("k1", "id-fixture:1", &file, "image/png") + .await + .unwrap(); + assert_eq!( + ( + applied.resource_id.as_str(), + applied.revision, + applied.outcome + ), + ("id-fixture:1", 1, MutationOutcome::Applied as i32) + ); + // The host stored its own picture, shrunk and re-encoded, exactly as for inline bytes. + let stored = host.covers.lock().unwrap()["fixture:1"].0.clone().unwrap(); + assert_eq!((stored.width, stored.height), (600, 800)); + assert_eq!(stored.media_type, "image/jpeg"); + assert_eq!( + fixture + .read_cover("id-fixture:1", 0) + .await + .unwrap() + .revision, + 1 + ); + + // Inline bytes of the same picture are the same picture: nothing changes. + let inline = fixture + .set_cover("k2", 1, "id-fixture:1", picture, "image/png") + .await + .unwrap(); + assert_eq!(inline.outcome, MutationOutcome::AlreadyApplied as i32); +} + +#[tokio::test] +async fn a_retried_request_is_answered_before_the_file_is_read_again() { + let (fixture, host, dir, root) = ready(&[("cover.png", &png(300, 450))]).await; + let file = fixture.child(&root, "cover.png").await; + let first = fixture + .set_cover_from("k1", "id-fixture:1", &file, "image/png") + .await + .unwrap(); + // The file is gone; the retry is a replay and neither reads nor writes anything. + std::fs::remove_file(dir.join("cover.png")).unwrap(); + let again = fixture + .set_cover_from("k1", "id-fixture:1", &file, "image/png") + .await + .unwrap(); + assert_eq!(again, first); + assert_eq!(host.writes.load(Ordering::SeqCst), 1); + // The same key for another declared type is another request. + assert_eq!( + code( + fixture + .set_cover_from("k1", "id-fixture:1", &file, "image/jpeg") + .await + ), + Code::FailedPrecondition + ); + // A new key finds the file missing, and says so without a path. + let missing = fixture + .set_cover_from("k2", "id-fixture:1", &file, "image/png") + .await + .unwrap_err(); + assert_eq!(missing.code(), Code::NotFound); + assert!(!missing.message().contains("cover.png")); +} + +#[tokio::test] +async fn the_request_must_choose_exactly_one_source_and_name_its_type() { + let (fixture, host, _dir, root) = ready(&[("cover.png", &png(300, 450))]).await; + let file = fixture.child(&root, "cover.png").await; + let both = fixture + .set_cover_with(ArtworkSetRequest { + mutation: Some(fixture.mutation("k", 0)), + installation_id: "id-fixture:1".into(), + encoded_image: png(10, 10), + file_handle: file.clone(), + media_type: "image/png".into(), + ..ArtworkSetRequest::default() + }) + .await; + assert_eq!(code(both), Code::InvalidArgument); + assert_eq!( + code(fixture.set_cover_from("k", "id-fixture:1", &file, "").await), + Code::InvalidArgument + ); + assert_eq!(host.writes.load(Ordering::SeqCst), 0); +} + +#[tokio::test] +async fn reading_a_file_needs_files_read_besides_artwork_write() { + // Only the write side of both: a handle exists, but reading the file is not granted. + let fixture = Fixture::new(&[cap::ARTWORK_WRITE, cap::FILES_WRITE]).await; + let dir = fixture.game_dir("one", &[("cover.png", &png(300, 450))]); + fixture.library_in(&[("fixture:1", Some(7), "One", &dir)]); + let host = fixture.with_host(); + fixture.user_approving(&dir); + let root = fixture.root_handle("id-fixture:1", &["write"]).await; + let created = fixture + .write_to(&root, "new.png", &png(300, 450), 0, true, "w") + .await + .unwrap(); + let denied = fixture + .set_cover_from("k", "id-fixture:1", &created.resource_id, "image/png") + .await + .unwrap_err(); + assert_eq!(denied.code(), Code::PermissionDenied); + assert_eq!(host.writes.load(Ordering::SeqCst), 0); + + // And files.read alone does not allow changing a cover. + let fixture = Fixture::new(&[cap::FILES_READ]).await; + let dir = fixture.game_dir("one", &[("cover.png", &png(300, 450))]); + fixture.library_in(&[("fixture:1", Some(7), "One", &dir)]); + let host = fixture.with_host(); + fixture.user_approving(&dir); + let root = fixture.root_handle("id-fixture:1", &["read"]).await; + let file = fixture.child(&root, "cover.png").await; + assert_eq!( + code( + fixture + .set_cover_from("k", "id-fixture:1", &file, "image/png") + .await + ), + Code::PermissionDenied + ); + assert_eq!(host.writes.load(Ordering::SeqCst), 0); +} + +#[tokio::test] +async fn a_handle_of_another_entry_or_session_or_a_made_up_reference_changes_nothing() { + let (mut fixture, host, _dir, root) = ready(&[("cover.png", &png(300, 450))]).await; + let file = fixture.child(&root, "cover.png").await; + + // A handle from the approval of another entry's folder (the plugin's own, but not for this + // entry) is refused for this entry. + let two = fixture.base().join("games").join("two"); + let user = fixture.user_approving(&two); + let other_root = fixture.root_handle("id-fixture:2", &["read"]).await; + drop(user); + let other = fixture.child(&other_root, "other.png").await; + assert_eq!( + code( + fixture + .set_cover_from("k1", "id-fixture:1", &other, "image/png") + .await + ), + Code::PermissionDenied + ); + // It works for the entry it was approved for. + assert!( + fixture + .set_cover_from("k1", "id-fixture:2", &other, "image/png") + .await + .is_ok() + ); + assert_eq!(host.writes.load(Ordering::SeqCst), 1); + + // A path, a URL, a forged or edited handle and a directory are all refused; a handle is the + // only reference there is, so none of them is opened as a file or fetched. + let mut edited = file.clone(); + edited.pop(); + edited.push('A'); + for (n, reference) in [ + "/etc/passwd", + "../cover.png", + "cover.png", + "https://example.com/c.png", + "file:///etc/passwd", + "forged", + edited.as_str(), + ] + .into_iter() + .enumerate() + { + assert_eq!( + code( + fixture + .set_cover_from(&format!("bad{n}"), "id-fixture:1", reference, "image/png") + .await + ), + Code::NotFound, + "{reference}" + ); + } + assert_eq!( + code( + fixture + .set_cover_from("dir", "id-fixture:1", &root, "image/png") + .await + ), + Code::FailedPrecondition + ); + assert_eq!(host.writes.load(Ordering::SeqCst), 1); + assert!(!host.covers.lock().unwrap().contains_key("fixture:1")); + + // After the session ends, the handles of the old one open nothing. + fixture.reconnect().await; + assert_eq!( + code( + fixture + .set_cover_from("late", "id-fixture:1", &file, "image/png") + .await + ), + Code::NotFound + ); + assert!(!host.covers.lock().unwrap().contains_key("fixture:1")); +} + +#[tokio::test] +async fn a_revoked_approval_or_grant_stops_the_handle_and_a_foreign_entry_is_never_read() { + let (fixture, host, _dir, root) = ready(&[("cover.png", &png(300, 450))]).await; + let file = fixture.child(&root, "cover.png").await; + + // An entry that is not the caller's is NOT_FOUND and its handle is not even opened. + assert_eq!( + code( + fixture + .set_cover_from("foreign", "id-steam:620", &file, "image/png") + .await + ), + Code::NotFound + ); + + // The user revokes the approval: the handle opens nothing. + let id = fixture + .files + .open_handle(&fixture.context().session_id, &root) + .unwrap() + .0; + let caller = fixture.caller(); + fixture + .storage + .run( + &caller, + |_| true, + move |namespace| namespace.revoke_approval(&id), + ) + .await + .unwrap(); + assert_eq!( + code( + fixture + .set_cover_from("revoked", "id-fixture:1", &file, "image/png") + .await + ), + Code::NotFound + ); + assert_eq!(host.writes.load(Ordering::SeqCst), 0); + + // A revoked grant stops it even though a new approval stands. + let fresh = fixture.root_handle("id-fixture:1", &["read"]).await; + let file = fixture.child(&fresh, "cover.png").await; + fixture + .api + .revoke_session_permission("fixture", cap::FILES_READ) + .await; + assert_eq!( + code( + fixture + .set_cover_from("grant", "id-fixture:1", &file, "image/png") + .await + ), + Code::PermissionDenied + ); + assert_eq!(host.writes.load(Ordering::SeqCst), 0); +} + +#[tokio::test(flavor = "multi_thread")] +async fn losing_files_read_before_the_commit_writes_nothing() { + let (fixture, host, _dir, root) = ready(&[("cover.png", &png(300, 450))]).await; + let file = fixture.child(&root, "cover.png").await; + *host.revoke_before_commit.lock().unwrap() = Some((fixture.api.clone(), cap::FILES_READ)); + assert_eq!( + code( + fixture + .set_cover_from("k", "id-fixture:1", &file, "image/png") + .await + ), + Code::PermissionDenied + ); + assert_eq!(host.writes.load(Ordering::SeqCst), 0); + assert!(host.covers.lock().unwrap().is_empty()); +} + +#[tokio::test] +async fn a_file_over_the_byte_limit_or_not_a_picture_is_refused_before_it_is_decoded_or_stored() { + let big = vec![0u8; MAX_INPUT_BYTES + 1]; + let exact = { + // A real picture padded to exactly the limit is still too far from a valid PNG to decode, + // so it proves the bound is "more than the limit", not "the limit". + let mut bytes = png(300, 450); + bytes.resize(MAX_INPUT_BYTES, 0); + bytes + }; + let (fixture, host, _dir, root) = ready(&[ + ("big.png", &big), + ("exact.png", &exact), + ("notes.png", b"this is not a picture"), + ("empty.png", b""), + ]) + .await; + + let over = fixture.child(&root, "big.png").await; + let status = fixture + .set_cover_from("big", "id-fixture:1", &over, "image/png") + .await + .unwrap_err(); + assert_eq!(status.code(), Code::InvalidArgument); + assert!(status.message().contains("larger"), "{}", status.message()); + + // The inline path says the same thing about the same size. + let inline = fixture + .set_cover("inline", 0, "id-fixture:1", big, "image/png") + .await + .unwrap_err(); + assert_eq!(inline.code(), Code::InvalidArgument); + assert_eq!(inline.message(), status.message()); + + // At the limit the file is read and decoded; trailing zeros after a PNG are not a reason + // to refuse it as too large. + let at = fixture.child(&root, "exact.png").await; + let result = fixture + .set_cover_from("exact", "id-fixture:1", &at, "image/png") + .await; + if let Err(status) = &result { + assert!(!status.message().contains("larger"), "{}", status.message()); + } + + let writes = host.writes.load(Ordering::SeqCst); + for (key, name) in [("text", "notes.png"), ("empty", "empty.png")] { + let file = fixture.child(&root, name).await; + assert_eq!( + code( + fixture + .set_cover_from(key, "id-fixture:1", &file, "image/png") + .await + ), + Code::InvalidArgument, + "{name}" + ); + } + // A type that does not match the bytes is refused like inline bytes. + let png_file = { + let (fixture2, _h, _d, root2) = ready(&[("c.png", &png(100, 150))]).await; + let file = fixture2.child(&root2, "c.png").await; + code( + fixture2 + .set_cover_from("mismatch", "id-fixture:1", &file, "image/jpeg") + .await, + ) + }; + assert_eq!(png_file, Code::InvalidArgument); + assert_eq!(host.writes.load(Ordering::SeqCst), writes); +} + +#[tokio::test] +async fn the_sdk_helper_sends_what_the_raw_call_sends() { + let (fixture, host, _dir, root) = ready(&[("cover.png", &png(600, 900))]).await; + let sdk = fixture.host.resources().unwrap(); + let file = fixture.child(&root, "cover.png").await; + let key = gamenode_plugin_sdk::idempotency_key(); + let written = sdk + .set_cover_from_file("id-fixture:1", 0, &key, &file, "image/png") + .await + .unwrap(); + assert_eq!(written.outcome, gamenode_plugin_sdk::Outcome::Applied); + // The same request by hand under the SDK's key is a replay: the host only answers that way + // for an identical request. + let by_hand = fixture + .set_cover_from(&key, "id-fixture:1", &file, "image/png") + .await + .unwrap(); + assert_eq!( + gamenode_plugin_sdk::Written::try_from(by_hand).unwrap(), + written + ); + assert_eq!(host.writes.load(Ordering::SeqCst), 1); + // Refusals are the host's own. + let status = sdk + .set_cover_from_file("id-fixture:1", 1, "k2", "/etc/passwd", "image/png") + .await + .unwrap_err(); + assert_eq!(status.code(), gamenode_plugin_sdk::Code::NotFound); +} diff --git a/crates/app/src/plugin_host/resources/tests/backups.rs b/crates/app/src/plugin_host/resources/tests/backups.rs new file mode 100644 index 000000000..8e3885958 --- /dev/null +++ b/crates/app/src/plugin_host/resources/tests/backups.rs @@ -0,0 +1,672 @@ +//! Backups over the real local transport, with a deterministic worker engine (no live saves). +use super::saves::{INSTALLATION, directory, profile}; +use super::*; +use crate::plugin_host::intents::{Answer, ConfirmationRequest, Prompter}; +use crate::plugin_host::jobs::JobOwner; +use gamenode_core::drm_free as d; +use std::path::PathBuf; +use tokio::sync::Notify; + +use super::action_recipes; + +const GRANTS: &[&str] = &[ + cap::GAME_LAUNCH, + cap::FILES_READ, + cap::GAME_SAVES_CREATE, + cap::GAME_SAVES_READ, + cap::GAME_SAVES_UPDATE, + cap::BACKUPS_READ, + cap::BACKUPS_CREATE, + cap::BACKUPS_RESTORE, +]; + +#[derive(Default)] +struct Backend { + snapshots: Mutex>>>, + requests: Mutex>, + recovery: Mutex)>>, + holding: AtomicBool, + entered: AtomicBool, +} +impl d::BackupEngine for Backend { + fn execute( + &self, + _: &d::BackupRequest, + _: &AtomicBool, + ) -> Result { + panic!("plugins must not use the manual backup port"); + } + fn scoped_available(&self) -> bool { + true + } + fn execute_scoped( + &self, + r: &d::ScopedBackupRequest, + cancel: &AtomicBool, + authority: &dyn d::BackupAuthority, + ) -> Result { + if cancel.load(Ordering::SeqCst) { + return Err(d::LocalError::Cancelled); + } + self.requests.lock().unwrap().push(r.clone()); + self.entered.store(true, Ordering::SeqCst); + let deadline = std::time::Instant::now() + Duration::from_secs(5); + while self.holding.load(Ordering::SeqCst) { + authority.check()?; + if cancel.load(Ordering::SeqCst) { + return Err(d::LocalError::Cancelled); + } + assert!( + std::time::Instant::now() < deadline, + "worker was never released" + ); + std::thread::sleep(Duration::from_millis(5)); + } + authority.check()?; + let mut snapshots = self.snapshots.lock().unwrap(); + let json = match &r.operation { + d::BackupOperation::Backup => { + authority.validate_targets(&r.profile.files, &[])?; + let files = r + .profile + .files + .iter() + .map(|p| (p.clone(), std::fs::read(p).unwrap())) + .collect(); + let name = format!("snapshot-{}", snapshots.len() + 1); + snapshots.insert(name, files); + serde_json::json!({"games":{&r.profile.title:{"files":{}}}}) + } + d::BackupOperation::History => { + serde_json::json!({"games":{&r.profile.title:{"backups":snapshots.keys().map(|name| serde_json::json!({"name":name,"created_at":1700000000,"size_bytes":4})).collect::>()}}}) + } + d::BackupOperation::RestorePreview { backup } + | d::BackupOperation::Restore { backup } => { + let files = snapshots.get(backup).ok_or(d::LocalError::InvalidTarget)?; + let targets = files.keys().cloned().collect::>(); + if matches!(r.operation, d::BackupOperation::Restore { .. }) { + authority.validate_targets(&targets, &[])?; + for (path, bytes) in files { + self.recovery + .lock() + .unwrap() + .push((path.clone(), std::fs::read(path).unwrap_or_default())); + authority.check()?; + std::fs::write(path, bytes).unwrap(); + } + } + serde_json::json!({"games":{&r.profile.title:{"files":files.keys().map(|p| (p.clone(),serde_json::json!({}))).collect::>()}}}) + } + _ => return Err(d::LocalError::Unsupported), + }; + Ok(d::BackupReport { + state: d::JobState::Successful, + json: json.to_string(), + }) + } +} + +struct Dialog { + shown: Mutex>, + gate: Option>, + approved: bool, +} +#[tonic::async_trait] +impl Prompter for Dialog { + async fn confirm(&self, request: ConfirmationRequest) -> Result { + self.shown.lock().unwrap().push(request); + if let Some(gate) = &self.gate { + gate.notified().await; + } + Ok(Answer { + approved: self.approved, + remember: true, + }) + } +} + +struct Ready { + f: Fixture, + folder: PathBuf, + profile: SaveProfileMutationReply, + backend: Arc, +} +impl Ready { + async fn new() -> Self { + let (f, folder) = Fixture::emulator(GRANTS).await; + let host = f.with_host(); + let backend = Arc::new(Backend::default()); + *host.backup.lock().unwrap() = Some(crate::plugin_host::library::BackupHostContext { + engine: backend.clone(), + destination: f + ._temp + .path() + .join("archives") + .to_string_lossy() + .into_owned(), + target: d::BackupTarget { + installation_id: INSTALLATION.into(), + root: f._temp.path().join("rom").to_string_lossy().into_owned(), + gameplay: vec![], + track_folder: true, + }, + }); + let handle = f.approve(INSTALLATION, "save", &folder).await; + let profile = f + .make( + "profile", + profile( + "Saves", + "", + vec![directory(&handle, "Slots", &["**/*.sav"])], + ), + ) + .await + .unwrap(); + Self { + f, + folder, + profile, + backend, + } + } + async fn create(&self, key: &str) -> Result { + self.f + .client() + .backups_request_create(BackupCreateRequest { + mutation: Some(self.f.mutation(key, self.profile.revision)), + game_id: "3".into(), + profile_id: self.profile.profile_id.clone(), + reason: "User requested".into(), + }) + .await + .map(Response::into_inner) + } + async fn list(&self, cursor: &str, size: u32) -> Result { + self.f + .client() + .backups_list(BackupsListRequest { + page: Some(PageRequest { + context: Some(self.f.context()), + page_size: size, + cursor: cursor.into(), + ..Default::default() + }), + game_id: "3".into(), + profile_id: self.profile.profile_id.clone(), + }) + .await + .map(Response::into_inner) + } + async fn restore(&self, key: &str, id: &str) -> Result { + self.f + .client() + .backups_request_restore(BackupRestoreRequest { + mutation: Some(self.f.mutation(key, self.profile.revision)), + backup_id: id.into(), + game_id: "3".into(), + profile_id: self.profile.profile_id.clone(), + user_intent_id: String::new(), + }) + .await + .map(Response::into_inner) + } + fn dialog(&self, approved: bool, gate: Option>) -> Arc { + let dialog = Arc::new(Dialog { + shown: Mutex::new(vec![]), + approved, + gate, + }); + self.f.intents.set_prompter(dialog.clone()); + dialog + } + async fn ended(&self, id: &str) -> JobReply { + let caller = self + .f + .api + .authorize_resource_session(Some(&self.f.context())) + .unwrap(); + let owner = JobOwner::of(&caller).unwrap(); + tokio::time::timeout(Duration::from_secs(5), async { + loop { + let job = self.f.jobs.get(&owner, id).unwrap(); + if !matches!(job.state(), JobState::Queued | JobState::Running) { + return job; + } + tokio::time::sleep(Duration::from_millis(5)).await; + } + }) + .await + .expect("backup did not end") + } + async fn created(&self, key: &str) -> JobReply { + let job = self.create(key).await.unwrap(); + let finished = self.ended(&job.job_id).await; + assert_eq!(finished.state(), JobState::Succeeded, "{finished:?}"); + job + } +} +async fn shown(dialog: &Dialog) { + tokio::time::timeout(Duration::from_secs(5), async { + while dialog.shown.lock().unwrap().is_empty() { + tokio::time::sleep(Duration::from_millis(5)).await; + } + }) + .await + .unwrap(); +} + +#[tokio::test(flavor = "multi_thread")] +async fn sdk_backup_calls_match_the_raw_calls_and_follow_the_job() { + let r = Ready::new().await; + let actions = r.f.host.actions().expect("an API 1.6 session"); + let created = actions + .create_backup( + "3", + &r.profile.profile_id, + "User requested", + r.profile.revision, + &gamenode_plugin_sdk::idempotency_key(), + ) + .await + .unwrap(); + assert_eq!( + action_recipes::wait_for_job(&actions, &created.job_id) + .await + .unwrap() + .state, + JobState::Succeeded + ); + let listed = r.list("", 50).await.unwrap(); + let through_sdk = actions.backups("3", &r.profile.profile_id).await.unwrap(); + assert_eq!(through_sdk.len(), listed.backups.len()); + assert_eq!( + ( + &through_sdk[0].game_id, + through_sdk[0].created_at, + through_sdk[0].size_bytes, + &through_sdk[0].state, + ), + ( + &listed.backups[0].game_id, + listed.backups[0].created_at, + listed.backups[0].size_bytes, + &listed.backups[0].state, + ) + ); + let dialog = r.dialog(true, None); + let restored = actions + .restore_backup( + &listed.backups[0].backup_id, + "3", + &r.profile.profile_id, + r.profile.revision, + &gamenode_plugin_sdk::idempotency_key(), + ) + .await + .unwrap(); + assert_eq!( + action_recipes::wait_for_job(&actions, &restored.job_id) + .await + .unwrap() + .state, + JobState::Succeeded + ); + assert_eq!(dialog.shown.lock().unwrap().len(), 1); + assert_eq!( + std::fs::read(r.folder.join("states/s1.sav")).unwrap(), + b"state" + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn create_selects_only_approved_rules_is_replayable_and_restores_only_after_confirmation() { + let r = Ready::new().await; + let created = r.created("create").await; + assert_eq!(r.create("create").await.unwrap().job_id, created.job_id); + assert_eq!(r.backend.snapshots.lock().unwrap().len(), 1); + let request = r.backend.requests.lock().unwrap()[0].clone(); + assert!(!request.owner.is_empty()); + assert_eq!( + request.profile.files, + vec![r.folder.join("states/s1.sav").to_string_lossy()] + ); + let listed = r.list("", 50).await.unwrap(); + assert_eq!(listed.backups.len(), 1); + assert!( + !listed.backups[0] + .backup_id + .contains(&*r.folder.to_string_lossy()) + ); + std::fs::write(r.folder.join("states/s1.sav"), b"newer").unwrap(); + let gate = Arc::new(Notify::new()); + let dialog = r.dialog(true, Some(gate.clone())); + let job = r + .restore("restore", &listed.backups[0].backup_id) + .await + .unwrap(); + shown(&dialog).await; + assert_eq!( + std::fs::read(r.folder.join("states/s1.sav")).unwrap(), + b"newer" + ); + assert!( + dialog.shown.lock().unwrap()[0] + .details + .iter() + .any(|p| p.ends_with("s1.sav")) + ); + gate.notify_one(); + assert_eq!(r.ended(&job.job_id).await.state(), JobState::Succeeded); + assert_eq!( + std::fs::read(r.folder.join("states/s1.sav")).unwrap(), + b"state" + ); + assert_eq!( + std::fs::read(r.folder.join("GC/USA/card.gci")).unwrap(), + b"card" + ); + assert_eq!(r.backend.recovery.lock().unwrap()[0].1, b"newer"); +} + +#[tokio::test(flavor = "multi_thread")] +async fn history_cursors_survive_new_tokens_but_not_a_changed_history_and_foreign_tokens_fail() { + let r = Ready::new().await; + r.created("one").await; + r.created("two").await; + let first = r.list("", 1).await.unwrap(); + let second = r.list(&first.next_cursor, 1).await.unwrap(); + assert_eq!(second.backups.len(), 1); + assert!(second.next_cursor.is_empty()); + r.created("three").await; + assert_eq!( + r.list(&first.next_cursor, 1).await.unwrap_err().code(), + Code::FailedPrecondition + ); + let other = Ready::new().await; + other.dialog(true, None); + assert_eq!( + other + .restore("foreign", &first.backups[0].backup_id) + .await + .unwrap_err() + .code(), + Code::NotFound + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn declined_cancelled_and_revoked_restores_write_nothing() { + let r = Ready::new().await; + r.created("one").await; + let id = r.list("", 50).await.unwrap().backups[0].backup_id.clone(); + let dialog = r.dialog(false, None); + let job = r.restore("decline", &id).await.unwrap(); + assert_eq!(r.ended(&job.job_id).await.state(), JobState::Failed); + shown(&dialog).await; + let gate = Arc::new(Notify::new()); + let dialog = r.dialog(true, Some(gate.clone())); + let job = r.restore("cancel", &id).await.unwrap(); + shown(&dialog).await; + r.f.client() + .jobs_cancel(JobCancelRequest { + mutation: Some(r.f.mutation("cancel-job", 0)), + job_id: job.job_id.clone(), + }) + .await + .unwrap(); + assert_eq!(r.ended(&job.job_id).await.state(), JobState::Cancelled); + let gate = Arc::new(Notify::new()); + let dialog = r.dialog(true, Some(gate.clone())); + let job = r.restore("revoke", &id).await.unwrap(); + shown(&dialog).await; + r.f.api + .revoke_session_permission("fixture", cap::BACKUPS_RESTORE) + .await; + gate.notify_one(); + assert_ne!(r.ended(&job.job_id).await.state(), JobState::Succeeded); + assert!(r.backend.recovery.lock().unwrap().is_empty()); +} + +#[tokio::test(flavor = "multi_thread")] +async fn restore_rejects_archive_targets_outside_rules_before_showing_confirmation() { + let r = Ready::new().await; + r.created("one").await; + r.backend + .snapshots + .lock() + .unwrap() + .get_mut("snapshot-1") + .unwrap() + .insert( + r.folder + .join("GC/USA/card.gci") + .to_string_lossy() + .into_owned(), + b"attack".to_vec(), + ); + let dialog = r.dialog(true, None); + let id = r.list("", 50).await.unwrap().backups[0].backup_id.clone(); + let job = r.restore("restore", &id).await.unwrap(); + assert_eq!(r.ended(&job.job_id).await.state(), JobState::Failed); + assert!(dialog.shown.lock().unwrap().is_empty()); + assert_eq!( + std::fs::read(r.folder.join("GC/USA/card.gci")).unwrap(), + b"card" + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn scope_revision_and_replaced_folders_fail_before_any_backup_and_unavailable_engine_is_explicit() + { + let mut r = Ready::new().await; + r.profile.revision += 1; + assert_eq!(r.create("stale").await.unwrap_err().code(), Code::Aborted); + r.profile.revision -= 1; + let original = r.folder.with_extension("away"); + std::fs::rename(&r.folder, &original).unwrap(); + std::fs::create_dir(&r.folder).unwrap(); + assert!(r.create("replaced").await.is_err()); + assert!(r.backend.requests.lock().unwrap().is_empty()); + let r = Ready::new().await; + let host = r.f.with_host(); // No engine installed on this host. + assert_eq!( + r.create("no-engine").await.unwrap_err().code(), + Code::Unavailable + ); + assert!(host.backup.lock().unwrap().is_none()); +} + +#[tokio::test(flavor = "multi_thread")] +async fn an_extension_backs_up_a_selected_store_game_without_manual_ownership_or_broad_reads() { + let f = Fixture::start_with_target( + GRANTS, + true, + None, + Some(TargetGameContext { + game_id: "5".into(), + installation_id: "id-steam:1".into(), + profile_id: String::new(), + revision: String::new(), + }), + ) + .await; + let install = f.game_dir("store-install", &[]); + let folder = f.game_dir("store-saves", &[("slot.sav", b"save")]); + f.library_in(&[ + ("steam:1", Some(5), "Selected store game", &install), + ("steam:2", Some(6), "Other game", &install), + ]); + let host = f.with_host(); + let backend = Arc::new(Backend::default()); + *host.backup.lock().unwrap() = Some(crate::plugin_host::library::BackupHostContext { + engine: backend.clone(), + destination: f + ._temp + .path() + .join("archives") + .to_string_lossy() + .into_owned(), + target: d::BackupTarget { + installation_id: String::new(), + root: install.to_string_lossy().into_owned(), + gameplay: vec![], + track_folder: true, + }, + }); + let handle = f.approve("id-steam:1", "save", &folder).await; + assert!( + f.request_access("id-steam:2", &["read"], &["save"]) + .await + .is_err() + ); + let mut proposed = profile( + "Store saves", + "", + vec![directory(&handle, "Slot", &["*.sav"])], + ); + proposed.installation_id = "id-steam:1".into(); + let profile = f.make("profile", proposed).await.unwrap(); + let job = f + .client() + .backups_request_create(BackupCreateRequest { + mutation: Some(f.mutation("create", profile.revision)), + game_id: "5".into(), + profile_id: profile.profile_id, + reason: String::new(), + }) + .await + .unwrap() + .into_inner(); + let r = Ready { + f, + folder, + profile: SaveProfileMutationReply::default(), + backend, + }; + assert_eq!(r.ended(&job.job_id).await.state(), JobState::Succeeded); + let requests = r.backend.requests.lock().unwrap(); + assert_eq!(requests[0].profile.installation, "id-steam:1"); + assert_eq!(r.f.feed.folders().len(), 2); + assert!( + r.f.feed + .folders() + .iter() + .all(|entry| entry.entry_key.starts_with("steam:")) + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn cancelling_a_running_worker_and_revising_a_confirmed_profile_prevent_effects() { + let r = Ready::new().await; + r.backend.holding.store(true, Ordering::SeqCst); + let job = r.create("cancel-running").await.unwrap(); + tokio::time::timeout(Duration::from_secs(5), async { + while !r.backend.entered.load(Ordering::SeqCst) { + tokio::time::sleep(Duration::from_millis(5)).await; + } + }) + .await + .unwrap(); + r.f.client() + .jobs_cancel(JobCancelRequest { + mutation: Some(r.f.mutation("cancel", 0)), + job_id: job.job_id.clone(), + }) + .await + .unwrap(); + r.backend.holding.store(false, Ordering::SeqCst); + assert_eq!(r.ended(&job.job_id).await.state(), JobState::Cancelled); + assert!(r.backend.snapshots.lock().unwrap().is_empty()); + r.created("one").await; + let id = r.list("", 50).await.unwrap().backups[0].backup_id.clone(); + let gate = Arc::new(Notify::new()); + let dialog = r.dialog(true, Some(gate.clone())); + let job = r.restore("restore", &id).await.unwrap(); + shown(&dialog).await; + r.f.patch( + "rename", + &r.profile.profile_id, + r.profile.revision, + &["name"], + SaveProfile { + name: "Changed".into(), + ..Default::default() + }, + ) + .await + .unwrap(); + gate.notify_one(); + assert_eq!(r.ended(&job.job_id).await.state(), JobState::Failed); + assert!(r.backend.recovery.lock().unwrap().is_empty()); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_backup_destination_inside_the_live_saves_is_refused_before_a_job_or_engine_call() { + let r = Ready::new().await; + let mut context = + r.f.feed + .host() + .unwrap() + .backup_context("fixture:1".into()) + .await + .unwrap(); + context.destination = r.folder.join("archives").to_string_lossy().into_owned(); + *r.f.with_host().backup.lock().unwrap() = Some(context); + assert_eq!( + r.create("overlap").await.unwrap_err().code(), + Code::FailedPrecondition + ); + assert!(r.backend.requests.lock().unwrap().is_empty()); + assert!(!r.folder.join("archives").exists()); +} + +#[tokio::test(flavor = "multi_thread")] +async fn changing_a_snapshot_after_its_preview_cannot_add_unreviewed_restore_targets() { + let r = Ready::new().await; + r.created("one").await; + let id = r.list("", 50).await.unwrap().backups[0].backup_id.clone(); + let gate = Arc::new(Notify::new()); + let dialog = r.dialog(true, Some(gate.clone())); + let job = r.restore("restore", &id).await.unwrap(); + shown(&dialog).await; + let extra = r.folder.join("states/unreviewed.sav"); + r.backend + .snapshots + .lock() + .unwrap() + .get_mut("snapshot-1") + .unwrap() + .insert( + extra.to_string_lossy().into_owned(), + b"not approved".to_vec(), + ); + gate.notify_one(); + assert_eq!(r.ended(&job.job_id).await.state(), JobState::Failed); + assert!(r.backend.recovery.lock().unwrap().is_empty()); + assert!(!extra.exists()); +} + +#[tokio::test(flavor = "multi_thread")] +async fn runtime_profiles_fail_closed_without_external_process_inspection() { + let mut r = Ready::new().await; + r.profile = + r.f.patch( + "runtime", + &r.profile.profile_id, + r.profile.revision, + &["runtime_id"], + SaveProfile { + runtime_id: "unresolved-runtime".into(), + ..Default::default() + }, + ) + .await + .unwrap(); + assert_eq!( + r.create("unsafe-runtime").await.unwrap_err().code(), + Code::Unavailable + ); + assert!(r.backend.requests.lock().unwrap().is_empty()); + assert!(r.f.profile(&r.profile.profile_id).await.is_ok()); +} diff --git a/crates/app/src/plugin_host/resources/tests/data.rs b/crates/app/src/plugin_host/resources/tests/data.rs new file mode 100644 index 000000000..b978d92d3 --- /dev/null +++ b/crates/app/src/plugin_host/resources/tests/data.rs @@ -0,0 +1,3380 @@ +//! Shared Data RPCs through a local ResourceHost gRPC server. + +use super::*; +use crate::plugin_host::{ + grants::PluginIdentity, + resources::ResourceApi, + shared_data::{DataBroker, Publication}, + shared_pool::DurableSharedPool, + sharing_policy::{ + ActivationReadGrant, Authorizer, SharedSharingPolicies, SharingClass, SharingPolicies, + SourceRecipientPolicy, + }, +}; +use gamenode_platform::plugin_shared_data::{ + OwnerScope, RecordProvenance, RecordWrite, SharedDataStore, WriteOutcome, +}; +use gamenode_plugin_protocol::{ + capability as cap, + prost_types::{self, Value, value::Kind}, +}; +use std::sync::Arc; +use tokio::task::JoinHandle; +use tokio_stream::wrappers::TcpListenerStream; +use tonic::transport::Channel; + +fn value(fields: &[(&str, Value)]) -> prost_types::Struct { + prost_types::Struct { + fields: fields + .iter() + .map(|(key, value)| ((*key).to_owned(), value.clone())) + .collect(), + } +} + +fn number(value: f64) -> Value { + Value { + kind: Some(Kind::NumberValue(value)), + } +} + +fn text(value: &str) -> Value { + Value { + kind: Some(Kind::StringValue(value.to_owned())), + } +} + +fn publication(owner: &PluginIdentity, fields: &[(&str, serde_json::Value)]) -> Publication { + Publication { + owner: owner.clone(), + dataset_id: "org.example.metrics.v1".into(), + category: None, + class: SharingClass::Custom, + schema_id: "org.example.metrics.v1".into(), + schema_version: 1, + fields: fields + .iter() + .map(|(key, value)| ((*key).to_owned(), value.clone())) + .collect(), + opaque_payload: Vec::new(), + resource_id: String::new(), + observed_at: 0, + sequence: 0, + source_observation_id: String::new(), + session_id: None, + publisher: None, + expires_at: None, + } +} + +fn service( + fixture: &Fixture, + data: Arc, + authorizer: Arc, +) -> ResourceApi { + ResourceApi::new( + fixture.api.clone(), + fixture.feed.clone(), + fixture.storage.clone(), + fixture.files.clone(), + fixture.network.clone(), + fixture.notifications.clone(), + fixture.jobs.clone(), + fixture.intents.clone(), + fixture.saves.clone(), + fixture.snapshots.clone(), + fixture.leases.clone(), + fixture.processes.clone(), + ) + .with_shared_data(data, authorizer) + .with_shared_pool(fixture.shared_pool.clone()) +} + +/// A restarted host: a fresh in-memory broker over the durable pool reopened from the fixture's +/// data folder, so the persisted pool sequence survives while the broker starts at zero. +fn restarted_service(fixture: &Fixture, broker: Arc) -> ResourceApi { + service(fixture, broker, fixture.shared_policies.clone()) + .with_shared_pool(Arc::new(DurableSharedPool::new(&fixture.data_dir))) +} + +async fn local_client(service: ResourceApi) -> (ResourceHostClient, JoinHandle<()>) { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let server = tokio::spawn(async move { + tonic::transport::Server::builder() + .add_service(resource_host_server::ResourceHostServer::new(service)) + .serve_with_incoming(TcpListenerStream::new(listener)) + .await + .unwrap(); + }); + let client = ResourceHostClient::connect(format!("http://{address}")) + .await + .unwrap(); + (client, server) +} + +fn data_publish(fixture: &Fixture, key: &str, value: prost_types::Struct) -> DataPublishRequest { + DataPublishRequest { + mutation: Some(fixture.mutation(key, 0)), + dataset_id: "org.example.metrics.v1".into(), + schema_id: "org.example.metrics.v1".into(), + schema_version: 1, + value: Some(value), + durability: StorageDurability::SessionOnly as i32, + ttl_seconds: 300, + resource_id: "runtime-primary".into(), + observed_at: 1_700_000_000, + sequence: 1, + source_observation_id: key.into(), + ..Default::default() + } +} + +#[tokio::test] +async fn data_publish_replays_identically_and_rejects_key_reuse_for_changed_request() { + let fixture = Fixture::new(&[cap::DATA_PUBLISH]).await; + let broker = Arc::new(DataBroker::new()); + let authorizer: Arc = Arc::new(SharingPolicies::default()); + let (mut client, server) = local_client(service(&fixture, broker, authorizer)).await; + let request = data_publish(&fixture, "data-idempotent", value(&[("fps", number(60.0))])); + + let first = client + .data_publish(request.clone()) + .await + .unwrap() + .into_inner(); + let replay = client + .data_publish(request.clone()) + .await + .unwrap() + .into_inner(); + assert_eq!(replay.record_id, first.record_id); + assert_eq!(replay.revision, first.revision); + + let mut changed = request; + changed.ttl_seconds += 1; + let error = client.data_publish(changed).await.unwrap_err(); + assert_eq!(error.code(), tonic::Code::FailedPrecondition); + server.abort(); +} + +#[tokio::test] +async fn data_publish_requires_exactly_one_nonempty_payload() { + let fixture = Fixture::new(&[cap::DATA_PUBLISH]).await; + let broker = Arc::new(DataBroker::new()); + let authorizer: Arc = Arc::new(SharingPolicies::default()); + let (mut client, server) = local_client(service(&fixture, broker, authorizer)).await; + + let mut neither = data_publish(&fixture, "payload-neither", prost_types::Struct::default()); + neither.value = None; + let error = client.data_publish(neither).await.unwrap_err(); + assert_eq!(error.code(), tonic::Code::InvalidArgument); + + let mut both = data_publish(&fixture, "payload-both", value(&[("fps", number(60.0))])); + both.opaque_payload = vec![1]; + let error = client.data_publish(both).await.unwrap_err(); + assert_eq!(error.code(), tonic::Code::InvalidArgument); + + let empty = data_publish( + &fixture, + "payload-empty-struct", + prost_types::Struct::default(), + ); + let error = client.data_publish(empty).await.unwrap_err(); + assert_eq!(error.code(), tonic::Code::InvalidArgument); + + server.abort(); +} + +/// A custom Struct carries data only. Top-level keys shaped like host authority are refused before +/// the record reaches the broker, so a payload can never shadow identity, provenance or execution. +#[tokio::test] +async fn authority_shaped_struct_fields_are_rejected_on_the_public_publish_route() { + let fixture = Fixture::new(&[cap::DATA_PUBLISH]).await; + let broker = Arc::new(DataBroker::new()); + let authorizer: Arc = Arc::new(SharingPolicies::default()); + let (mut client, server) = local_client(service(&fixture, broker.clone(), authorizer)).await; + + for field in [ + "owner", + "provenance", + "permissions", + "executable_handle", + "path", + ] { + let request = data_publish( + &fixture, + &format!("authority-{field}"), + value(&[(field, text("plugin-supplied"))]), + ); + let error = client.data_publish(request).await.unwrap_err(); + assert_eq!(error.code(), tonic::Code::InvalidArgument, "{field}"); + } + assert_eq!(broker.revision(), 0, "a rejected payload changes nothing"); + assert!( + client + .data_list(DataListRequest { + page: Some(PageRequest { + context: Some(fixture.context()), + page_size: 10, + ..Default::default() + }), + dataset_id: "org.example.metrics.v1".into(), + ..Default::default() + }) + .await + .unwrap() + .into_inner() + .records + .is_empty() + ); + + // An ordinary observation still lands after the refusals. + client + .data_publish(data_publish( + &fixture, + "authority-ordinary", + value(&[("fps", number(60.0))]), + )) + .await + .unwrap(); + server.abort(); +} + +#[tokio::test] +async fn data_publish_preserves_observation_metadata_and_host_provenance() { + let fixture = Fixture::new(&[cap::DATA_PUBLISH]).await; + let broker = Arc::new(DataBroker::new()); + let authorizer: Arc = Arc::new(SharingPolicies::default()); + let (mut client, server) = local_client(service(&fixture, broker, authorizer)).await; + let request = data_publish(&fixture, "data-metadata", value(&[("fps", number(60.0))])); + + let published = client.data_publish(request).await.unwrap().into_inner(); + let listed = client + .data_list(DataListRequest { + page: Some(PageRequest { + context: Some(fixture.context()), + page_size: 10, + ..Default::default() + }), + dataset_id: "org.example.metrics.v1".into(), + ..Default::default() + }) + .await + .unwrap() + .into_inner(); + let record = listed + .records + .iter() + .find(|record| record.record_id == published.record_id) + .unwrap(); + assert_eq!(record.resource_id, "runtime-primary"); + assert_eq!(record.observed_at, 1_700_000_000); + assert_eq!(record.sequence, 1); + assert_eq!(record.source_observation_id, "data-metadata"); + assert!(record.received_at > 0); + let provenance = record.provenance.as_ref().unwrap(); + assert_eq!(provenance.producer_plugin_id, "fixture.plugin"); + assert!(!provenance.package_version.is_empty()); + assert_eq!(provenance.package_digest.len(), 32); + server.abort(); +} + +#[tokio::test] +async fn data_publish_round_trips_opaque_bytes_and_enforces_sequence_idempotency() { + let fixture = Fixture::new(&[cap::DATA_PUBLISH]).await; + let broker = Arc::new(DataBroker::new()); + let authorizer: Arc = Arc::new(SharingPolicies::default()); + let (mut client, server) = local_client(service(&fixture, broker, authorizer)).await; + let mut request = DataPublishRequest { + mutation: Some(fixture.mutation("opaque-first", 0)), + dataset_id: "org.example.metrics.v1".into(), + schema_id: "org.example.metrics.v1".into(), + schema_version: 1, + durability: StorageDurability::SessionOnly as i32, + ttl_seconds: 300, + opaque_payload: vec![0, 1, 2, 255], + resource_id: "runtime-primary".into(), + observed_at: 1_700_000_000, + sequence: 1, + source_observation_id: "opaque-observation-1".into(), + ..Default::default() + }; + let first = client + .data_publish(request.clone()) + .await + .unwrap() + .into_inner(); + assert_eq!(first.outcome, MutationOutcome::Applied as i32); + + let replay = client + .data_publish(request.clone()) + .await + .unwrap() + .into_inner(); + assert_eq!(replay.record_id, first.record_id); + let mut changed_payload = request.clone(); + changed_payload.opaque_payload[3] = 254; + let error = client.data_publish(changed_payload).await.unwrap_err(); + assert_eq!(error.code(), tonic::Code::FailedPrecondition); + + request.mutation = Some(fixture.mutation("opaque-replay", 0)); + let duplicate = client + .data_publish(request.clone()) + .await + .unwrap() + .into_inner(); + assert_eq!(duplicate.record_id, first.record_id); + assert_eq!(duplicate.outcome, MutationOutcome::AlreadyApplied as i32); + + let got = client + .data_get(DataGetRequest { + context: Some(fixture.context()), + dataset_id: request.dataset_id.clone(), + record_id: first.record_id.clone(), + ..Default::default() + }) + .await + .unwrap() + .into_inner() + .record + .unwrap(); + assert!(got.value.is_none()); + assert_eq!(got.opaque_payload, vec![0, 1, 2, 255]); + assert_eq!(got.sequence, 1); + assert_eq!(got.source_observation_id, "opaque-observation-1"); + + request.mutation = Some(fixture.mutation("opaque-conflict", 0)); + request.source_observation_id = "different-observation".into(); + let conflict = client.data_publish(request).await.unwrap().into_inner(); + assert_eq!(conflict.outcome, MutationOutcome::RevisionConflict as i32); + assert_eq!(conflict.revision, 1); + server.abort(); +} + +#[tokio::test] +async fn publisher_session_disconnect_removes_its_session_retained_data() { + let fixture = Fixture::new(&[cap::DATA_PUBLISH]).await; + let broker = Arc::new(DataBroker::new()); + let authorizer: Arc = Arc::new(SharingPolicies::default()); + let (mut client, server) = local_client(service(&fixture, broker.clone(), authorizer)).await; + let mut request = data_publish(&fixture, "session-cleanup", value(&[("fps", number(60.0))])); + request.ttl_seconds = 0; + let published = client.data_publish(request).await.unwrap().into_inner(); + assert!(!published.record_id.is_empty()); + assert_eq!(published.expires_at, 0); + + let session_id = fixture.context().session_id; + fixture.api.disconnect("fixture").await; + // ResourceApi registered this same broker with ProviderApi, so close_session finds that the + // disconnect callback already removed the record and its sequence cursor. + assert_eq!(broker.close_session(&session_id), 0); + server.abort(); +} + +#[tokio::test] +async fn data_publish_list_get_and_watch_use_the_snapshot_revision() { + let fixture = Fixture::new(&[cap::DATA_PUBLISH]).await; + let broker = Arc::new(DataBroker::new()); + let authorizer: Arc = Arc::new(SharingPolicies::default()); + let (mut client, server) = local_client(service(&fixture, broker, authorizer)).await; + + let first = client + .data_publish(data_publish( + &fixture, + "data-first", + value(&[("fps", number(60.0))]), + )) + .await + .unwrap() + .into_inner(); + assert!(!first.record_id.is_empty()); + assert!(first.expires_at > 0); + + let context = Some(fixture.context()); + let list = client + .data_list(DataListRequest { + page: Some(PageRequest { + context: context.clone(), + page_size: 10, + ..Default::default() + }), + dataset_id: "org.example.metrics.v1".into(), + ..Default::default() + }) + .await + .unwrap() + .into_inner(); + assert_eq!(list.records.len(), 1); + assert_eq!(list.records[0].record_id, first.record_id); + assert!(list.revision >= list.records[0].revision); + + let mut watch = client + .data_watch(DataWatchRequest { + context, + dataset_id: "org.example.metrics.v1".into(), + after_revision: list.revision, + common_data_categories: None, + }) + .await + .unwrap() + .into_inner(); + let mut second_request = data_publish(&fixture, "data-second", value(&[("fps", number(75.0))])); + second_request.sequence = 2; + let second = client + .data_publish(second_request) + .await + .unwrap() + .into_inner(); + let event = tokio::time::timeout(std::time::Duration::from_secs(2), watch.message()) + .await + .unwrap() + .unwrap() + .unwrap(); + assert_eq!(event.event_type, "published"); + assert_eq!(event.revision, second.revision); + assert_eq!(event.record.unwrap().record_id, second.record_id); + + let got = client + .data_get(DataGetRequest { + context: Some(fixture.context()), + dataset_id: "org.example.metrics.v1".into(), + record_id: second.record_id, + common_data_categories: None, + }) + .await + .unwrap() + .into_inner() + .record + .unwrap(); + assert_eq!(got.publisher_id, "fixture.plugin"); + assert_eq!( + got.value.unwrap().fields["fps"].kind, + Some(Kind::NumberValue(75.0)) + ); + server.abort(); +} + +pub(super) async fn consumer_session(fixture: &Fixture) -> Session { + consumer_session_with_grants(fixture, &[cap::STORAGE_WRITE]).await +} + +pub(super) async fn consumer_session_with_grants( + fixture: &Fixture, + grants: &[&'static str], +) -> Session { + let mut capabilities = vec![cap::CONTEXT]; + capabilities.extend_from_slice(grants); + fixture + .api + .register(Registration { + provider_id: "consumer".into(), + plugin_id: "org.example.consumer".into(), + kind: crate::plugin_host::provider::RegistrationKind::Provider, + declared_developer: "Consumer developer".into(), + package_digest: vec![8; 32], + origin: RegistrationOrigin::ThirdParty { + publisher_fingerprint: "cd".repeat(32), + }, + capabilities: capabilities.iter().map(|cap| (*cap).into()).collect(), + shared_catalog: false, + playtime: Default::default(), + services: Arc::new(NoServices), + }) + .unwrap(); + let launch = fixture.api.begin_launch("consumer").unwrap(); + let credential = (0..launch.credential.len()) + .step_by(2) + .map(|i| u8::from_str_radix(&launch.credential[i..i + 2], 16).unwrap()) + .collect(); + let session = Session::open_with_options( + Launch { + endpoint: fixture.endpoint.clone(), + credential, + operation_id: "consumer-launch".into(), + }, + "org.example.consumer", + "consumer", + "1.0", + &capabilities, + SessionOptions { + min_api_major: 1, + min_api_minor: cap::THIRD_PARTY_API_MINOR, + max_api_major: 1, + max_api_minor: gamenode_plugin_protocol::API_MINOR, + ..SessionOptions::default() + }, + ) + .await + .unwrap(); + launch.ready.await.unwrap(); + session +} + +pub(super) fn authenticated_identity( + fixture: &Fixture, + context: &ServiceContext, +) -> PluginIdentity { + let caller = fixture + .api + .authorize_resource_session(Some(context)) + .unwrap(); + ResourceApi::data_identity(&caller).unwrap() +} + +/// A second third-party plugin opened as a game-bound extension session. It publishes +/// per-game data under the host-selected target, like a bundled provider's runtime adapter. +pub(super) async fn producer_session_with_grants( + fixture: &Fixture, + grants: &[&'static str], + target: TargetGameContext, +) -> Session { + let mut capabilities = vec![cap::CONTEXT]; + capabilities.extend_from_slice(grants); + let registration_id = + crate::plugin_host::provider::extension_registration_id("org.example.producer"); + fixture + .api + .register(Registration { + provider_id: registration_id.clone(), + plugin_id: "org.example.producer".into(), + kind: crate::plugin_host::provider::RegistrationKind::Extension, + declared_developer: "Example developer".into(), + package_digest: vec![8; 32], + origin: RegistrationOrigin::ThirdParty { + publisher_fingerprint: "cd".repeat(32), + }, + capabilities: capabilities.iter().map(|cap| (*cap).into()).collect(), + shared_catalog: false, + playtime: Default::default(), + services: Arc::new(NoServices), + }) + .unwrap(); + let launch = fixture + .api + .begin_extension_launch( + ®istration_id, + fixture.api.profiles().epoch(), + target.clone(), + ) + .unwrap(); + let credential = (0..launch.credential.len()) + .step_by(2) + .map(|i| u8::from_str_radix(&launch.credential[i..i + 2], 16).unwrap()) + .collect(); + let session = Session::open_with_options( + Launch { + endpoint: fixture.endpoint.clone(), + credential, + operation_id: "producer-launch".into(), + }, + "org.example.producer", + "", + "1.0", + &capabilities, + SessionOptions { + min_api_major: 1, + min_api_minor: cap::THIRD_PARTY_API_MINOR, + max_api_major: 1, + max_api_minor: gamenode_plugin_protocol::API_MINOR, + session_kind: SessionKind::Extension, + target_game: Some(target), + ..SessionOptions::default() + }, + ) + .await + .unwrap(); + launch.ready.await.unwrap(); + session +} + +fn list_request(context: &ServiceContext, dataset_id: &str) -> DataListRequest { + DataListRequest { + page: Some(PageRequest { + context: Some(context.clone()), + page_size: 10, + ..Default::default() + }), + dataset_id: dataset_id.into(), + ..Default::default() + } +} + +fn assert_projected(record: &DataRecord, receipt: &DataMutationReply, fps: f64) { + assert_eq!(record.record_id, receipt.record_id); + assert_eq!(record.revision, receipt.revision); + assert_eq!(record.value, Some(value(&[("fps", number(fps))]))); + assert!(record.opaque_payload.is_empty()); + let provenance = record.provenance.as_ref().unwrap(); + assert_eq!(provenance.producer_plugin_id, "fixture.plugin"); + assert_eq!(provenance.publisher_fingerprint, "ab".repeat(32)); +} + +#[tokio::test] +async fn persisted_custom_policy_filters_authenticated_public_exchange_and_revokes_access() { + use futures_util::StreamExt; + + let fixture = Fixture::new(&[cap::DATA_PUBLISH]).await; + let consumer = consumer_session(&fixture).await; + let context = consumer.host.resource_context().unwrap().clone(); + let source = authenticated_identity(&fixture, &fixture.context()); + let recipient = authenticated_identity(&fixture, &context); + let dataset = "org.example.metrics.v1"; + let other_dataset = "org.example.private.v1"; + let broker = Arc::new(DataBroker::new()); + let dir = tempfile::tempdir().unwrap(); + let policy = |history, live| { + SourceRecipientPolicy::new( + source.clone(), + recipient.clone(), + SharingClass::Custom, + dataset.into(), + ["fps".into()], + history, + live, + ) + .unwrap() + }; + { + let store = SharedSharingPolicies::open(dir.path()).unwrap(); + store + .replace_recipient_policies( + &recipient, + 0, + ActivationReadGrant::default(), + vec![policy(true, false)], + ) + .unwrap(); + } + let store = Arc::new(SharedSharingPolicies::open(dir.path()).unwrap()); + let resource = service(&fixture, broker, store.clone()); + let (mut consumer_rpc, server) = local_client(resource.clone()).await; + let mut producer_rpc = consumer_rpc.clone(); + let publish = |sequence, fps| { + let key = format!("metrics-{sequence}"); + let mut request = data_publish( + &fixture, + &key, + value(&[("fps", number(fps)), ("device_id", number(42.0))]), + ); + request.sequence = sequence; + request + }; + let first = producer_rpc + .data_publish(publish(1, 60.0)) + .await + .unwrap() + .into_inner(); + let mut private = publish(1, 1.0); + private.dataset_id = other_dataset.into(); + private.schema_id = other_dataset.into(); + private.mutation = Some(fixture.mutation("private-record", 0)); + producer_rpc.data_publish(private).await.unwrap(); + + let listed = consumer_rpc + .data_list(list_request(&context, dataset)) + .await + .unwrap() + .into_inner(); + assert_eq!(listed.records.len(), 1); + assert_projected(&listed.records[0], &first, 60.0); + let get = DataGetRequest { + context: Some(context.clone()), + dataset_id: dataset.into(), + record_id: first.record_id.clone(), + ..Default::default() + }; + let fetched = consumer_rpc + .data_get(get.clone()) + .await + .unwrap() + .into_inner(); + assert_projected(&fetched.record.unwrap(), &first, 60.0); + let denied = consumer_rpc + .data_list(list_request(&context, other_dataset)) + .await + .unwrap() + .into_inner(); + assert!(denied.records.is_empty()); + + let watch = |after_revision| DataWatchRequest { + context: Some(context.clone()), + dataset_id: dataset.into(), + after_revision, + ..Default::default() + }; + let mut history_only = + ResourceHost::data_watch(&resource, Request::new(watch(listed.revision))) + .await + .unwrap() + .into_inner(); + producer_rpc.data_publish(publish(2, 65.0)).await.unwrap(); + assert!( + tokio::time::timeout(Duration::ZERO, history_only.next()) + .await + .is_err() + ); + + let revision = store.recipient_snapshot(&recipient).unwrap().revision; + let revision = store + .replace_recipient_policies( + &recipient, + revision, + ActivationReadGrant::default(), + vec![policy(false, true)], + ) + .unwrap(); + let listed = consumer_rpc + .data_list(list_request(&context, dataset)) + .await + .unwrap() + .into_inner(); + assert!(listed.records.is_empty()); + let mut live = consumer_rpc + .data_watch(watch(listed.revision)) + .await + .unwrap() + .into_inner(); + let third = producer_rpc + .data_publish(publish(3, 70.0)) + .await + .unwrap() + .into_inner(); + let event = tokio::time::timeout(Duration::from_secs(2), live.message()) + .await + .unwrap() + .unwrap() + .unwrap(); + assert_eq!(event.event_type, "published"); + assert_projected(&event.record.unwrap(), &third, 70.0); + + let revision = store + .replace_recipient_policies( + &recipient, + revision, + ActivationReadGrant::default(), + vec![policy(true, true)], + ) + .unwrap(); + let listed = consumer_rpc + .data_list(list_request(&context, dataset)) + .await + .unwrap() + .into_inner(); + assert_eq!(listed.records.len(), 3); + assert_projected(&listed.records[2], &third, 70.0); + let mut live = consumer_rpc + .data_watch(watch(listed.revision)) + .await + .unwrap() + .into_inner(); + // Keep this second ResourceHost stream unpolled so revocation precedes dequeue. + let mut pending = ResourceHost::data_watch(&resource, Request::new(watch(listed.revision))) + .await + .unwrap() + .into_inner(); + let fourth = producer_rpc + .data_publish(publish(4, 75.0)) + .await + .unwrap() + .into_inner(); + let event = tokio::time::timeout(Duration::from_secs(2), live.message()) + .await + .unwrap() + .unwrap() + .unwrap(); + assert_eq!(event.event_type, "published"); + assert_projected(&event.record.unwrap(), &fourth, 75.0); + + let mut durable = publish(5, 60.0); + durable.durability = StorageDurability::Persistent as i32; + let error = producer_rpc.data_publish(durable).await.unwrap_err(); + assert_eq!(error.code(), Code::PermissionDenied); + assert!(error.message().contains("storage.persist")); + let error = consumer_rpc + .storage_put(StoragePutRequest { + mutation: Some(MutationContext { + context: Some(context.clone()), + idempotency_key: "durable-copy".into(), + ..Default::default() + }), + key: "copy".into(), + value: vec![60], + durability: StorageDurability::Persistent as i32, + ..Default::default() + }) + .await + .unwrap_err(); + assert_eq!(error.code(), Code::PermissionDenied); + + let mut page = list_request(&context, dataset); + page.page.as_mut().unwrap().page_size = 1; + let listed = consumer_rpc + .data_list(page.clone()) + .await + .unwrap() + .into_inner(); + assert_eq!(listed.revision, fourth.revision); + assert!(!listed.next_cursor.is_empty()); + page.page.as_mut().unwrap().cursor = listed.next_cursor; + store + .replace_recipient_policies(&recipient, revision, ActivationReadGrant::default(), vec![]) + .unwrap(); + assert_eq!( + pending.next().await.unwrap().unwrap_err().code(), + Code::FailedPrecondition + ); + assert!(pending.next().await.is_none()); + assert_eq!( + consumer_rpc.data_list(page).await.unwrap_err().code(), + Code::FailedPrecondition + ); + assert_eq!( + consumer_rpc.data_get(get).await.unwrap_err().code(), + Code::NotFound + ); + let denied = consumer_rpc + .data_list(list_request(&context, dataset)) + .await + .unwrap() + .into_inner(); + assert!(denied.records.is_empty()); + server.abort(); +} + +#[tokio::test] +async fn recipient_must_explicitly_persist_a_projected_shared_record() { + use gamenode_plugin_protocol::prost::Message; + + let fixture = Fixture::new(&[cap::DATA_PUBLISH]).await; + let consumer = consumer_session_with_grants( + &fixture, + &[cap::STORAGE_READ, cap::STORAGE_WRITE, cap::STORAGE_PERSIST], + ) + .await; + let consumer_context = consumer.host.resource_context().unwrap().clone(); + let source = authenticated_identity(&fixture, &fixture.context()); + let recipient = authenticated_identity(&fixture, &consumer_context); + fixture + .shared_policies + .set_source_recipient_policy( + SourceRecipientPolicy::new( + source, + recipient, + SharingClass::Custom, + "org.example.metrics.v1".into(), + ["fps".into()], + true, + false, + ) + .unwrap(), + ) + .unwrap(); + + let published = fixture + .client() + .data_publish(data_publish( + &fixture, + "retained-shared-record", + value(&[("fps", number(60.0)), ("device_id", number(42.0))]), + )) + .await + .unwrap() + .into_inner(); + let read = consumer + .host + .resource_client() + .data_get(DataGetRequest { + context: Some(consumer_context.clone()), + dataset_id: "org.example.metrics.v1".into(), + record_id: published.record_id, + ..Default::default() + }) + .await + .unwrap() + .into_inner() + .record + .unwrap(); + assert_eq!(read.value.as_ref().unwrap().fields.len(), 1); + assert!(read.value.as_ref().unwrap().fields.contains_key("fps")); + + let stored = consumer + .host + .resource_client() + .storage_put(StoragePutRequest { + mutation: Some(MutationContext { + context: Some(consumer_context.clone()), + idempotency_key: "retain-projected-report".into(), + expected_revision: 0, + ..Default::default() + }), + key: "shared/metrics/latest".into(), + value: read.encode_to_vec(), + durability: StorageDurability::Persistent as i32, + ttl_seconds: 3600, + }) + .await + .unwrap() + .into_inner(); + assert_eq!(stored.durability, StorageDurability::Persistent as i32); + assert!(stored.expires_at > 0); + assert!(stored.usage_bytes > 0); + + let restored = consumer + .host + .resource_client() + .storage_get(StorageGetRequest { + context: Some(consumer_context), + key: "shared/metrics/latest".into(), + }) + .await + .unwrap() + .into_inner(); + assert!(restored.found); + assert_eq!(restored.durability, StorageDurability::Persistent as i32); + assert_eq!(restored.expires_at, stored.expires_at); + let retained = DataRecord::decode(restored.value.as_slice()).unwrap(); + assert_eq!(retained.value.unwrap().fields.len(), 1); +} + +#[tokio::test] +async fn consented_runtime_session_data_projection_hides_handles_and_credentials() { + let fixture = Fixture::new(&[cap::DATA_PUBLISH]).await; + let consumer = consumer_session(&fixture).await; + let context = consumer.host.resource_context().unwrap().clone(); + let source = authenticated_identity(&fixture, &fixture.context()); + let recipient = authenticated_identity(&fixture, &context); + let dataset = "org.example.runtime-sessions.v1"; + let policy = SourceRecipientPolicy::new( + source, + recipient, + SharingClass::Custom, + dataset.into(), + ["game_id".into(), "content_id".into(), "transition".into()], + true, + true, + ) + .unwrap(); + let dir = tempfile::tempdir().unwrap(); + let store = Arc::new(SharedSharingPolicies::open(dir.path()).unwrap()); + store + .replace_recipient_policies( + &authenticated_identity(&fixture, &context), + 0, + ActivationReadGrant::default(), + vec![policy], + ) + .unwrap(); + let resource = service(&fixture, Arc::new(DataBroker::new()), store); + let (mut client, server) = local_client(resource).await; + + let mut request = data_publish( + &fixture, + "runtime-session-observation", + value(&[ + ("game_id", text("620")), + ("content_id", text("rom:zelda")), + ("transition", text("started")), + ("process_handle", text("opaque-process-handle")), + ("credential", text("launch-secret")), + ]), + ); + request.dataset_id = dataset.into(); + request.schema_id = dataset.into(); + let published = client.data_publish(request).await.unwrap().into_inner(); + let listed = client + .data_list(list_request(&context, dataset)) + .await + .unwrap() + .into_inner(); + assert_eq!(listed.records.len(), 1); + assert_eq!( + listed.records[0].value, + Some(value(&[ + ("game_id", text("620")), + ("content_id", text("rom:zelda")), + ("transition", text("started")), + ])) + ); + assert_eq!(listed.records[0].record_id, published.record_id); + assert!(listed.records[0].opaque_payload.is_empty()); + let fetched = client + .data_get(DataGetRequest { + context: Some(context.clone()), + dataset_id: dataset.into(), + record_id: published.record_id, + ..Default::default() + }) + .await + .unwrap() + .into_inner() + .record + .unwrap(); + assert_eq!(fetched.value, listed.records[0].value); + + let mut live = client + .data_watch(DataWatchRequest { + context: Some(context), + dataset_id: dataset.into(), + after_revision: listed.revision, + ..Default::default() + }) + .await + .unwrap() + .into_inner(); + let mut paused_request = data_publish( + &fixture, + "runtime-session-paused", + value(&[ + ("game_id", text("620")), + ("content_id", text("rom:zelda")), + ("transition", text("paused")), + ("process_handle", text("opaque-process-handle")), + ("credential", text("launch-secret")), + ]), + ); + paused_request.dataset_id = dataset.into(); + paused_request.schema_id = dataset.into(); + paused_request.sequence = 2; + paused_request.source_observation_id = "runtime-session-paused".into(); + client.data_publish(paused_request).await.unwrap(); + let event = tokio::time::timeout(Duration::from_secs(2), live.message()) + .await + .unwrap() + .unwrap() + .unwrap(); + assert_eq!(event.event_type, "published"); + assert_eq!( + event.record.unwrap().value, + Some(value(&[ + ("game_id", text("620")), + ("content_id", text("rom:zelda")), + ("transition", text("paused")), + ])) + ); + server.abort(); +} + +#[tokio::test] +async fn persisted_common_policy_requires_explicit_selectors_on_public_reads() { + let fixture = Fixture::new(&[]).await; + let recipient = authenticated_identity(&fixture, &fixture.context()); + let source = PluginIdentity { + plugin_id: "org.example.adapter".into(), + publisher_fingerprint: "1234".into(), + profile_id: recipient.profile_id.clone(), + }; + let dataset = "org.example.metrics.v1"; + let broker = Arc::new(DataBroker::new()); + let now = unix_now().unwrap(); + let category = CommonDataCategory::GamePerformanceHistory; + // DataPublish is custom-only. Stand in for a host domain adapter producing common records. + let mut common = publication(&source, &[("fps", serde_json::json!(60))]); + common.class = SharingClass::Common; + common.category = Some(category); + let first = broker.publish(common.clone(), now).unwrap(); + let second = broker.publish(common.clone(), now).unwrap(); + common.owner.profile_id = "different-profile".into(); + let foreign = broker.publish(common, now).unwrap(); + let dir = tempfile::tempdir().unwrap(); + let grant = ActivationReadGrant::new([category], [first.record_id.clone()]).unwrap(); + SharedSharingPolicies::open(dir.path()) + .unwrap() + .replace_recipient_policies(&recipient, 0, grant, vec![]) + .unwrap(); + let store = Arc::new(SharedSharingPolicies::open(dir.path()).unwrap()); + let (mut client, server) = local_client(service(&fixture, broker, store)).await; + let context = fixture.context(); + let mut list = list_request(&context, dataset); + assert!( + client + .data_list(list.clone()) + .await + .unwrap() + .into_inner() + .records + .is_empty() + ); + + let mut get = DataGetRequest { + context: Some(context), + dataset_id: dataset.into(), + record_id: first.record_id.clone(), + ..Default::default() + }; + assert_eq!( + client.data_get(get.clone()).await.unwrap_err().code(), + Code::NotFound + ); + let selected = CommonDataSelector { + categories: vec![], + selected_record_ids: vec![first.record_id.clone(), second.record_id.clone()], + }; + get.common_data_categories = Some(selected.clone()); + let fetched = client.data_get(get).await.unwrap().into_inner(); + assert_eq!(fetched.record.unwrap().record_id, first.record_id); + + list.common_data_categories = Some(selected); + let selected = client.data_list(list.clone()).await.unwrap().into_inner(); + assert_eq!(selected.records.len(), 1); + assert_eq!(selected.records[0].record_id, first.record_id); + + list.common_data_categories = Some(CommonDataSelector { + categories: vec![category as i32], + selected_record_ids: vec![foreign.record_id], + }); + let selected = client.data_list(list).await.unwrap().into_inner(); + let ids: Vec<_> = selected.records.into_iter().map(|r| r.record_id).collect(); + assert_eq!(ids, [first.record_id, second.record_id]); + server.abort(); +} + +fn durable_owner(fixture: &Fixture, context: &ServiceContext) -> OwnerScope { + let caller = fixture + .api + .authorize_resource_session(Some(context)) + .unwrap(); + let namespace = caller.namespace.as_ref().expect("third-party namespace"); + OwnerScope::new(*namespace.storage_owner().key(), caller.profile_epoch).unwrap() +} + +/// The opaque storage key of one authenticated session's durable owner, for pool-level fixtures +/// that stand in for a host domain adapter writing beside the plugin's own publications. +fn durable_owner_key(fixture: &Fixture, context: &ServiceContext) -> [u8; 32] { + let caller = fixture + .api + .authorize_resource_session(Some(context)) + .unwrap(); + let namespace = caller.namespace.as_ref().expect("third-party namespace"); + *namespace.storage_owner().key() +} + +fn unix_seconds() -> i64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_secs() as i64 +} + +fn durable_request( + context: &ServiceContext, + key: &str, + resource_id: &str, + fps: f64, +) -> DataPublishRequest { + DataPublishRequest { + mutation: Some(MutationContext { + context: Some(context.clone()), + idempotency_key: key.into(), + ..Default::default() + }), + dataset_id: "org.example.metrics.v1".into(), + schema_id: "org.example.metrics.v1".into(), + schema_version: 1, + value: Some(value(&[("fps", number(fps))])), + opaque_payload: Vec::new(), + durability: StorageDurability::Persistent as i32, + ttl_seconds: 300, + resource_id: resource_id.into(), + observed_at: 1_700_000_000, + sequence: 1, + source_observation_id: key.into(), + } +} + +#[tokio::test] +async fn durable_publish_without_storage_persist_fails_without_session_fallback() { + let fixture = Fixture::new(&[cap::DATA_PUBLISH]).await; + let mut request = data_publish(&fixture, "durable-denied", value(&[("fps", number(60.0))])); + request.durability = StorageDurability::Persistent as i32; + + let error = fixture.client().data_publish(request).await.unwrap_err(); + assert_eq!(error.code(), Code::PermissionDenied); + assert!( + error.message().contains("storage.persist"), + "unexpected message: {}", + error.message() + ); + + // Nothing was retained for the session and no pool file was created. + let listed = fixture + .client() + .data_list(list_request(&fixture.context(), "org.example.metrics.v1")) + .await + .unwrap() + .into_inner(); + assert!(listed.records.is_empty()); + assert!( + SharedDataStore::open_existing(&fixture.data_dir) + .unwrap() + .is_none() + ); +} + +#[tokio::test] +async fn session_only_publish_is_never_persisted() { + let fixture = Fixture::new(&[cap::DATA_PUBLISH, cap::STORAGE_PERSIST]).await; + let published = fixture + .client() + .data_publish(data_publish( + &fixture, + "session-only", + value(&[("fps", number(60.0))]), + )) + .await + .unwrap() + .into_inner(); + assert_eq!( + published.durability, + StorageDurability::SessionOnly as i32, + "the reply reports the mode actually used" + ); + + let listed = fixture + .client() + .data_list(list_request(&fixture.context(), "org.example.metrics.v1")) + .await + .unwrap() + .into_inner(); + assert_eq!(listed.records.len(), 1, "the session copy is readable"); + assert!( + SharedDataStore::open_existing(&fixture.data_dir) + .unwrap() + .is_none(), + "session-only data never reaches the durable pool" + ); +} + +#[tokio::test] +async fn session_only_publish_disappears_at_producer_disconnect_and_never_reaches_the_pool() { + // storage.persist is granted: only the requested durability keeps this record in memory. + let fixture = Fixture::new(&[cap::DATA_PUBLISH, cap::STORAGE_PERSIST]).await; + let published = fixture + .client() + .data_publish(data_publish( + &fixture, + "session-only-disconnect", + value(&[("fps", number(60.0))]), + )) + .await + .unwrap() + .into_inner(); + assert_eq!(published.durability, StorageDurability::SessionOnly as i32); + + let listed = fixture + .client() + .data_list(list_request(&fixture.context(), "org.example.metrics.v1")) + .await + .unwrap() + .into_inner(); + assert_eq!(listed.records.len(), 1, "the session copy is readable"); + assert_eq!(listed.records[0].record_id, published.record_id); + assert_eq!( + listed.records[0].durability, + StorageDurability::SessionOnly as i32 + ); + assert!( + SharedDataStore::open_existing(&fixture.data_dir) + .unwrap() + .is_none(), + "session-only data never reaches the durable pool" + ); + + let session_id = fixture.context().session_id; + fixture.api.disconnect("fixture").await; + // This broker is the one the fixture's ResourceApi registered with ProviderApi, so the + // disconnect already removed the producer's session rows and fenced their watches. + assert_eq!(fixture.data_broker.close_session(&session_id), 0); + assert!( + fixture + .data_broker + .sharing_catalog(unix_seconds()) + .is_empty(), + "the session-only record disappears with its producer session" + ); + assert!( + SharedDataStore::open_existing(&fixture.data_dir) + .unwrap() + .is_none(), + "producer disconnect never leaves a durable copy behind" + ); +} + +#[tokio::test] +async fn durable_publish_survives_producer_disconnect() { + let fixture = Fixture::new(&[cap::DATA_PUBLISH]).await; + let producer = + consumer_session_with_grants(&fixture, &[cap::DATA_PUBLISH, cap::STORAGE_PERSIST]).await; + let context = producer.host.resource_context().unwrap().clone(); + let owner = durable_owner(&fixture, &context); + + let published = producer + .host + .resource_client() + .data_publish(durable_request( + &context, + "durable-survives", + "runtime-primary", + 60.0, + )) + .await + .unwrap() + .into_inner(); + assert_eq!(published.durability, StorageDurability::Persistent as i32); + assert!(!published.record_id.is_empty()); + assert!(published.expires_at > 0); + + drop(producer); + + // Reopen the pool as a restarted host would and read the producer's record directly. + let store = SharedDataStore::open(&fixture.data_dir).unwrap(); + let records = store + .list_dataset(&owner, "org.example.metrics.v1", unix_seconds()) + .unwrap() + .records; + assert_eq!(records.len(), 1); + assert_eq!(records[0].record_id, published.record_id); + assert_eq!(records[0].revision, published.revision); + assert_eq!(records[0].expires_at, Some(published.expires_at)); + assert_eq!( + records[0].provenance.source_plugin_id, + "org.example.consumer" + ); + assert_eq!( + records[0].provenance.source_publisher_fingerprint, + "cd".repeat(32) + ); +} + +#[tokio::test] +async fn durable_resource_replacement_is_owner_scoped() { + let fixture = Fixture::new(&[cap::DATA_PUBLISH, cap::STORAGE_PERSIST]).await; + let other = + consumer_session_with_grants(&fixture, &[cap::DATA_PUBLISH, cap::STORAGE_PERSIST]).await; + let other_context = other.host.resource_context().unwrap().clone(); + let own_owner = durable_owner(&fixture, &fixture.context()); + let other_owner = durable_owner(&fixture, &other_context); + + let first = fixture + .client() + .data_publish(durable_request( + &fixture.context(), + "durable-first", + "runtime-primary", + 60.0, + )) + .await + .unwrap() + .into_inner(); + let foreign = other + .host + .resource_client() + .data_publish(durable_request( + &other_context, + "durable-foreign", + "runtime-primary", + 1.0, + )) + .await + .unwrap() + .into_inner(); + assert_ne!(first.record_id, foreign.record_id); + + let replaced = fixture + .client() + .data_publish(durable_request( + &fixture.context(), + "durable-replacement", + "runtime-primary", + 75.0, + )) + .await + .unwrap() + .into_inner(); + assert_eq!(replaced.record_id, first.record_id); + assert!(replaced.revision > first.revision); + + let store = SharedDataStore::open(&fixture.data_dir).unwrap(); + let now = unix_seconds(); + let own = store + .list_dataset(&own_owner, "org.example.metrics.v1", now) + .unwrap() + .records; + assert_eq!(own.len(), 1, "replacement is in place"); + assert_eq!(own[0].record_id, first.record_id); + assert_eq!(own[0].revision, replaced.revision); + let fields: serde_json::Value = serde_json::from_str(&own[0].fields_json).unwrap(); + assert_eq!(fields["fps"], 75.0); + + let foreign_records = store + .list_dataset(&other_owner, "org.example.metrics.v1", now) + .unwrap() + .records; + assert_eq!(foreign_records.len(), 1, "the other producer is untouched"); + assert_eq!(foreign_records[0].record_id, foreign.record_id); + assert_eq!(foreign_records[0].revision, foreign.revision); + let fields: serde_json::Value = serde_json::from_str(&foreign_records[0].fields_json).unwrap(); + assert_eq!(fields["fps"], 1.0); +} + +/// A reviewed dataset-scope grant from one source to one recipient. +fn grant_durable_dataset( + fixture: &Fixture, + source: &PluginIdentity, + recipient: &PluginIdentity, + history: bool, + live: bool, +) { + grant_durable_dataset_fields( + fixture, + source, + recipient, + "org.example.metrics.v1", + ["fps".into()], + history, + live, + ); +} + +/// A reviewed dataset-scope grant for an explicit dataset and field projection. +fn grant_durable_dataset_fields( + fixture: &Fixture, + source: &PluginIdentity, + recipient: &PluginIdentity, + dataset_id: &str, + fields: impl IntoIterator, + history: bool, + live: bool, +) { + fixture + .shared_policies + .set_source_recipient_policy( + SourceRecipientPolicy::new( + source.clone(), + recipient.clone(), + SharingClass::Custom, + dataset_id.to_owned(), + fields, + history, + live, + ) + .unwrap(), + ) + .unwrap(); +} + +fn durable_catalog_request( + context: &ServiceContext, + key: &str, + resource_id: &str, + title: &str, +) -> DataPublishRequest { + DataPublishRequest { + mutation: Some(MutationContext { + context: Some(context.clone()), + idempotency_key: key.into(), + ..Default::default() + }), + dataset_id: "org.example.catalog.v1".into(), + schema_id: "org.example.catalog.v1".into(), + schema_version: 1, + value: Some(value(&[("title", text(title))])), + opaque_payload: Vec::new(), + durability: StorageDurability::Persistent as i32, + ttl_seconds: 300, + resource_id: resource_id.into(), + observed_at: 1_700_000_000, + sequence: 1, + source_observation_id: key.into(), + } +} + +#[tokio::test] +async fn two_plugin_durable_catalog_fixture_survives_stop_restart_revocation_and_cleanup() { + const CATALOG: &str = "org.example.catalog.v1"; + const HISTORY: &str = "game.performance.history.v1"; + const CATEGORY: CommonDataCategory = CommonDataCategory::GamePerformanceHistory; + + // The consumer is the ordinary third-party plugin and the producer is a game-bound extension + // session, exactly like a bundled runtime adapter. Its performance writes are checked against + // the host-selected game, and every grant below still applies to the API only: a native plugin + // process keeps the OS access of the user's identity (docs/plugin-api-permissions.md, "This + // audit describes API enforcement"; docs/plugin-development.md, "Host capabilities and native + // access are different"). No assertion here claims to observe the other process. + let fixture = Fixture::new(&[ + cap::DATA_PUBLISH, + cap::STORAGE_PERSIST, + cap::STORAGE_READ, + cap::GAME_PERFORMANCE_READ, + ]) + .await; + let target = TargetGameContext { + game_id: "5".into(), + installation_id: "steam:five".into(), + profile_id: String::new(), + revision: "library-rev-1".into(), + }; + let producer = producer_session_with_grants( + &fixture, + &[ + cap::GAME_LAUNCH, + cap::DATA_PUBLISH, + cap::STORAGE_PERSIST, + cap::STORAGE_WRITE, + cap::GAME_PERFORMANCE_PUBLISH, + ], + target, + ) + .await; + let producer_context = producer.host.resource_context().unwrap().clone(); + let producer_owner = durable_owner(&fixture, &producer_context); + let producer_key = durable_owner_key(&fixture, &producer_context); + let own_owner = durable_owner(&fixture, &fixture.context()); + let source = authenticated_identity(&fixture, &producer_context); + let recipient = authenticated_identity(&fixture, &fixture.context()); + assert_eq!( + producer_context + .target_game + .as_ref() + .map(|target| target.game_id.as_str()), + Some("5"), + "the producer session is bound to the selected game" + ); + + // The producer publishes one durable catalog record and a private value; the consumer also + // owns one row in the same catalog dataset so cleanup can prove owner isolation. + let published = producer + .host + .resource_client() + .data_publish(durable_catalog_request( + &producer_context, + "catalog-producer", + "disc-1", + "Dolphin", + )) + .await + .unwrap() + .into_inner(); + assert_eq!(published.durability, StorageDurability::Persistent as i32); + producer + .host + .resource_client() + .storage_put(StoragePutRequest { + mutation: Some(MutationContext { + context: Some(producer_context.clone()), + idempotency_key: "producer-private".into(), + expected_revision: 0, + ..Default::default() + }), + key: "catalog-notes".into(), + value: b"producer-only".to_vec(), + durability: StorageDurability::Persistent as i32, + ttl_seconds: 0, + }) + .await + .unwrap(); + let own = fixture + .client() + .data_publish(durable_catalog_request( + &fixture.context(), + "catalog-consumer", + "disc-2", + "Other", + )) + .await + .unwrap() + .into_inner(); + assert_ne!(published.record_id, own.record_id); + + // No producer adapter feeds a common category into this build's broker, so the durable + // history row is written at the pool boundary where a host domain adapter would write it. + let history = write_pool_row( + &fixture, + producer_key, + &source, + HISTORY, + PoolRowClass::Common(CATEGORY), + "performance-series", + r#"{"fps":59,"game_id":"5"}"#, + ); + + let category_selector = CommonDataSelector { + categories: vec![CATEGORY as i32], + selected_record_ids: Vec::new(), + }; + let history_list = |selector: Option| { + let mut request = list_request(&fixture.context(), HISTORY); + request.common_data_categories = selector; + request + }; + let performance_list = + |game_id: &str, selector: Option| PerformanceListRequest { + page: Some(PageRequest { + context: Some(fixture.context()), + page_size: 10, + common_data_categories: selector, + ..Default::default() + }), + game_id: game_id.into(), + computer_context_id: "active-host".into(), + projection_id: "performance.v1".into(), + }; + let mut performance = fixture.host.game_performance_client(); + let record_ids = |reply: DataListReply| { + reply + .records + .into_iter() + .map(|record| record.record_id) + .collect::>() + }; + + // Private-only defaults: no grants yet, so only the consumer's own row is disclosed. An + // explicit selector without a matching grant is denied (empty) rather than narrowed. + assert_eq!( + record_ids( + fixture + .client() + .data_list(list_request(&fixture.context(), CATALOG)) + .await + .unwrap() + .into_inner() + ), + vec![own.record_id.clone()] + ); + assert!( + fixture + .client() + .data_list(history_list(Some(category_selector.clone()))) + .await + .unwrap() + .into_inner() + .records + .is_empty() + ); + // The same logical key in another plugin's namespace is not addressable. + let hidden = fixture + .client() + .storage_get(StorageGetRequest { + context: Some(fixture.context()), + key: "catalog-notes".into(), + }) + .await + .unwrap() + .into_inner(); + assert!(!hidden.found); + + // Review the common category and the exact custom dataset pair separately. + fixture + .shared_policies + .set_activation_grants( + &recipient, + ActivationReadGrant::new([CATEGORY], std::iter::empty::()).unwrap(), + ) + .unwrap(); + grant_durable_dataset_fields( + &fixture, + &source, + &recipient, + CATALOG, + ["title".into()], + true, + true, + ); + + // The durable common row is included only when its category is selected, and a query for + // another dataset does not widen to it. + assert!( + fixture + .client() + .data_list(history_list(None)) + .await + .unwrap() + .into_inner() + .records + .is_empty() + ); + assert_eq!( + record_ids( + fixture + .client() + .data_list(history_list(Some(category_selector.clone()))) + .await + .unwrap() + .into_inner() + ), + vec![history.clone()] + ); + let mut other_dataset = list_request(&fixture.context(), "org.example.metrics.v1"); + other_dataset.common_data_categories = Some(category_selector.clone()); + assert!( + fixture + .client() + .data_list(other_dataset) + .await + .unwrap() + .into_inner() + .records + .is_empty(), + "the category grant stays scoped to the queried dataset" + ); + + // The reviewed dataset projection returns both rows, with only the granted field of the + // producer's record. + let listed = fixture + .client() + .data_list(list_request(&fixture.context(), CATALOG)) + .await + .unwrap() + .into_inner(); + let ids: Vec<_> = listed + .records + .iter() + .map(|record| record.record_id.clone()) + .collect(); + assert!(ids.contains(&published.record_id) && ids.contains(&own.record_id)); + let projected = listed + .records + .iter() + .find(|record| record.record_id == published.record_id) + .unwrap(); + assert_eq!(projected.value, Some(value(&[("title", text("Dolphin"))]))); + + let now_ms = unix_now().unwrap() * 1000; + let reported = producer + .host + .resource_client() + .game_performance_publish_samples(super::performance::request_for( + &producer_context, + "performance-producer", + 0, + vec![super::performance::sample(1, now_ms - 100, 59.0)], + )) + .await + .unwrap() + .into_inner(); + assert_eq!(reported.accepted_samples, 1); + + // The write belongs to the host-selected game: another game is refused, not relabelled. + let mut wrong_game = super::performance::request_for( + &producer_context, + "performance-wrong-game", + 0, + vec![super::performance::sample(1, now_ms, 60.0)], + ); + wrong_game.game_id = "6".into(); + let denied = producer + .host + .resource_client() + .game_performance_publish_samples(wrong_game) + .await + .unwrap_err(); + assert_eq!(denied.code(), Code::PermissionDenied); + + // A grant makes records eligible; it never triggers or includes a query by itself. + assert!( + performance + .list(performance_list("5", None)) + .await + .unwrap() + .into_inner() + .series + .is_empty() + ); + let included = performance + .list(performance_list("5", Some(category_selector.clone()))) + .await + .unwrap() + .into_inner(); + assert_eq!(included.series.len(), 1); + assert_eq!(included.series[0].series_id, reported.report_id); + assert_eq!(included.series[0].installation_id, "steam:five"); + assert_eq!(included.series[0].samples.len(), 1); + assert!( + performance + .list(performance_list("6", Some(category_selector.clone()))) + .await + .unwrap() + .into_inner() + .series + .is_empty(), + "no series leaks to another game" + ); + assert_eq!( + performance + .list(performance_list("", Some(category_selector.clone()))) + .await + .unwrap() + .into_inner() + .series + .len(), + 1, + "even an unscoped query only returns the granted game" + ); + + drop(producer); + // Session-retained history ends with the producer session; durable rows survive. + assert!( + performance + .list(performance_list("5", Some(category_selector.clone()))) + .await + .unwrap() + .into_inner() + .series + .is_empty() + ); + + // The consumer reads the producer's durable records after the producer session stopped. + let fetched = fixture + .client() + .data_get(DataGetRequest { + context: Some(fixture.context()), + dataset_id: CATALOG.into(), + record_id: published.record_id.clone(), + ..Default::default() + }) + .await + .unwrap() + .into_inner() + .record + .unwrap(); + assert_eq!(fetched.value, Some(value(&[("title", text("Dolphin"))]))); + assert_eq!(fetched.publisher_id, "org.example.producer"); + assert_eq!(fetched.durability, StorageDurability::Persistent as i32); + + // A real host restart starts a fresh broker over the same pool file. + let broker = Arc::new(DataBroker::new()); + assert_eq!(broker.revision(), 0); + let (mut restarted, server) = local_client(restarted_service(&fixture, broker.clone())).await; + let listed = restarted + .data_list(list_request(&fixture.context(), CATALOG)) + .await + .unwrap() + .into_inner(); + let ids: Vec<_> = listed + .records + .iter() + .map(|record| record.record_id.clone()) + .collect(); + assert!(ids.contains(&published.record_id) && ids.contains(&own.record_id)); + assert_eq!( + listed.records[0].durability, + StorageDurability::Persistent as i32 + ); + assert_eq!( + record_ids( + restarted + .data_list(history_list(Some(category_selector.clone()))) + .await + .unwrap() + .into_inner() + ), + vec![history.clone()] + ); + + // Uninstall with Keep archives the producer's two durable rows (the same primitive the + // lifecycle applies before removing the package). Archived rows are inert for every ordinary + // read, including the standing category grant. + let now = unix_seconds(); + let archived = fixture + .shared_pool + .archive_owner(producer_owner, now) + .await + .unwrap() + .unwrap(); + assert_eq!(archived.records, 2); + assert_eq!( + record_ids( + fixture + .client() + .data_list(list_request(&fixture.context(), CATALOG)) + .await + .unwrap() + .into_inner() + ), + vec![own.record_id.clone()] + ); + assert!( + fixture + .client() + .data_list(history_list(Some(category_selector.clone()))) + .await + .unwrap() + .into_inner() + .records + .is_empty(), + "an archived common row is not readable even under the current category grant" + ); + let mut archived_get = DataGetRequest { + context: Some(fixture.context()), + dataset_id: HISTORY.into(), + record_id: history.clone(), + ..Default::default() + }; + archived_get.common_data_categories = Some(category_selector.clone()); + assert_eq!( + fixture + .client() + .data_get(archived_get) + .await + .unwrap_err() + .code(), + Code::NotFound + ); + + // The separate host review restores them; the same category grant reads them again without a + // new per-record review. + let reused = fixture + .shared_pool + .reuse_archived_owner(producer_owner, now) + .await + .unwrap() + .unwrap(); + assert_eq!(reused.records, 2); + assert_eq!( + record_ids( + fixture + .client() + .data_list(history_list(Some(category_selector.clone()))) + .await + .unwrap() + .into_inner() + ), + vec![history.clone()] + ); + assert_eq!( + record_ids( + fixture + .client() + .data_list(list_request(&fixture.context(), CATALOG)) + .await + .unwrap() + .into_inner() + ) + .len(), + 2 + ); + + // Revoking the custom dataset grant fences that row while the independently granted common + // category remains available. + let snapshot = fixture + .shared_policies + .recipient_snapshot(&recipient) + .unwrap(); + fixture + .shared_policies + .replace_recipient_policies( + &recipient, + snapshot.revision, + ActivationReadGrant::new(snapshot.categories, snapshot.selected_record_ids).unwrap(), + vec![], + ) + .unwrap(); + let error = fixture + .client() + .data_get(DataGetRequest { + context: Some(fixture.context()), + dataset_id: CATALOG.into(), + record_id: published.record_id.clone(), + ..Default::default() + }) + .await + .unwrap_err(); + assert_eq!(error.code(), Code::NotFound); + assert_eq!( + record_ids( + fixture + .client() + .data_list(list_request(&fixture.context(), CATALOG)) + .await + .unwrap() + .into_inner() + ), + vec![own.record_id.clone()], + "only the consumer's own row remains visible" + ); + assert_eq!( + record_ids( + fixture + .client() + .data_list(history_list(Some(category_selector.clone()))) + .await + .unwrap() + .into_inner() + ), + vec![history.clone()], + "revoking a custom pair does not touch the common category grant" + ); + + // Private cleanup is namespace-scoped: clearing the consumer's own persistence changes no + // public-pool row. A host-wide cleanup across owners stays a reviewed host command (task + // 1.17); no plugin RPC accepts an owner or another plugin's namespace. + let cleared = fixture + .client() + .persistence_clear(PersistenceClearRequest { + mutation: Some(MutationContext { + context: Some(fixture.context()), + idempotency_key: "clear-private".into(), + expected_revision: 0, + ..Default::default() + }), + category: "private".into(), + }) + .await + .unwrap() + .into_inner(); + assert_eq!(cleared.outcome, MutationOutcome::AlreadyApplied as i32); + assert_eq!( + fixture + .shared_pool + .usage(producer_owner, now) + .await + .unwrap() + .unwrap() + .records, + 2, + "a private cleanup never reaches another owner's public rows" + ); + let hidden = fixture + .client() + .storage_get(StorageGetRequest { + context: Some(fixture.context()), + key: "catalog-notes".into(), + }) + .await + .unwrap() + .into_inner(); + assert!( + !hidden.found, + "private namespaces never follow a pool cleanup" + ); + // Own cleanup reclaims exactly one owner. The consumer's deletion leaves the producer's rows + // and private namespace alone; only the producer's own deletion removes them. + let deleted = fixture + .shared_pool + .delete_owner(own_owner, now) + .await + .unwrap() + .unwrap(); + assert_eq!(deleted.removed_records, 1); + assert_eq!( + fixture + .shared_pool + .usage(producer_owner, now) + .await + .unwrap() + .unwrap() + .records, + 2 + ); + assert_eq!( + record_ids( + fixture + .client() + .data_list(history_list(Some(category_selector.clone()))) + .await + .unwrap() + .into_inner() + ), + vec![history.clone()] + ); + let deleted = fixture + .shared_pool + .delete_owner(producer_owner, now) + .await + .unwrap() + .unwrap(); + assert_eq!(deleted.removed_records, 2); + let store = SharedDataStore::open(&fixture.data_dir).unwrap(); + assert!(store.get_any(&published.record_id, now).unwrap().is_none()); + assert!(store.get_any(&history, now).unwrap().is_none()); + assert_eq!( + fixture + .shared_pool + .usage(own_owner, now) + .await + .unwrap() + .unwrap() + .records, + 0 + ); + assert_eq!( + fixture + .shared_pool + .delete_owner(producer_owner, now) + .await + .unwrap() + .unwrap() + .removed_records, + 0 + ); + + server.abort(); +} +/// A session-only publication from one producer session in the metrics dataset. +fn session_request( + context: &ServiceContext, + key: &str, + resource_id: &str, + fps: f64, +) -> DataPublishRequest { + DataPublishRequest { + mutation: Some(MutationContext { + context: Some(context.clone()), + idempotency_key: key.into(), + ..Default::default() + }), + dataset_id: "org.example.metrics.v1".into(), + schema_id: "org.example.metrics.v1".into(), + schema_version: 1, + value: Some(value(&[("fps", number(fps))])), + durability: StorageDurability::SessionOnly as i32, + ttl_seconds: 300, + resource_id: resource_id.into(), + observed_at: 1_700_000_000, + sequence: 1, + source_observation_id: key.into(), + ..Default::default() + } +} + +#[tokio::test] +async fn consumer_reads_a_durable_record_while_the_producer_is_stopped() { + let fixture = Fixture::new(&[]).await; + let producer = + consumer_session_with_grants(&fixture, &[cap::DATA_PUBLISH, cap::STORAGE_PERSIST]).await; + let producer_context = producer.host.resource_context().unwrap().clone(); + let source = authenticated_identity(&fixture, &producer_context); + let recipient = authenticated_identity(&fixture, &fixture.context()); + grant_durable_dataset(&fixture, &source, &recipient, true, true); + + let published = producer + .host + .resource_client() + .data_publish(durable_request( + &producer_context, + "durable-offline-read", + "runtime-primary", + 60.0, + )) + .await + .unwrap() + .into_inner(); + assert_eq!(published.durability, StorageDurability::Persistent as i32); + drop(producer); + + // The consumer's broker never retained the durable row: a fresh read can only come from the + // pool, with the producer's session gone. + let fetched = fixture + .client() + .data_get(DataGetRequest { + context: Some(fixture.context()), + dataset_id: "org.example.metrics.v1".into(), + record_id: published.record_id.clone(), + ..Default::default() + }) + .await + .unwrap() + .into_inner() + .record + .unwrap(); + assert_eq!(fetched.record_id, published.record_id); + assert_eq!(fetched.revision, published.revision); + assert_eq!( + fetched.durability, + StorageDurability::Persistent as i32, + "the merged record reports its stored mode" + ); + assert_eq!(fetched.value, Some(value(&[("fps", number(60.0))]))); + assert_eq!(fetched.publisher_id, "org.example.consumer"); + assert_eq!(fetched.resource_id, "runtime-primary"); + assert!(fetched.expires_at > 0); + let provenance = fetched.provenance.unwrap(); + assert_eq!(provenance.producer_plugin_id, "org.example.consumer"); + assert_eq!(provenance.publisher_fingerprint, "cd".repeat(32)); + assert_eq!(provenance.resource_id, "runtime-primary"); + + let listed = fixture + .client() + .data_list(list_request(&fixture.context(), "org.example.metrics.v1")) + .await + .unwrap() + .into_inner(); + assert_eq!(listed.records.len(), 1); + assert_eq!(listed.records[0].record_id, published.record_id); + assert_eq!( + listed.records[0].durability, + StorageDurability::Persistent as i32 + ); +} + +#[tokio::test] +async fn list_pages_session_and_durable_records_in_one_stable_order() { + let fixture = Fixture::new(&[]).await; + let producer = + consumer_session_with_grants(&fixture, &[cap::DATA_PUBLISH, cap::STORAGE_PERSIST]).await; + let producer_context = producer.host.resource_context().unwrap().clone(); + let source = authenticated_identity(&fixture, &producer_context); + let recipient = authenticated_identity(&fixture, &fixture.context()); + grant_durable_dataset(&fixture, &source, &recipient, true, true); + + let mut producer_rpc = producer.host.resource_client(); + let durable = producer_rpc + .data_publish(durable_request( + &producer_context, + "durable-page", + "runtime-durable", + 60.0, + )) + .await + .unwrap() + .into_inner(); + let session = producer_rpc + .data_publish(session_request( + &producer_context, + "session-page", + "runtime-session", + 61.0, + )) + .await + .unwrap() + .into_inner(); + + let mut page = list_request(&fixture.context(), "org.example.metrics.v1"); + page.page.as_mut().unwrap().page_size = 1; + let mut seen = Vec::new(); + let mut expect_more = true; + while expect_more { + let reply = fixture + .client() + .data_list(page.clone()) + .await + .unwrap() + .into_inner(); + assert_eq!(reply.records.len(), 1); + seen.push(reply.records[0].clone()); + expect_more = !reply.next_cursor.is_empty(); + page.page.as_mut().unwrap().cursor = reply.next_cursor; + } + assert_eq!(seen.len(), 2, "one page per record across both sources"); + let ids: Vec<_> = seen.iter().map(|record| record.record_id.clone()).collect(); + assert!(ids.contains(&durable.record_id) && ids.contains(&session.record_id)); + assert!( + (seen[0].received_at, &seen[0].record_id) <= (seen[1].received_at, &seen[1].record_id), + "pages follow the merged receipt order" + ); + let mode = |id: &str| { + seen.iter() + .find(|record| record.record_id == id) + .unwrap() + .durability + }; + assert_eq!( + mode(&durable.record_id), + StorageDurability::Persistent as i32 + ); + assert_eq!( + mode(&session.record_id), + StorageDurability::SessionOnly as i32 + ); +} + +#[tokio::test] +async fn consumer_without_a_grant_sees_neither_session_nor_durable_records() { + let fixture = Fixture::new(&[]).await; + let producer = + consumer_session_with_grants(&fixture, &[cap::DATA_PUBLISH, cap::STORAGE_PERSIST]).await; + let producer_context = producer.host.resource_context().unwrap().clone(); + let mut producer_rpc = producer.host.resource_client(); + + let durable = producer_rpc + .data_publish(durable_request( + &producer_context, + "denied-durable", + "runtime-durable", + 60.0, + )) + .await + .unwrap() + .into_inner(); + let session = producer_rpc + .data_publish(session_request( + &producer_context, + "denied-session", + "runtime-session", + 61.0, + )) + .await + .unwrap() + .into_inner(); + + let listed = fixture + .client() + .data_list(list_request(&fixture.context(), "org.example.metrics.v1")) + .await + .unwrap() + .into_inner(); + assert!( + listed.records.is_empty(), + "no owner-private or granted record is visible without a policy" + ); + for record_id in [durable.record_id, session.record_id] { + let error = fixture + .client() + .data_get(DataGetRequest { + context: Some(fixture.context()), + dataset_id: "org.example.metrics.v1".into(), + record_id, + ..Default::default() + }) + .await + .unwrap_err(); + assert_eq!(error.code(), Code::NotFound); + } +} + +#[tokio::test] +async fn revocation_fences_durable_reads_and_queued_watch_events_immediately() { + use futures_util::StreamExt; + + let fixture = Fixture::new(&[]).await; + let producer = + consumer_session_with_grants(&fixture, &[cap::DATA_PUBLISH, cap::STORAGE_PERSIST]).await; + let producer_context = producer.host.resource_context().unwrap().clone(); + let source = authenticated_identity(&fixture, &producer_context); + let recipient = authenticated_identity(&fixture, &fixture.context()); + grant_durable_dataset(&fixture, &source, &recipient, true, true); + + let mut producer_rpc = producer.host.resource_client(); + let first = producer_rpc + .data_publish(durable_request( + &producer_context, + "revocation-first", + "runtime-primary", + 60.0, + )) + .await + .unwrap() + .into_inner(); + let listed = fixture + .client() + .data_list(list_request(&fixture.context(), "org.example.metrics.v1")) + .await + .unwrap() + .into_inner(); + assert_eq!(listed.records.len(), 1); + let mut watch = fixture + .client() + .data_watch(DataWatchRequest { + context: Some(fixture.context()), + dataset_id: "org.example.metrics.v1".into(), + after_revision: listed.revision, + ..Default::default() + }) + .await + .unwrap() + .into_inner(); + + let revision = fixture + .shared_policies + .recipient_snapshot(&recipient) + .unwrap() + .revision; + fixture + .shared_policies + .replace_recipient_policies(&recipient, revision, ActivationReadGrant::default(), vec![]) + .unwrap(); + + // The producer replaces the durable record after revocation. The queued watch must be fenced + // rather than deliver the new revision. + producer_rpc + .data_publish(durable_request( + &producer_context, + "revocation-second", + "runtime-primary", + 75.0, + )) + .await + .unwrap(); + let error = tokio::time::timeout(Duration::from_secs(2), watch.next()) + .await + .unwrap() + .unwrap() + .unwrap_err(); + assert_eq!(error.code(), Code::FailedPrecondition); + + let listed = fixture + .client() + .data_list(list_request(&fixture.context(), "org.example.metrics.v1")) + .await + .unwrap() + .into_inner(); + assert!( + listed.records.is_empty(), + "revocation fences the durable list" + ); + let error = fixture + .client() + .data_get(DataGetRequest { + context: Some(fixture.context()), + dataset_id: "org.example.metrics.v1".into(), + record_id: first.record_id, + ..Default::default() + }) + .await + .unwrap_err(); + assert_eq!(error.code(), Code::NotFound); +} + +#[tokio::test] +async fn owner_reads_own_durable_record_without_a_selector() { + let fixture = Fixture::new(&[cap::DATA_PUBLISH, cap::STORAGE_PERSIST]).await; + let owner_context = fixture.context(); + let durable = fixture + .client() + .data_publish(durable_request( + &owner_context, + "owner-durable", + "runtime-primary", + 60.0, + )) + .await + .unwrap() + .into_inner(); + assert!( + fixture + .data_broker + .sharing_catalog(unix_seconds()) + .is_empty(), + "the durable publication is never retained in session memory" + ); + + let listed = fixture + .client() + .data_list(list_request(&owner_context, "org.example.metrics.v1")) + .await + .unwrap() + .into_inner(); + assert_eq!(listed.records.len(), 1); + assert_eq!(listed.records[0].record_id, durable.record_id); + assert_eq!( + listed.records[0].value, + Some(value(&[("fps", number(60.0))])) + ); + assert_eq!( + listed.records[0].durability, + StorageDurability::Persistent as i32 + ); + + let fetched = fixture + .client() + .data_get(DataGetRequest { + context: Some(owner_context), + dataset_id: "org.example.metrics.v1".into(), + record_id: durable.record_id, + ..Default::default() + }) + .await + .unwrap() + .into_inner() + .record + .unwrap(); + assert_eq!(fetched.value, Some(value(&[("fps", number(60.0))]))); +} + +#[tokio::test] +async fn durable_watch_reports_replacements_without_replaying_old_revisions() { + use futures_util::StreamExt; + + let fixture = Fixture::new(&[]).await; + let producer = + consumer_session_with_grants(&fixture, &[cap::DATA_PUBLISH, cap::STORAGE_PERSIST]).await; + let producer_context = producer.host.resource_context().unwrap().clone(); + let source = authenticated_identity(&fixture, &producer_context); + let recipient = authenticated_identity(&fixture, &fixture.context()); + grant_durable_dataset(&fixture, &source, &recipient, true, true); + + let mut producer_rpc = producer.host.resource_client(); + let first = producer_rpc + .data_publish(durable_request( + &producer_context, + "watch-first", + "runtime-primary", + 60.0, + )) + .await + .unwrap() + .into_inner(); + let listed = fixture + .client() + .data_list(list_request(&fixture.context(), "org.example.metrics.v1")) + .await + .unwrap() + .into_inner(); + assert_eq!(listed.records.len(), 1); + assert!(listed.revision >= first.revision); + let mut watch = fixture + .client() + .data_watch(DataWatchRequest { + context: Some(fixture.context()), + dataset_id: "org.example.metrics.v1".into(), + after_revision: listed.revision, + ..Default::default() + }) + .await + .unwrap() + .into_inner(); + assert!( + tokio::time::timeout(Duration::ZERO, watch.next()) + .await + .is_err(), + "a watch never replays an already listed durable record" + ); + + // The producer replaces the same resource: the pool advances its sequence and revision, and + // the stable record id reaches the watcher with the new value. + let replaced = producer_rpc + .data_publish(durable_request( + &producer_context, + "watch-second", + "runtime-primary", + 75.0, + )) + .await + .unwrap() + .into_inner(); + assert_eq!(replaced.record_id, first.record_id); + assert!(replaced.revision > first.revision); + let event = tokio::time::timeout(Duration::from_secs(2), watch.next()) + .await + .unwrap() + .unwrap() + .unwrap(); + assert_eq!(event.event_type, "published"); + assert_eq!(event.revision, replaced.revision); + let record = event.record.unwrap(); + assert_eq!(record.record_id, replaced.record_id); + assert_eq!(record.value, Some(value(&[("fps", number(75.0))]))); + assert_eq!(record.durability, StorageDurability::Persistent as i32); + + let store = SharedDataStore::open(&fixture.data_dir).unwrap(); + let pool_revision = store.pool_revision().unwrap(); + assert_eq!( + pool_revision, 2, + "the pool sequence advanced for the publication and its replacement" + ); + + // A watch opened from the fresh list revision starts live-only and never replays the record. + let listed = fixture + .client() + .data_list(list_request(&fixture.context(), "org.example.metrics.v1")) + .await + .unwrap() + .into_inner(); + let mut fresh = fixture + .client() + .data_watch(DataWatchRequest { + context: Some(fixture.context()), + dataset_id: "org.example.metrics.v1".into(), + after_revision: listed.revision, + ..Default::default() + }) + .await + .unwrap() + .into_inner(); + assert!( + tokio::time::timeout(Duration::ZERO, fresh.next()) + .await + .is_err(), + "restarting a watch does not replay durable rows" + ); +} + +#[tokio::test] +async fn durable_list_revision_hands_off_to_watch_after_a_real_host_restart() { + use futures_util::StreamExt; + + let fixture = Fixture::new(&[]).await; + let producer = + consumer_session_with_grants(&fixture, &[cap::DATA_PUBLISH, cap::STORAGE_PERSIST]).await; + let producer_context = producer.host.resource_context().unwrap().clone(); + let source = authenticated_identity(&fixture, &producer_context); + let recipient = authenticated_identity(&fixture, &fixture.context()); + grant_durable_dataset(&fixture, &source, &recipient, true, true); + + let mut producer_rpc = producer.host.resource_client(); + let first = producer_rpc + .data_publish(durable_request( + &producer_context, + "restart-first", + "runtime-first", + 60.0, + )) + .await + .unwrap() + .into_inner(); + let second = producer_rpc + .data_publish(durable_request( + &producer_context, + "restart-second", + "runtime-second", + 61.0, + )) + .await + .unwrap() + .into_inner(); + fixture.api.disconnect("consumer").await; + drop(producer); + + // The pool kept a sequence across the producer session; the reopened store must agree. + let persisted = SharedDataStore::open(&fixture.data_dir) + .unwrap() + .pool_revision() + .unwrap(); + assert_eq!(persisted, 2, "two durable publications advanced the pool"); + + // Restart: the in-memory broker is empty while the pool kept its sequence. + let broker = Arc::new(DataBroker::new()); + assert_eq!(broker.revision(), 0); + let (mut client, server) = local_client(restarted_service(&fixture, broker.clone())).await; + + let listed = client + .data_list(list_request(&fixture.context(), "org.example.metrics.v1")) + .await + .unwrap() + .into_inner(); + assert_eq!(listed.records.len(), 2); + let ids: Vec<_> = listed + .records + .iter() + .map(|record| record.record_id.clone()) + .collect(); + assert!(ids.contains(&first.record_id) && ids.contains(&second.record_id)); + assert_eq!( + listed.revision, persisted, + "the list resumes the persisted pool sequence instead of zero" + ); + assert_eq!(broker.revision(), persisted); + + // The revision the restarted list returned is a valid watch position, with no replay. + let mut watch = client + .data_watch(DataWatchRequest { + context: Some(fixture.context()), + dataset_id: "org.example.metrics.v1".into(), + after_revision: listed.revision, + ..Default::default() + }) + .await + .unwrap() + .into_inner(); + assert!( + tokio::time::timeout(Duration::ZERO, watch.next()) + .await + .is_err(), + "a post-restart handoff starts live-only" + ); + server.abort(); +} + +#[tokio::test] +async fn stale_watch_position_and_cursor_are_rejected_after_a_real_host_restart() { + let fixture = Fixture::new(&[]).await; + let producer = + consumer_session_with_grants(&fixture, &[cap::DATA_PUBLISH, cap::STORAGE_PERSIST]).await; + let producer_context = producer.host.resource_context().unwrap().clone(); + let source = authenticated_identity(&fixture, &producer_context); + let recipient = authenticated_identity(&fixture, &fixture.context()); + grant_durable_dataset(&fixture, &source, &recipient, true, true); + let mut producer_rpc = producer.host.resource_client(); + + let first = producer_rpc + .data_publish(durable_request( + &producer_context, + "stale-first", + "runtime-first", + 60.0, + )) + .await + .unwrap() + .into_inner(); + producer_rpc + .data_publish(durable_request( + &producer_context, + "stale-second", + "runtime-second", + 61.0, + )) + .await + .unwrap(); + // A first page at pool revision 2 yields both a cursor and a watch position. + let mut page = list_request(&fixture.context(), "org.example.metrics.v1"); + page.page.as_mut().unwrap().page_size = 1; + let first_page = fixture + .client() + .data_list(page.clone()) + .await + .unwrap() + .into_inner(); + assert_eq!(first_page.records[0].record_id, first.record_id); + assert_eq!(first_page.revision, 2); + assert!(!first_page.next_cursor.is_empty()); + + // A later durable publication moves the persisted sequence past both positions. + producer_rpc + .data_publish(durable_request( + &producer_context, + "stale-third", + "runtime-third", + 62.0, + )) + .await + .unwrap(); + fixture.api.disconnect("consumer").await; + drop(producer); + + let broker = Arc::new(DataBroker::new()); + let (mut client, server) = local_client(restarted_service(&fixture, broker.clone())).await; + + // The watch position predates the persisted sequence: resume is refused, not skipped. + let error = client + .data_watch(DataWatchRequest { + context: Some(fixture.context()), + dataset_id: "org.example.metrics.v1".into(), + after_revision: first_page.revision, + ..Default::default() + }) + .await + .unwrap_err(); + assert_eq!(error.code(), Code::FailedPrecondition); + + // The in-process cursor did not survive the restart and cannot silently skip records. + let mut stale = page.clone(); + stale.page.as_mut().unwrap().cursor = first_page.next_cursor.clone(); + let error = client.data_list(stale).await.unwrap_err(); + assert_eq!(error.code(), Code::FailedPrecondition); + assert!( + error.message().contains("cursor is stale"), + "unexpected message: {}", + error.message() + ); + + // A fresh list re-anchors at the persisted sequence and pages every record. + let listed = client + .data_list(list_request(&fixture.context(), "org.example.metrics.v1")) + .await + .unwrap() + .into_inner(); + assert_eq!(listed.records.len(), 3); + assert_eq!(listed.revision, 3); + server.abort(); +} + +#[tokio::test] +async fn revocation_fences_durable_reads_and_watch_with_the_producer_stopped() { + use futures_util::StreamExt; + + let fixture = Fixture::new(&[]).await; + let producer = + consumer_session_with_grants(&fixture, &[cap::DATA_PUBLISH, cap::STORAGE_PERSIST]).await; + let producer_context = producer.host.resource_context().unwrap().clone(); + let source = authenticated_identity(&fixture, &producer_context); + let recipient = authenticated_identity(&fixture, &fixture.context()); + grant_durable_dataset(&fixture, &source, &recipient, true, true); + + let published = producer + .host + .resource_client() + .data_publish(durable_request( + &producer_context, + "revoked-offline", + "runtime-primary", + 60.0, + )) + .await + .unwrap() + .into_inner(); + // The producer stops before the revocation: no publication or reconnection can fence us. + fixture.api.disconnect("consumer").await; + drop(producer); + + let listed = fixture + .client() + .data_list(list_request(&fixture.context(), "org.example.metrics.v1")) + .await + .unwrap() + .into_inner(); + assert_eq!(listed.records.len(), 1); + let mut watch = fixture + .client() + .data_watch(DataWatchRequest { + context: Some(fixture.context()), + dataset_id: "org.example.metrics.v1".into(), + after_revision: listed.revision, + ..Default::default() + }) + .await + .unwrap() + .into_inner(); + + let revision = fixture + .shared_policies + .recipient_snapshot(&recipient) + .unwrap() + .revision; + fixture + .shared_policies + .replace_recipient_policies(&recipient, revision, ActivationReadGrant::default(), vec![]) + .unwrap(); + + // Reads are fenced immediately, straight from the persisted row. + let listed = fixture + .client() + .data_list(list_request(&fixture.context(), "org.example.metrics.v1")) + .await + .unwrap() + .into_inner(); + assert!(listed.records.is_empty(), "revocation fences the list"); + let error = fixture + .client() + .data_get(DataGetRequest { + context: Some(fixture.context()), + dataset_id: "org.example.metrics.v1".into(), + record_id: published.record_id, + ..Default::default() + }) + .await + .unwrap_err(); + assert_eq!(error.code(), Code::NotFound); + + // The open watch ends at its next policy recheck without any producer event. + let error = tokio::time::timeout(Duration::from_secs(10), watch.next()) + .await + .unwrap() + .unwrap() + .unwrap_err(); + assert_eq!(error.code(), Code::FailedPrecondition); +} + +#[tokio::test] +async fn a_profile_change_fences_durable_reads_and_watch_with_the_producer_stopped() { + use futures_util::StreamExt; + + let mut fixture = Fixture::new(&[]).await; + let producer = + consumer_session_with_grants(&fixture, &[cap::DATA_PUBLISH, cap::STORAGE_PERSIST]).await; + let producer_context = producer.host.resource_context().unwrap().clone(); + let source = authenticated_identity(&fixture, &producer_context); + let recipient = authenticated_identity(&fixture, &fixture.context()); + grant_durable_dataset(&fixture, &source, &recipient, true, true); + + let published = producer + .host + .resource_client() + .data_publish(durable_request( + &producer_context, + "profile-durable", + "runtime-primary", + 60.0, + )) + .await + .unwrap() + .into_inner(); + fixture.api.disconnect("consumer").await; + drop(producer); + + let listed = fixture + .client() + .data_list(list_request(&fixture.context(), "org.example.metrics.v1")) + .await + .unwrap() + .into_inner(); + assert_eq!(listed.records.len(), 1); + let mut watch = fixture + .client() + .data_watch(DataWatchRequest { + context: Some(fixture.context()), + dataset_id: "org.example.metrics.v1".into(), + after_revision: listed.revision, + ..Default::default() + }) + .await + .unwrap() + .into_inner(); + let stale_context = fixture.context(); + + // Another account signs in. The producer stays stopped; the session and its watches are + // fenced while the durable row remains under the previous profile's owner. + fixture.api.profiles().update(Some("b"), true); + fixture.api.fence_third_party_sessions().await; + let error = tokio::time::timeout(Duration::from_secs(10), watch.next()) + .await + .unwrap() + .unwrap() + .unwrap_err(); + assert!( + matches!( + error.code(), + Code::FailedPrecondition | Code::Unauthenticated + ), + "the previous profile's watch must not deliver a record: {error:?}" + ); + let error = fixture + .client() + .data_list(list_request(&stale_context, "org.example.metrics.v1")) + .await + .unwrap_err(); + assert!( + matches!( + error.code(), + Code::FailedPrecondition | Code::Unauthenticated + ), + "a stale profile context must be fenced: {error:?}" + ); + + // Reconnecting into the new profile cannot reach the previous profile's durable record. + fixture.reconnect().await; + let listed = fixture + .client() + .data_list(list_request(&fixture.context(), "org.example.metrics.v1")) + .await + .unwrap() + .into_inner(); + assert!( + listed.records.is_empty(), + "another profile never sees this owner's durable row" + ); + let error = fixture + .client() + .data_get(DataGetRequest { + context: Some(fixture.context()), + dataset_id: "org.example.metrics.v1".into(), + record_id: published.record_id, + ..Default::default() + }) + .await + .unwrap_err(); + assert_eq!(error.code(), Code::NotFound); +} + +/// The sharing class of one host-written pool row. A common row always names its category. +#[derive(Clone, Copy)] +enum PoolRowClass { + Custom, + Common(CommonDataCategory), +} + +/// Writes one host-resolved durable row straight into the pool, standing in for a producer whose +/// session is gone or a host domain adapter that feeds Common records into the public pool. +fn write_pool_row( + fixture: &Fixture, + owner_key: [u8; 32], + source: &PluginIdentity, + dataset_id: &str, + class: PoolRowClass, + resource_id: &str, + fields_json: &str, +) -> String { + let (class, category) = match class { + PoolRowClass::Custom => (SharingClass::Custom, None), + PoolRowClass::Common(category) => (SharingClass::Common, Some(category)), + }; + let caller = fixture + .api + .authorize_resource_session(Some(&fixture.context())) + .unwrap(); + let owner = OwnerScope::new(owner_key, caller.profile_epoch).unwrap(); + let provenance = RecordProvenance { + source_plugin_id: source.plugin_id.clone(), + source_publisher_fingerprint: source.publisher_fingerprint.clone(), + source_profile_id: source.profile_id.clone(), + declared_developer: "Example Developer".into(), + origin: "signed-package".into(), + package_version: "1.0.0".into(), + package_digest: vec![9; 32], + }; + let now = unix_seconds(); + let mut store = SharedDataStore::open(&fixture.data_dir).unwrap(); + let outcome = store + .write( + owner, + RecordWrite { + dataset_id, + category: category.map(|category| category as i32), + class: class.as_name(), + schema_id: dataset_id, + schema_version: 1, + fields_json, + opaque_payload: &[], + resource_id: Some(resource_id), + observed_at: now, + sequence: 1, + source_observation_id: resource_id, + expires_at: None, + now, + provenance: &provenance, + expected_revision: None, + }, + ) + .unwrap(); + match outcome { + WriteOutcome::Stored(receipt) => receipt.record.record_id, + other => panic!("unexpected pool write outcome: {other:?}"), + } +} + +#[tokio::test] +async fn durable_custom_records_stay_private_until_their_dataset_grant_keeps_the_mask() { + let fixture = Fixture::new(&[]).await; + let producer = + consumer_session_with_grants(&fixture, &[cap::DATA_PUBLISH, cap::STORAGE_PERSIST]).await; + let producer_context = producer.host.resource_context().unwrap().clone(); + let source = authenticated_identity(&fixture, &producer_context); + let recipient = authenticated_identity(&fixture, &fixture.context()); + + let mut request = durable_request(&producer_context, "masked-durable", "runtime-primary", 60.0); + request.value = Some(value(&[ + ("fps", number(60.0)), + ("title", text("private title")), + ])); + let published = producer + .host + .resource_client() + .data_publish(request) + .await + .unwrap() + .into_inner(); + fixture.api.disconnect("consumer").await; + drop(producer); + + // Owner-private default: the row exists in the pool but is not disclosed. + let listed = fixture + .client() + .data_list(list_request(&fixture.context(), "org.example.metrics.v1")) + .await + .unwrap() + .into_inner(); + assert!(listed.records.is_empty(), "no grant, no durable row"); + let error = fixture + .client() + .data_get(DataGetRequest { + context: Some(fixture.context()), + dataset_id: "org.example.metrics.v1".into(), + record_id: published.record_id.clone(), + ..Default::default() + }) + .await + .unwrap_err(); + assert_eq!(error.code(), Code::NotFound); + + // A category/selected-record activation grant cannot authorize a Custom durable row, even + // when the request selects that category and record. + fixture + .shared_policies + .set_activation_grants( + &recipient, + ActivationReadGrant::new( + [CommonDataCategory::GamePerformanceHistory], + [published.record_id.clone()], + ) + .unwrap(), + ) + .unwrap(); + let mut selected = list_request(&fixture.context(), "org.example.metrics.v1"); + selected.common_data_categories = Some(CommonDataSelector { + categories: vec![CommonDataCategory::GamePerformanceHistory as i32], + selected_record_ids: vec![published.record_id.clone()], + }); + let listed = fixture + .client() + .data_list(selected.clone()) + .await + .unwrap() + .into_inner(); + assert!( + listed.records.is_empty(), + "a category or selected-record Common grant cannot widen a Custom durable projection" + ); + + // The reviewed dataset grant is the only authorization, and its field mask is enforced. + grant_durable_dataset(&fixture, &source, &recipient, true, true); + let listed = fixture + .client() + .data_list(selected.clone()) + .await + .unwrap() + .into_inner(); + assert_eq!(listed.records.len(), 1); + assert_eq!(listed.records[0].record_id, published.record_id); + assert_eq!( + listed.records[0].value, + Some(value(&[("fps", number(60.0))])), + "the ungranted title field stays hidden" + ); + assert_eq!( + listed.records[0].durability, + StorageDurability::Persistent as i32 + ); + + let mut get = DataGetRequest { + context: Some(fixture.context()), + dataset_id: "org.example.metrics.v1".into(), + record_id: published.record_id.clone(), + ..Default::default() + }; + get.common_data_categories = selected.common_data_categories.clone(); + let fetched = fixture + .client() + .data_get(get) + .await + .unwrap() + .into_inner() + .record + .unwrap(); + assert_eq!(fetched.value, Some(value(&[("fps", number(60.0))]))); + assert!( + !fetched.value.unwrap().fields.contains_key("title"), + "the merged get applies the same mask" + ); +} + +#[tokio::test] +async fn durable_common_rows_honour_selected_record_grants_through_the_merged_path() { + let fixture = Fixture::new(&[]).await; + let recipient = authenticated_identity(&fixture, &fixture.context()); + let source = PluginIdentity { + plugin_id: "org.example.adapter".into(), + publisher_fingerprint: "1234".repeat(8), + profile_id: recipient.profile_id.clone(), + }; + let category = CommonDataCategory::GamePerformanceHistory; + let granted = write_pool_row( + &fixture, + [0x21; 32], + &source, + "org.example.metrics.v1", + PoolRowClass::Common(category), + "runtime-granted", + r#"{"fps":60,"title":"catalog"}"#, + ); + let other = write_pool_row( + &fixture, + [0x21; 32], + &source, + "org.example.metrics.v1", + PoolRowClass::Common(category), + "runtime-other", + r#"{"fps":61,"title":"other"}"#, + ); + + let selector = CommonDataSelector { + categories: vec![category as i32], + selected_record_ids: vec![granted.clone(), other.clone()], + }; + let mut list = list_request(&fixture.context(), "org.example.metrics.v1"); + list.common_data_categories = Some(selector.clone()); + // Owner-private default: the durable Common rows are not disclosed without a grant. + assert!( + fixture + .client() + .data_list(list.clone()) + .await + .unwrap() + .into_inner() + .records + .is_empty() + ); + + // Review exactly one record; the category selection must not widen it to the other row. + fixture + .shared_policies + .set_activation_grants( + &recipient, + ActivationReadGrant::new(Vec::::new(), [granted.clone()]).unwrap(), + ) + .unwrap(); + let listed = fixture + .client() + .data_list(list.clone()) + .await + .unwrap() + .into_inner(); + assert_eq!(listed.records.len(), 1); + assert_eq!(listed.records[0].record_id, granted); + assert_eq!( + listed.records[0].value, + Some(value(&[("fps", number(60.0)), ("title", text("catalog")),])) + ); + assert_eq!( + listed.records[0].durability, + StorageDurability::Persistent as i32 + ); + + let mut denied = DataGetRequest { + context: Some(fixture.context()), + dataset_id: "org.example.metrics.v1".into(), + record_id: other, + ..Default::default() + }; + denied.common_data_categories = Some(selector); + let error = fixture.client().data_get(denied).await.unwrap_err(); + assert_eq!(error.code(), Code::NotFound); +} + +#[tokio::test] +async fn another_owners_durable_record_stays_private_through_the_merged_path() { + let fixture = Fixture::new(&[]).await; + let producer = + consumer_session_with_grants(&fixture, &[cap::DATA_PUBLISH, cap::STORAGE_PERSIST]).await; + let producer_context = producer.host.resource_context().unwrap().clone(); + let source = authenticated_identity(&fixture, &producer_context); + let recipient = authenticated_identity(&fixture, &fixture.context()); + grant_durable_dataset(&fixture, &source, &recipient, true, true); + + let mut request = durable_request(&producer_context, "granted-owner", "runtime-granted", 60.0); + request.value = Some(value(&[ + ("fps", number(60.0)), + ("title", text("private title")), + ])); + let published = producer + .host + .resource_client() + .data_publish(request) + .await + .unwrap() + .into_inner(); + // A second owner's durable row in the same dataset, written by the host pool itself. Its + // private namespace is never part of this projection. + let foreign = write_pool_row( + &fixture, + [0x31; 32], + &PluginIdentity { + plugin_id: "org.example.foreign".into(), + publisher_fingerprint: "ef".repeat(32), + profile_id: recipient.profile_id.clone(), + }, + "org.example.metrics.v1", + PoolRowClass::Custom, + "runtime-foreign", + r#"{"fps":99,"title":"foreign"}"#, + ); + fixture.api.disconnect("consumer").await; + drop(producer); + + // Both rows are in the pool; only the granted owner's row may cross the API. + let now = unix_seconds(); + let pool_rows = SharedDataStore::open(&fixture.data_dir) + .unwrap() + .list_dataset_any("org.example.metrics.v1", now) + .unwrap(); + assert_eq!(pool_rows.len(), 2); + assert!(pool_rows.iter().any(|row| row.record_id == foreign)); + + let listed = fixture + .client() + .data_list(list_request(&fixture.context(), "org.example.metrics.v1")) + .await + .unwrap() + .into_inner(); + assert_eq!(listed.records.len(), 1); + assert_eq!(listed.records[0].record_id, published.record_id); + assert_eq!( + listed.records[0].value, + Some(value(&[("fps", number(60.0))])), + "only the granted fields cross the projection" + ); + let provenance = listed.records[0].provenance.as_ref().unwrap(); + assert_eq!( + provenance.producer_plugin_id, "org.example.consumer", + "the record keeps its host-assigned owner, never the reader's" + ); + let field_names: Vec<_> = listed.records[0] + .value + .as_ref() + .unwrap() + .fields + .keys() + .cloned() + .collect(); + assert_eq!( + field_names, + ["fps"], + "no private storage path or ungranted field is reachable" + ); + + let error = fixture + .client() + .data_get(DataGetRequest { + context: Some(fixture.context()), + dataset_id: "org.example.metrics.v1".into(), + record_id: foreign, + ..Default::default() + }) + .await + .unwrap_err(); + assert_eq!(error.code(), Code::NotFound); +} + +#[tokio::test] +async fn a_previous_profile_cannot_reach_a_durable_record_even_when_selecting_it() { + let mut fixture = Fixture::new(&[]).await; + let producer = + consumer_session_with_grants(&fixture, &[cap::DATA_PUBLISH, cap::STORAGE_PERSIST]).await; + let producer_context = producer.host.resource_context().unwrap().clone(); + let source = authenticated_identity(&fixture, &producer_context); + let recipient = authenticated_identity(&fixture, &fixture.context()); + grant_durable_dataset(&fixture, &source, &recipient, true, true); + let published = producer + .host + .resource_client() + .data_publish(durable_request( + &producer_context, + "profile-scoped", + "runtime-primary", + 60.0, + )) + .await + .unwrap() + .into_inner(); + fixture.api.disconnect("consumer").await; + drop(producer); + + // Profile a can read it, even by exact record id. + let mut selected = list_request(&fixture.context(), "org.example.metrics.v1"); + selected.common_data_categories = Some(CommonDataSelector { + categories: vec![CommonDataCategory::GamePerformanceHistory as i32], + selected_record_ids: vec![published.record_id.clone()], + }); + let listed = fixture + .client() + .data_list(selected.clone()) + .await + .unwrap() + .into_inner(); + assert_eq!(listed.records.len(), 1); + + // Another account signs in and the plugin reconnects into profile b: the grant belonged to + // profile a and the durable owner is still profile a, so selecting the record changes nothing. + fixture.api.profiles().update(Some("b"), true); + fixture.api.fence_third_party_sessions().await; + fixture.reconnect().await; + let listed = fixture + .client() + .data_list(list_request(&fixture.context(), "org.example.metrics.v1")) + .await + .unwrap() + .into_inner(); + assert!( + listed.records.is_empty(), + "another profile never sees the durable row" + ); + selected.page.as_mut().unwrap().context = Some(fixture.context()); + let listed = fixture + .client() + .data_list(selected) + .await + .unwrap() + .into_inner(); + assert!( + listed.records.is_empty(), + "selecting the exact record id cannot cross profiles" + ); +} diff --git a/crates/app/src/plugin_host/resources/tests/declared_locations.rs b/crates/app/src/plugin_host/resources/tests/declared_locations.rs new file mode 100644 index 000000000..1b554fbc5 --- /dev/null +++ b/crates/app/src/plugin_host/resources/tests/declared_locations.rs @@ -0,0 +1,501 @@ +//! `FilesRequestAccess.declared_locations` over the real local socket (task 6.7): a plugin may +//! suggest where a game's saves or prefix usually are, and the suggestion is only ever shown to +//! the user, labelled as the plugin's. + +use gamenode_plugin_sdk::declared_location as declare; + +use super::*; +use crate::plugin_host::files::DeclaredFolder; + +const FILES: &[&str] = &[cap::FILES_READ, cap::FILES_WRITE, cap::FILES_DELETE]; + +fn text(path: &std::path::Path) -> String { + path.to_str().unwrap().to_owned() +} + +impl Fixture { + async fn ask_with( + &self, + installation: &str, + operations: &[&str], + kinds: &[&str], + declared: Vec, + ) -> Result { + self.client() + .files_request_access(FilesRequestAccessRequest { + mutation: Some(self.mutation("access", 0)), + game_id: String::new(), + installation_id: installation.into(), + requested_operations: operations.iter().map(|op| (*op).into()).collect(), + resource_kinds: kinds.iter().map(|kind| (*kind).into()).collect(), + declared_locations: declared, + }) + .await + .map(Response::into_inner) + } + + /// How the approval behind `handle` was made. + async fn origin_of(&self, handle: &str) -> String { + let id = self + .files + .open_handle(&self.context().session_id, handle) + .unwrap() + .0; + let caller = self.caller(); + self.storage + .run( + &caller, + |_| true, + move |namespace| Ok(namespace.approval(&id)?.unwrap().origin), + ) + .await + .unwrap() + } +} + +/// A library with one entry in `/games/one`, and a folder `/` per name given. +fn setup(fixture: &Fixture, folders: &[&str]) -> Vec { + let game = fixture.game_dir("one", &[("a.txt", b"a")]); + fixture.library_in(&[("fixture:1", Some(7), "One", &game)]); + folders + .iter() + .map(|name| { + let dir = fixture.base().join(name); + std::fs::create_dir_all(&dir).unwrap(); + dir + }) + .collect() +} + +#[tokio::test] +async fn a_declaration_alone_grants_nothing_and_leaves_no_trace() { + let fixture = Fixture::new(FILES).await; + let [saves] = setup(&fixture, &["saves"]).try_into().unwrap(); + let declared = || vec![declare("save", &text(&saves), "Saves")]; + + // No dialog in this build: nothing is approved. + assert_eq!( + fixture + .ask_with("id-fixture:1", &["read"], &["save"], declared()) + .await + .unwrap_err() + .code(), + Code::FailedPrecondition + ); + // The user declines: nothing is approved, and the next request asks again. + let user = fixture.user_approving(&saves); + user.consent.store(false, Ordering::SeqCst); + assert_eq!( + fixture + .ask_with("id-fixture:1", &["read"], &["save"], declared()) + .await + .unwrap_err() + .code(), + Code::PermissionDenied + ); + assert_eq!(user.asked(), 1); + // The folder was only ever shown to the user as a suggestion; declining left no approval. + let asked = user.asked.lock().unwrap()[0].clone(); + assert_eq!(asked.declared.len(), 1); + let [scope] = user.confirmed.lock().unwrap().clone().try_into().unwrap(); + assert!(scope.declared_by_plugin); + let caller = fixture.caller(); + let stored = fixture + .storage + .run( + &caller, + |_| true, + |namespace| namespace.approval_for("id-fixture:1", "save"), + ) + .await + .unwrap(); + assert_eq!(stored, None); + user.consent.store(true, Ordering::SeqCst); + fixture + .ask_with("id-fixture:1", &["read"], &["save"], declared()) + .await + .unwrap(); + assert_eq!(user.asked(), 2); +} + +#[tokio::test] +async fn suggestions_reach_the_user_in_the_plugins_order_labelled_with_the_first_existing_chosen() { + let fixture = Fixture::new(FILES).await; + let [first, second] = setup(&fixture, &["first", "second"]).try_into().unwrap(); + let missing = fixture.base().join("not-there"); + let user = fixture.user_approving(&second); + fixture + .ask_with( + "id-fixture:1", + &["read"], + &["save"], + vec![ + declare("save", &text(&missing), " Saves on the old path "), + declare("save", &text(&first), "Saves"), + declare("save", &text(&second), ""), + // The same folder again, written another way, and one of the other kind. + declare("save", &format!("{}/./", text(&first)), "again"), + declare("prefix", &text(&second), "Prefix"), + ], + ) + .await + .unwrap(); + let asked = user.asked.lock().unwrap()[0].clone(); + assert_eq!( + asked.declared, + [ + DeclaredFolder { + path: missing, + description: "Saves on the old path".into(), + exists: false + }, + DeclaredFolder { + path: first.clone(), + description: "Saves".into(), + exists: true + }, + DeclaredFolder { + path: second, + description: String::new(), + exists: true + }, + ] + ); + // Not the first listed, but the first that exists, and the host has no suggestion of its own. + assert_eq!(asked.preselected, Some(first)); + assert_eq!(asked.suggested, None); + assert_eq!(asked.kind, "save"); +} + +#[tokio::test] +async fn the_host_suggestion_for_an_installation_stays_first() { + let fixture = Fixture::new(FILES).await; + setup(&fixture, &[]); + let game = fixture.base().join("games").join("one"); + let user = fixture.user_approving(&game); + fixture + .ask_with("id-fixture:1", &["read"], &[], vec![]) + .await + .unwrap(); + let asked = user.asked.lock().unwrap()[0].clone(); + assert_eq!(asked.suggested.as_deref(), Some(game.as_path())); + assert_eq!(asked.preselected, Some(game)); + assert!(asked.declared.is_empty()); +} + +#[tokio::test] +async fn what_cannot_apply_here_or_is_private_to_the_host_is_dropped_without_an_error() { + let fixture = Fixture::new(FILES).await; + let [saves] = setup(&fixture, &["saves"]).try_into().unwrap(); + let user = fixture.user_approving(&saves); + let reply = fixture + .ask_with( + "id-fixture:1", + &["read"], + &["save"], + vec![ + declare("save", "{appdata}/Portal", "Windows"), + declare("save", "{localappdata}/Portal", "Windows"), + declare( + "save", + "C:\\Users\\ana\\Saved Games\\Portal", + "Windows drive", + ), + declare("save", "\\\\nas\\games\\portal", "Windows share"), + // The host's own data folder: never offered, never an error. + declare("save", &text(&fixture.plugin_data), "Private"), + declare( + "save", + &format!("{}/plugins", text(&fixture.plugin_data)), + "Private", + ), + declare("save", &text(&saves), "Saves"), + ], + ) + .await + .unwrap(); + assert_eq!(reply.handles.len(), 1); + let asked = user.asked.lock().unwrap()[0].clone(); + assert_eq!( + asked + .declared + .iter() + .map(|f| f.path.clone()) + .collect::>(), + [saves] + ); + // `{xdg_*}`, `{home}` and `{documents}` apply here; whether the folder exists is the user's + // dialog's concern, and none of them is an error. + fixture + .ask_with( + "id-fixture:1", + &["read"], + &["prefix"], + vec![ + declare("prefix", "{xdg_data}/Portal", "Linux data"), + declare("prefix", "{xdg_config}/Portal", "Linux config"), + declare("prefix", "{home}/Portal", "Home"), + declare("prefix", "{documents}/Portal", "Documents"), + ], + ) + .await + .unwrap(); +} + +#[tokio::test] +async fn a_malformed_declaration_is_refused_before_the_user_is_asked() { + let fixture = Fixture::new(FILES).await; + let [saves] = setup(&fixture, &["saves"]).try_into().unwrap(); + let user = fixture.user_approving(&saves); + let good = declare("save", &text(&saves), "Saves"); + let nine: Vec<_> = (0..9) + .map(|n| declare("save", &format!("/opt/games/{n}"), "")) + .collect(); + let long = format!("/{}", "a".repeat(1100)); + let cases: Vec<(&str, Vec)> = vec![ + ("unknown placeholder", vec![declare("save", "{nope}/x", "")]), + ("relative path", vec![declare("save", "saves/slot1", "")]), + ("tilde", vec![declare("save", "~/saves", "")]), + ("dot dot", vec![declare("save", "{home}/../etc", "")]), + ("dot dot literal", vec![declare("save", "/opt/../etc", "")]), + ("empty", vec![declare("save", "", "")]), + ("too long", vec![declare("save", &long, "")]), + ("control", vec![declare("save", "/opt/a\u{7}b", "")]), + ( + "installation kind", + vec![declare("installation", &text(&saves), "")], + ), + ("unknown kind", vec![declare("backup", &text(&saves), "")]), + ("empty kind", vec![declare("", &text(&saves), "")]), + ("nine for one kind", nine), + ( + "long description", + vec![declare("save", &text(&saves), &"x".repeat(121))], + ), + ( + "multi-line description", + vec![declare("save", &text(&saves), "a\nb")], + ), + ( + "control description", + vec![declare("save", &text(&saves), "a\u{7}")], + ), + ( + "bidi description", + vec![declare("save", &text(&saves), "a\u{202e}b")], + ), + ( + "a bad one among good ones", + vec![good.clone(), declare("save", "x", "")], + ), + ]; + for (name, declared) in cases { + let status = fixture + .ask_with("id-fixture:1", &["read"], &["save"], declared) + .await + .unwrap_err(); + assert_eq!(status.code(), Code::InvalidArgument, "{name}"); + // The message never repeats the location the plugin sent back as a path of ours. + assert!( + !status.message().contains("/home"), + "{name}: {}", + status.message() + ); + } + assert_eq!(user.asked(), 0); + + // Eight for each kind is the limit, not nine in total. + let eight: Vec<_> = (0..8) + .map(|n| declare("save", &format!("/opt/games/{n}"), "")) + .chain((0..8).map(|n| declare("prefix", &format!("/opt/prefix/{n}"), ""))) + .collect(); + fixture + .ask_with("id-fixture:1", &["read"], &["save"], eight) + .await + .unwrap(); +} + +#[tokio::test] +async fn the_approval_records_whether_the_plugin_suggested_the_folder() { + let fixture = Fixture::new(FILES).await; + let [suggested, other] = setup(&fixture, &["suggested", "other"]).try_into().unwrap(); + let user = fixture.user_approving(&suggested); + + // The user takes the plugin's suggestion; the confirmation still names the library games. + let taken = fixture + .ask_with( + "id-fixture:1", + &["read"], + &["save"], + vec![declare("save", &text(&suggested), "Saves")], + ) + .await + .unwrap(); + assert_eq!( + fixture.origin_of(&taken.handles[0].handle).await, + "declared" + ); + assert!(user.confirmed.lock().unwrap()[0].declared_by_plugin); + + // The user picks another folder for the prefix, though the plugin suggested the first. + *user.root.lock().unwrap() = Some(other.clone()); + let chosen = fixture + .ask_with( + "id-fixture:1", + &["read"], + &["prefix"], + vec![declare("prefix", &text(&suggested), "Prefix")], + ) + .await + .unwrap(); + assert_eq!(fixture.origin_of(&chosen.handles[0].handle).await, "user"); + assert!(!user.confirmed.lock().unwrap()[1].declared_by_plugin); + + // A suggestion that is a link to the folder the user chose is the same folder. + let link = fixture.base().join("link"); + std::os::unix::fs::symlink(&other, &link).unwrap(); + *user.root.lock().unwrap() = Some(link.clone()); + let reply = fixture + .ask_with( + "id-fixture:1", + &["read"], + &["save", "prefix"], + vec![declare("save", &text(&other), "Other")], + ) + .await + .unwrap(); + // The `save` approval already stands and is reused; `prefix` had no suggestion at all. + assert_eq!( + fixture.origin_of(&reply.handles[0].handle).await, + "declared" + ); + assert_eq!(fixture.origin_of(&reply.handles[1].handle).await, "user"); + + // Nothing but the kind and writability tells the plugin how it went. + assert_eq!( + reply + .handles + .iter() + .map(|h| (h.resource_kind.as_str(), h.writable)) + .collect::>(), + [("save", false), ("prefix", false)] + ); +} + +#[tokio::test] +async fn the_plugin_cannot_tell_which_suggestions_exist_or_were_shown() { + let describe = |reply: &FileAccessReply| -> Vec<(String, String, bool)> { + reply + .handles + .iter() + .map(|h| (h.display_name.clone(), h.resource_kind.clone(), h.writable)) + .collect() + }; + let mut answers = Vec::new(); + for suggestions in [0, 1, 2] { + let fixture = Fixture::new(FILES).await; + let [saves] = setup(&fixture, &["saves"]).try_into().unwrap(); + fixture.user_approving(&saves); + let declared = match suggestions { + 0 => vec![], + 1 => vec![declare("save", &text(&saves), "Saves")], + _ => vec![ + declare("save", "/definitely/not/there", "Nothing"), + declare("save", "{appdata}/X", "Windows"), + ], + }; + answers.push(describe( + &fixture + .ask_with("id-fixture:1", &["read"], &["save"], declared) + .await + .unwrap(), + )); + } + assert_eq!(answers[0], answers[1]); + assert_eq!(answers[1], answers[2]); +} + +#[tokio::test] +async fn a_read_only_approval_gives_no_write_and_widening_asks_the_user_again() { + let fixture = Fixture::new(FILES).await; + let [saves] = setup(&fixture, &["saves"]).try_into().unwrap(); + std::fs::write(saves.join("slot.sav"), b"s").unwrap(); + let user = fixture.user_approving(&saves); + let declared = || vec![declare("save", &text(&saves), "Saves")]; + + let read_only = fixture + .ask_with("id-fixture:1", &["read"], &["save"], declared()) + .await + .unwrap(); + let root = &read_only.handles[0]; + assert!(!root.writable); + assert_eq!(user.asked(), 1); + let denied = fixture + .write_to(&root.handle, "new.sav", b"x", 0, true, "w") + .await + .unwrap_err(); + assert_eq!(denied.code(), Code::PermissionDenied); + assert!(!saves.join("new.sav").exists()); + + // The same request again reuses the approval and the declared list is not looked at again. + fixture + .ask_with( + "id-fixture:1", + &["read"], + &["save"], + vec![declare("save", "/somewhere/else", "Other")], + ) + .await + .unwrap(); + assert_eq!(user.asked(), 1); + // ... but a list that is not well formed is refused even then. + assert_eq!( + fixture + .ask_with( + "id-fixture:1", + &["read"], + &["save"], + vec![declare("save", "relative", "")] + ) + .await + .unwrap_err() + .code(), + Code::InvalidArgument + ); + + // Widening to write asks the user again, with the suggestions shown again. + let widened = fixture + .ask_with("id-fixture:1", &["read", "write"], &["save"], declared()) + .await + .unwrap(); + assert_eq!(user.asked(), 2); + assert_eq!(user.asked.lock().unwrap()[1].declared.len(), 1); + assert!(widened.handles[0].writable); +} + +#[tokio::test] +async fn the_sdk_sends_the_declaration_the_raw_call_sends() { + let fixture = Fixture::new(FILES).await; + let [saves] = setup(&fixture, &["saves"]).try_into().unwrap(); + let user = fixture.user_approving(&saves); + let sdk = fixture.host.resources().unwrap(); + let handles = sdk + .files_request_access_with( + "id-fixture:1", + &["read"], + &["save"], + &[declare("save", &text(&saves), "Saves")], + "k", + ) + .await + .unwrap(); + assert_eq!(handles.len(), 1); + let asked = user.asked.lock().unwrap()[0].clone(); + assert_eq!(asked.declared.len(), 1); + assert_eq!(asked.declared[0].description, "Saves"); + // Without a declaration the old call still works and sends none. + sdk.files_request_access("id-fixture:1", &["read"], &["prefix"], "k2") + .await + .unwrap(); + assert!(user.asked.lock().unwrap()[1].declared.is_empty()); +} diff --git a/crates/app/src/plugin_host/resources/tests/diagnostics.rs b/crates/app/src/plugin_host/resources/tests/diagnostics.rs new file mode 100644 index 000000000..55411ca6b --- /dev/null +++ b/crates/app/src/plugin_host/resources/tests/diagnostics.rs @@ -0,0 +1,209 @@ +//! Public StorageDiagnostics RPC flow and permission fences. + +use super::*; +use std::time::{SystemTime, UNIX_EPOCH}; + +const GRANTS: &[&str] = &[ + cap::STORAGE_DIAGNOSTICS_PUBLISH, + cap::STORAGE_DIAGNOSTICS_READ, + cap::FILES_READ, +]; + +#[tokio::test] +async fn benchmark_report_is_host_volume_bound_and_retrievable_over_public_services() { + let fixture = Fixture::new(GRANTS).await; + let installation = fixture.game_dir("installed", &[]); + fixture.library_in(&[("fixture:1", Some(42), "Example game", &installation)]); + fixture.user_approving(&installation); + let handle = fixture + .request_access("id-fixture:1", &["read"], &[]) + .await + .unwrap() + .handles + .remove(0) + .handle; + let observed_at = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_secs() as i64; + let published = fixture + .client() + .storage_diagnostics_publish_benchmark(BenchmarkReportRequest { + mutation: Some(fixture.mutation("benchmark-report", 0)), + volume_handle: handle, + tool_name: "FixtureBench".into(), + tool_version: "2.1".into(), + measurements: std::collections::HashMap::from([("sequential_read".into(), 12_000.0)]), + units: "bytes_per_second".into(), + observed_at, + ..Default::default() + }) + .await + .unwrap() + .into_inner(); + assert!(!published.report_id.is_empty()); + + let mut diagnostics = fixture.host.storage_diagnostics_client(); + let listed = diagnostics + .list(DiagnosticListRequest { + page: Some(PageRequest { + context: Some(fixture.context()), + cursor: String::new(), + page_size: 10, + common_data_categories: None, + }), + owner_plugin_id: "fixture.plugin".into(), + volume_identity_token: String::new(), + projection_id: "benchmark.v1".into(), + }) + .await + .unwrap() + .into_inner(); + assert_eq!(listed.reports.len(), 1); + let report = &listed.reports[0]; + assert_eq!(report.report_id, published.report_id); + assert_eq!(report.report_kind, "benchmark"); + assert_eq!(report.owner_plugin_id, "fixture.plugin"); + assert!(!report.volume_identity_token.is_empty()); + assert_eq!(report.schema_id, "storage.diagnostics.benchmark.v1"); + let fields = report.typed_measurements.as_ref().unwrap(); + assert!(fields.fields.contains_key("measurements.sequential_read")); + assert!(!fields.fields.contains_key("volume_identity_token")); + + let fetched = diagnostics + .get(DiagnosticGetRequest { + context: Some(fixture.context()), + report_id: published.report_id, + projection_id: "benchmark.v1".into(), + }) + .await + .unwrap() + .into_inner(); + assert_eq!(fetched.report.unwrap().report_kind, "benchmark"); +} + +#[tokio::test] +async fn diagnostics_publish_and_read_require_separate_permissions() { + let fixture = Fixture::new(&[cap::FILES_READ]).await; + let status = fixture + .client() + .storage_diagnostics_publish_benchmark(BenchmarkReportRequest { + mutation: Some(fixture.mutation("denied-publish", 0)), + volume_handle: "not-resolved".into(), + tool_name: "FixtureBench".into(), + tool_version: "1".into(), + units: "bytes_per_second".into(), + measurements: std::collections::HashMap::from([("read".into(), 1.0)]), + observed_at: SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_secs() as i64, + ..Default::default() + }) + .await + .unwrap_err(); + assert_eq!(status.code(), tonic::Code::PermissionDenied); + + let mut diagnostics = fixture.host.storage_diagnostics_client(); + let status = diagnostics + .list(DiagnosticListRequest { + page: Some(PageRequest { + context: Some(fixture.context()), + cursor: String::new(), + page_size: 10, + common_data_categories: None, + }), + owner_plugin_id: String::new(), + volume_identity_token: String::new(), + projection_id: "benchmark.v1".into(), + }) + .await + .unwrap_err(); + assert_eq!(status.code(), tonic::Code::PermissionDenied); +} + +#[tokio::test] +async fn benchmark_report_flows_from_producer_to_consumer_with_reviewed_projection() { + use crate::plugin_host::sharing_policy::{SharingClass, SourceRecipientPolicy}; + + let fixture = Fixture::new(&[ + cap::STORAGE_DIAGNOSTICS_PUBLISH, + cap::STORAGE_DIAGNOSTICS_READ, + cap::FILES_READ, + ]) + .await; + let consumer = + super::data::consumer_session_with_grants(&fixture, &[cap::STORAGE_DIAGNOSTICS_READ]).await; + let consumer_context = consumer.host.resource_context().unwrap().clone(); + let source = super::data::authenticated_identity(&fixture, &fixture.context()); + let recipient = super::data::authenticated_identity(&fixture, &consumer_context); + fixture + .shared_policies + .set_source_recipient_policy( + SourceRecipientPolicy::new( + source, + recipient, + SharingClass::Sensitive, + "storage.diagnostics.benchmark.v1".into(), + ["measurements.sequential_read".into()], + true, + false, + ) + .unwrap(), + ) + .unwrap(); + + let installation = fixture.game_dir("installed", &[]); + fixture.library_in(&[("fixture:1", Some(42), "Example game", &installation)]); + fixture.user_approving(&installation); + let handle = fixture + .request_access("id-fixture:1", &["read"], &[]) + .await + .unwrap() + .handles + .remove(0) + .handle; + let published = fixture + .client() + .storage_diagnostics_publish_benchmark(BenchmarkReportRequest { + mutation: Some(fixture.mutation("producer-benchmark", 0)), + volume_handle: handle, + tool_name: "FixtureBench".into(), + tool_version: "2.1".into(), + measurements: std::collections::HashMap::from([ + ("sequential_read".into(), 12_000.0), + ("random_read".into(), 3_000.0), + ]), + units: "bytes_per_second".into(), + observed_at: SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_secs() as i64, + ..Default::default() + }) + .await + .unwrap() + .into_inner(); + + let mut diagnostics = consumer.host.storage_diagnostics_client(); + let listed = diagnostics + .list(DiagnosticListRequest { + page: Some(PageRequest { + context: Some(consumer_context.clone()), + page_size: 10, + ..Default::default() + }), + projection_id: "benchmark.v1".into(), + ..Default::default() + }) + .await + .unwrap() + .into_inner(); + assert_eq!(listed.reports.len(), 1); + let report = &listed.reports[0]; + assert_eq!(report.report_id, published.report_id); + let fields = &report.typed_measurements.as_ref().unwrap().fields; + assert!(fields.contains_key("measurements.sequential_read")); + assert!(!fields.contains_key("measurements.random_read")); + assert!(!fields.contains_key("volume_identity_token")); +} diff --git a/crates/app/src/plugin_host/resources/tests/files.rs b/crates/app/src/plugin_host/resources/tests/files.rs new file mode 100644 index 000000000..a542ec730 --- /dev/null +++ b/crates/app/src/plugin_host/resources/tests/files.rs @@ -0,0 +1,1159 @@ +//! `FilesRequestAccess`/`List`/`Read`/`Write`/`Delete` over the real local socket (task 6.2), +//! with a scripted stand-in for the user's approval dialog. + +use std::os::unix::fs::symlink; +use std::path::{Path, PathBuf}; +use std::sync::Mutex as StdMutex; + +use super::*; +use crate::plugin_host::files::{AffectedGame, RootApprover, RootRequest, RootScope}; +use crate::plugin_host::provider::ResourceCaller; + +const FILES: &[&str] = &[cap::FILES_READ, cap::FILES_WRITE, cap::FILES_DELETE]; +const ALL: &[&str] = &["read", "write", "delete"]; +const FILES_AND_STORAGE: &[&str] = &[ + cap::FILES_READ, + cap::FILES_WRITE, + cap::FILES_DELETE, + cap::STORAGE_READ, + cap::STORAGE_WRITE, + cap::STORAGE_PERSIST, +]; + +/// The user: picks `root`, and consents or not. +#[derive(Default)] +pub(super) struct FakeApprover { + pub(super) root: StdMutex>, + pub(super) consent: AtomicBool, + pub(super) asked: StdMutex>, + pub(super) confirmed: StdMutex>, + gate: StdMutex>>, +} + +#[tonic::async_trait] +impl RootApprover for FakeApprover { + async fn choose_root(&self, request: RootRequest) -> Result, Status> { + self.asked.lock().unwrap().push(request); + let gate = self.gate.lock().unwrap().clone(); + if let Some(gate) = gate { + gate.notified().await; + } + Ok(self.root.lock().unwrap().clone()) + } + + async fn confirm(&self, scope: RootScope) -> Result { + self.confirmed.lock().unwrap().push(scope); + Ok(self.consent.load(Ordering::SeqCst)) + } +} + +impl FakeApprover { + pub(super) fn asked(&self) -> usize { + self.asked.lock().unwrap().len() + } +} + +fn names(reply: &FilesListReply) -> Vec<&str> { + reply + .entries + .iter() + .map(|entry| entry.name.as_str()) + .collect() +} + +impl Fixture { + /// A user who approves `root`. + pub(super) fn user_approving(&self, root: &Path) -> Arc { + let approver = Arc::new(FakeApprover::default()); + *approver.root.lock().unwrap() = Some(root.to_path_buf()); + approver.consent.store(true, Ordering::SeqCst); + self.files.set_approver(approver.clone()); + approver + } + + /// The plugin as the resource services see it, for operations the UI performs. + pub(super) fn caller(&self) -> ResourceCaller { + self.api + .authorize_resource(Some(&self.context()), cap::FILES_READ) + .unwrap() + } + + pub(super) fn base(&self) -> PathBuf { + self._temp.path().to_path_buf() + } + + /// `/games/` holding `files`. + pub(super) fn game_dir(&self, name: &str, files: &[(&str, &[u8])]) -> PathBuf { + let dir = self.base().join("games").join(name); + std::fs::create_dir_all(&dir).unwrap(); + for (file, contents) in files { + let path = dir.join(file); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, contents).unwrap(); + } + dir + } + + /// Library rows `(entry key, game, name, install folder)`; each gets the id `id-`. + pub(super) fn library_in(&self, rows: &[(&str, Option, &str, &Path)]) { + let missing = self.feed.sync( + rows.iter() + .map(|(key, game_id, name, dir)| LibrarySource { + entry_key: (*key).into(), + provider_id: key.split(':').next().unwrap().into(), + game_id: *game_id, + name: (*name).into(), + install_state: InstallState::Installed, + display_name: None, + metadata_revision: 0, + artwork_revision: 0, + install_dir: dir.to_string_lossy().into_owned(), + detected_target: None, + }) + .collect(), + ); + let ids = missing + .iter() + .map(|key| (key.clone(), format!("id-{key}"))) + .collect(); + self.feed.assign_ids(&missing, ids); + } + + pub(super) async fn request_access( + &self, + installation: &str, + operations: &[&str], + kinds: &[&str], + ) -> Result { + self.client() + .files_request_access(FilesRequestAccessRequest { + mutation: Some(self.mutation("access", 0)), + game_id: String::new(), + installation_id: installation.into(), + requested_operations: operations.iter().map(|op| (*op).into()).collect(), + resource_kinds: kinds.iter().map(|kind| (*kind).into()).collect(), + declared_locations: vec![], + }) + .await + .map(Response::into_inner) + } + + /// The root handle of an approved `installation` folder. + pub(super) async fn root_handle(&self, installation: &str, operations: &[&str]) -> String { + self.request_access(installation, operations, &[]) + .await + .unwrap() + .handles + .remove(0) + .handle + } + + pub(super) async fn ls(&self, handle: &str) -> Result { + self.ls_page(handle, 0, "").await + } + + async fn ls_page( + &self, + handle: &str, + page_size: u32, + cursor: &str, + ) -> Result { + self.client() + .files_list(FilesListRequest { + context: Some(self.context()), + directory_handle: handle.into(), + cursor: cursor.into(), + page_size, + }) + .await + .map(Response::into_inner) + } + + pub(super) async fn cat( + &self, + handle: &str, + offset: u64, + max_bytes: u64, + ) -> Result { + self.client() + .files_read(FilesReadRequest { + context: Some(self.context()), + file_handle: handle.into(), + offset, + max_bytes, + }) + .await + .map(Response::into_inner) + } + + #[allow(clippy::too_many_arguments)] + pub(super) async fn write_to( + &self, + handle: &str, + name: &str, + contents: &[u8], + offset: u64, + truncate: bool, + idempotency: &str, + ) -> Result { + self.client() + .files_write(FilesWriteRequest { + mutation: Some(self.mutation(idempotency, 0)), + file_handle: handle.into(), + offset, + contents: contents.to_vec(), + truncate, + name: name.into(), + }) + .await + .map(Response::into_inner) + } + + pub(super) async fn rm( + &self, + handle: &str, + idempotency: &str, + ) -> Result { + self.client() + .files_delete(FilesDeleteRequest { + mutation: Some(self.mutation(idempotency, 0)), + file_handle: handle.into(), + }) + .await + .map(Response::into_inner) + } + + /// The handle of the entry called `name` in a listing. + pub(super) async fn child(&self, directory: &str, name: &str) -> String { + self.ls(directory) + .await + .unwrap() + .entries + .into_iter() + .find(|entry| entry.name == name) + .unwrap_or_else(|| panic!("no entry {name}")) + .handle + } +} + +fn code(result: Result) -> Code { + result.unwrap_err().code() +} + +#[tokio::test] +async fn an_approved_folder_is_listed_read_written_and_deleted() { + let fixture = Fixture::new(FILES).await; + let dir = fixture.game_dir( + "portal", + &[("readme.txt", b"hello world"), ("saves/slot1.sav", b"s1")], + ); + fixture.library_in(&[("fixture:1", Some(7), "Portal", &dir)]); + let user = fixture.user_approving(&dir); + + let reply = fixture + .request_access("id-fixture:1", ALL, &[]) + .await + .unwrap(); + let [root] = reply.handles.as_slice() else { + panic!("one handle expected") + }; + assert_eq!(root.resource_kind, "installation"); + assert!(root.writable); + assert_eq!(root.display_name, "Portal (installation)"); + // The user was shown the folder the library knows and the full scope. + { + let asked = user.asked.lock().unwrap(); + assert_eq!(asked.len(), 1); + assert_eq!(asked[0].plugin_id, "fixture.plugin"); + assert_eq!(asked[0].installation_name, "Portal"); + assert_eq!(asked[0].operations, ["read", "write", "delete"]); + assert_eq!(asked[0].suggested.as_deref(), Some(dir.as_path())); + let scopes = user.confirmed.lock().unwrap(); + assert_eq!(scopes[0].root, std::fs::canonicalize(&dir).unwrap()); + assert_eq!( + scopes[0].affected, + [AffectedGame { + name: "Portal".into(), + game_id: Some(7) + }] + ); + } + + let listing = fixture.ls(&root.handle).await.unwrap(); + assert_eq!(names(&listing), ["readme.txt", "saves"]); + assert!(listing.entries[1].directory); + assert_eq!(listing.entries[0].size_bytes, 11); + + let readme = fixture.child(&root.handle, "readme.txt").await; + let read = fixture.cat(&readme, 6, 0).await.unwrap(); + assert_eq!( + (read.contents.as_slice(), read.eof, read.next_offset), + (&b"world"[..], true, 11) + ); + + let saves = fixture.child(&root.handle, "saves").await; + assert_eq!(names(&fixture.ls(&saves).await.unwrap()), ["slot1.sav"]); + + // Create a file, read it back through the returned handle, overwrite it, then delete it. + let created = fixture + .write_to(&saves, "slot2.sav", b"new save", 0, false, "w1") + .await + .unwrap(); + assert_eq!(created.outcome, MutationOutcome::Applied as i32); + assert_eq!( + std::fs::read(dir.join("saves/slot2.sav")).unwrap(), + b"new save" + ); + assert_eq!( + fixture + .cat(&created.resource_id, 0, 0) + .await + .unwrap() + .contents, + b"new save" + ); + fixture + .write_to(&created.resource_id, "", b"X", 0, true, "w2") + .await + .unwrap(); + assert_eq!(std::fs::read(dir.join("saves/slot2.sav")).unwrap(), b"X"); + fixture.rm(&created.resource_id, "d1").await.unwrap(); + assert!(!dir.join("saves/slot2.sav").exists()); + assert_eq!( + code(fixture.cat(&created.resource_id, 0, 0).await), + Code::NotFound + ); +} + +#[tokio::test] +async fn nothing_is_reachable_without_the_grants_and_each_operation_needs_its_own() { + let none = Fixture::new(&[]).await; + assert_eq!( + code(none.request_access("id-x", &["read"], &[]).await), + Code::PermissionDenied + ); + assert_eq!(code(none.cat("h", 0, 0).await), Code::PermissionDenied); + assert_eq!(code(none.ls("h").await), Code::PermissionDenied); + assert_eq!( + code(none.write_to("h", "", b"x", 0, false, "k").await), + Code::PermissionDenied + ); + assert_eq!(code(none.rm("h", "k").await), Code::PermissionDenied); + + // Asking for write needs files.write, whatever else is granted. + let reader = Fixture::new(&[cap::FILES_READ]).await; + let dir = reader.game_dir("g", &[("a.txt", b"a")]); + reader.library_in(&[("fixture:1", None, "G", &dir)]); + let user = reader.user_approving(&dir); + let status = reader + .request_access("id-fixture:1", &["read", "write"], &[]) + .await + .unwrap_err(); + assert_eq!(status.code(), Code::PermissionDenied); + assert_eq!( + user.asked(), + 0, + "the user is not asked for what the plugin may not even request" + ); + + // With only read, an approval for read works and mutations stay denied by the grants. + let root = reader.root_handle("id-fixture:1", &["read"]).await; + let file = reader.child(&root, "a.txt").await; + assert_eq!(reader.cat(&file, 0, 0).await.unwrap().contents, b"a"); + assert_eq!( + code(reader.write_to(&file, "", b"x", 0, false, "w").await), + Code::PermissionDenied + ); + assert_eq!(code(reader.rm(&file, "d").await), Code::PermissionDenied); + assert_eq!(std::fs::read(dir.join("a.txt")).unwrap(), b"a"); +} + +#[tokio::test] +async fn write_and_delete_are_independent_in_the_grants_and_in_the_approval() { + // Granted all three, but the user approved only read and write. + let fixture = Fixture::new(FILES).await; + let dir = fixture.game_dir("g", &[("a.txt", b"a")]); + fixture.library_in(&[("fixture:1", None, "G", &dir)]); + fixture.user_approving(&dir); + let root = fixture + .root_handle("id-fixture:1", &["read", "write"]) + .await; + let file = fixture.child(&root, "a.txt").await; + fixture + .write_to(&file, "", b"b", 0, false, "w") + .await + .unwrap(); + let status = fixture.rm(&file, "d").await.unwrap_err(); + assert_eq!(status.code(), Code::PermissionDenied); + assert!( + status.message().contains("not approved for delete"), + "{}", + status.message() + ); + assert!(dir.join("a.txt").exists()); + + // Approved for delete too, but the plugin's delete grant was revoked. + let wider = fixture.root_handle("id-fixture:1", ALL).await; + let file = fixture.child(&wider, "a.txt").await; + fixture + .api + .revoke_session_permission("fixture", cap::FILES_DELETE) + .await; + assert_eq!(code(fixture.rm(&file, "d2").await), Code::PermissionDenied); + assert!(dir.join("a.txt").exists()); + // Write still works: the grants are independent. + fixture + .write_to(&file, "", b"c", 0, false, "w2") + .await + .unwrap(); +} + +#[tokio::test] +async fn a_declined_or_impossible_approval_gives_no_handle_and_is_not_remembered() { + let fixture = Fixture::new(FILES).await; + let dir = fixture.game_dir("g", &[("a.txt", b"a")]); + fixture.library_in(&[("fixture:1", None, "G", &dir)]); + + // No dialog connected in this build. + assert_eq!( + code(fixture.request_access("id-fixture:1", &["read"], &[]).await), + Code::FailedPrecondition + ); + + let user = fixture.user_approving(&dir); + *user.root.lock().unwrap() = None; + assert_eq!( + code(fixture.request_access("id-fixture:1", &["read"], &[]).await), + Code::PermissionDenied + ); + *user.root.lock().unwrap() = Some(dir.clone()); + user.consent.store(false, Ordering::SeqCst); + assert_eq!( + code(fixture.request_access("id-fixture:1", &["read"], &[]).await), + Code::PermissionDenied + ); + // A folder that is not there. + *user.root.lock().unwrap() = Some(fixture.base().join("missing")); + user.consent.store(true, Ordering::SeqCst); + assert_eq!( + code(fixture.request_access("id-fixture:1", &["read"], &[]).await), + Code::FailedPrecondition + ); + let asked = user.asked(); + + // None of that left an approval behind: the next request asks again, and works. + *user.root.lock().unwrap() = Some(dir.clone()); + fixture + .request_access("id-fixture:1", &["read"], &[]) + .await + .unwrap(); + assert_eq!(user.asked(), asked + 1); +} + +#[tokio::test] +async fn an_approval_is_remembered_and_reused_but_a_wider_request_asks_again() { + let first = Fixture::new(FILES).await; + let dir = first.game_dir("g", &[("a.txt", b"a")]); + first.library_in(&[("fixture:1", None, "G", &dir)]); + let user = first.user_approving(&dir); + first + .request_access("id-fixture:1", &["read"], &[]) + .await + .unwrap(); + assert_eq!(user.asked(), 1); + + // Asking again for the same or less does not bother the user. + first + .request_access("id-fixture:1", &["read"], &[]) + .await + .unwrap(); + assert_eq!(user.asked(), 1); + // Wanting write as well is a wider scope. + first + .request_access("id-fixture:1", &["read", "write"], &[]) + .await + .unwrap(); + assert_eq!(user.asked(), 2); + first + .request_access("id-fixture:1", &["write"], &[]) + .await + .unwrap(); + assert_eq!(user.asked(), 2); + + // After a restart of the host the approval is still there: it belongs to the profile. + let second = Fixture::restarted(FILES, first.plugin_data.clone()).await; + second.library_in(&[("fixture:1", None, "G", &dir)]); + let nobody = Arc::new(FakeApprover::default()); + second.files.set_approver(nobody.clone()); + let root = second.root_handle("id-fixture:1", &["read", "write"]).await; + assert_eq!(names(&second.ls(&root).await.unwrap()), ["a.txt"]); + assert_eq!(nobody.asked(), 0); +} + +#[tokio::test] +async fn handles_belong_to_the_session_that_received_them() { + let mut fixture = Fixture::new(FILES).await; + let dir = fixture.game_dir("g", &[("a.txt", b"a")]); + fixture.library_in(&[("fixture:1", None, "G", &dir)]); + let user = fixture.user_approving(&dir); + let root = fixture.root_handle("id-fixture:1", ALL).await; + let file = fixture.child(&root, "a.txt").await; + + fixture.reconnect().await; + // The old session's handles mean nothing now, however they are used. + assert_eq!(code(fixture.ls(&root).await), Code::NotFound); + assert_eq!(code(fixture.cat(&file, 0, 0).await), Code::NotFound); + assert_eq!(code(fixture.rm(&file, "d").await), Code::NotFound); + // The approval is kept, so new handles come without asking. + let fresh = fixture.root_handle("id-fixture:1", ALL).await; + assert_ne!(fresh, root); + assert_eq!(names(&fixture.ls(&fresh).await.unwrap()), ["a.txt"]); + assert_eq!(user.asked(), 1); + assert!(dir.join("a.txt").exists()); +} + +#[tokio::test] +async fn forged_edited_and_empty_handles_open_nothing() { + let fixture = Fixture::new(FILES).await; + let dir = fixture.game_dir("g", &[("a.txt", b"a")]); + fixture.library_in(&[("fixture:1", None, "G", &dir)]); + fixture.user_approving(&dir); + let root = fixture.root_handle("id-fixture:1", ALL).await; + let file = fixture.child(&root, "a.txt").await; + + let mut flipped = file.clone().into_bytes(); + flipped[20] = if flipped[20] == b'0' { b'1' } else { b'0' }; + for bad in [ + String::new(), + "x".into(), + "../../etc/passwd".into(), + "/etc/passwd".into(), + file[..file.len() - 2].to_owned(), + String::from_utf8(flipped).unwrap(), + "0".repeat(200), + ] { + let expected = if bad.is_empty() { + Code::InvalidArgument + } else { + Code::NotFound + }; + assert_eq!(code(fixture.cat(&bad, 0, 0).await), expected, "{bad:?}"); + assert_eq!(code(fixture.ls(&bad).await), expected, "{bad:?}"); + assert_eq!(code(fixture.rm(&bad, "d").await), expected, "{bad:?}"); + } + // A cursor is not a handle and a handle is not a cursor. + assert_eq!( + code(fixture.ls_page(&root, 1, &file).await), + Code::InvalidArgument + ); + assert!(dir.join("a.txt").exists()); +} + +#[tokio::test] +async fn a_sibling_games_folder_is_out_of_reach() { + let fixture = Fixture::new(FILES).await; + let a = fixture.game_dir("a", &[("a.sav", b"a")]); + let b = fixture.game_dir("b", &[("b.sav", b"b")]); + fixture.library_in(&[("fixture:1", None, "A", &a), ("fixture:2", None, "B", &b)]); + let user = fixture.user_approving(&a); + + let root_a = fixture.root_handle("id-fixture:1", ALL).await; + // A's folder shows only A's files and nothing links to the sibling. + assert_eq!(names(&fixture.ls(&root_a).await.unwrap()), ["a.sav"]); + // Approving A did not approve B: B asks the user on its own, and is shown B. + *user.root.lock().unwrap() = Some(b.clone()); + let root_b = fixture.root_handle("id-fixture:2", &["read"]).await; + assert_eq!(names(&fixture.ls(&root_b).await.unwrap()), ["b.sav"]); + assert_eq!(user.asked(), 2); + assert_eq!( + user.asked.lock().unwrap()[1].suggested.as_deref(), + Some(b.as_path()) + ); + // B's read-only approval does not let A's handle write to B or B's handle write at all. + let b_file = fixture.child(&root_b, "b.sav").await; + assert_eq!( + code(fixture.write_to(&b_file, "", b"x", 0, false, "w").await), + Code::PermissionDenied + ); + assert_eq!(std::fs::read(b.join("b.sav")).unwrap(), b"b"); +} + +#[tokio::test] +async fn another_providers_or_unknown_installations_cannot_be_approved() { + let fixture = Fixture::new(FILES).await; + let dir = fixture.game_dir("g", &[]); + fixture.library_in(&[ + ("fixture:1", Some(5), "G", &dir), + ("steam:9", Some(6), "Other", &dir), + ]); + let user = fixture.user_approving(&dir); + assert_eq!( + code(fixture.request_access("id-steam:9", &["read"], &[]).await), + Code::NotFound + ); + assert_eq!( + code(fixture.request_access("id-nope", &["read"], &[]).await), + Code::NotFound + ); + // A game named for another match does not select the installation either. + let status = fixture + .client() + .files_request_access(FilesRequestAccessRequest { + mutation: Some(fixture.mutation("k", 0)), + game_id: "99".into(), + installation_id: "id-fixture:1".into(), + requested_operations: vec!["read".into()], + resource_kinds: vec![], + declared_locations: vec![], + }) + .await + .unwrap_err(); + assert_eq!(status.code(), Code::NotFound); + assert_eq!(user.asked(), 0); +} + +#[tokio::test] +async fn a_shared_folder_needs_the_whole_scope_confirmed_and_holds_only_while_it_is_complete() { + let fixture = Fixture::new(FILES).await; + let shared = fixture.base().join("games"); + let a = fixture.game_dir("a", &[("a.sav", b"a")]); + let b = fixture.game_dir("b", &[("b.sav", b"b")]); + fixture.library_in(&[ + ("fixture:1", Some(1), "A", &a), + ("fixture:2", Some(2), "B", &b), + ]); + // The user approves the parent that holds both games for A. + let user = fixture.user_approving(&shared); + let root = fixture.root_handle("id-fixture:1", &["read"]).await; + let scope = user.confirmed.lock().unwrap()[0].clone(); + assert_eq!( + scope.affected, + [ + AffectedGame { + name: "A".into(), + game_id: Some(1) + }, + AffectedGame { + name: "B".into(), + game_id: Some(2) + }, + ], + "the sibling is named in the confirmation" + ); + assert_eq!(names(&fixture.ls(&root).await.unwrap()), ["a", "b"]); + + // A game installed there later was never confirmed: the approval stops covering it. + let c = fixture.game_dir("c", &[]); + fixture.library_in(&[ + ("fixture:1", Some(1), "A", &a), + ("fixture:2", Some(2), "B", &b), + ("fixture:3", Some(3), "C", &c), + ]); + assert_eq!(code(fixture.ls(&root).await), Code::FailedPrecondition); + // Asking again shows the new, complete scope; confirming it restores access. + let asked = user.asked(); + let again = fixture.root_handle("id-fixture:1", &["read"]).await; + assert_eq!(user.asked(), asked + 1); + assert_eq!( + user.confirmed + .lock() + .unwrap() + .last() + .unwrap() + .affected + .len(), + 3 + ); + assert_eq!(names(&fixture.ls(&again).await.unwrap()), ["a", "b", "c"]); +} + +#[tokio::test] +async fn a_game_leaving_a_shared_folder_also_needs_a_new_approval() { + let fixture = Fixture::new(FILES).await; + let a = fixture.game_dir("a", &[]); + let b = fixture.game_dir("b", &[]); + fixture.library_in(&[("fixture:1", None, "A", &a), ("fixture:2", None, "B", &b)]); + fixture.user_approving(&fixture.base().join("games")); + let root = fixture.root_handle("id-fixture:1", &["read"]).await; + fixture.library_in(&[("fixture:1", None, "A", &a)]); + assert_eq!(code(fixture.ls(&root).await), Code::FailedPrecondition); +} + +#[tokio::test] +async fn the_hosts_own_folders_are_excluded_even_under_an_approved_parent() { + let fixture = Fixture::new(FILES_AND_STORAGE).await; + let dir = fixture.game_dir("g", &[("a.txt", b"a")]); + fixture.library_in(&[("fixture:1", None, "G", &dir)]); + // A durable value makes the plugin's private store exist inside the reserved folder. + fixture + .store("k", b"v", StorageDurability::Persistent, 0) + .await + .unwrap(); + assert!(fixture.stored_files() > 0); + + // The user approves the whole base folder, which contains the reserved plugin-data folder. + let user = fixture.user_approving(&fixture.base()); + let root = fixture.root_handle("id-fixture:1", ALL).await; + let listing = names(&fixture.ls(&root).await.unwrap()).join(","); + assert!(listing.contains("games"), "{listing}"); + assert!(!listing.contains("plugin-data"), "{listing}"); + // Nor can a folder inside it, or it itself, be approved. + for reserved in [ + fixture.plugin_data.clone(), + fixture.plugin_data.join("anything"), + ] { + std::fs::create_dir_all(&reserved).unwrap(); + *user.root.lock().unwrap() = Some(reserved); + let status = fixture + .request_access("id-fixture:1", &["read"], &["save"]) + .await + .unwrap_err(); + assert_eq!(status.code(), Code::FailedPrecondition); + } + assert!(fixture.stored_files() > 0, "the private store is untouched"); +} + +#[tokio::test] +async fn a_directory_replaced_by_a_link_after_listing_is_refused() { + let fixture = Fixture::new(FILES).await; + let dir = fixture.game_dir("g", &[("saves/slot1.sav", b"mine")]); + let outside = fixture.base().join("outside"); + std::fs::create_dir_all(&outside).unwrap(); + std::fs::write(outside.join("slot1.sav"), b"secret").unwrap(); + fixture.library_in(&[("fixture:1", None, "G", &dir)]); + fixture.user_approving(&dir); + let root = fixture.root_handle("id-fixture:1", ALL).await; + let saves = fixture.child(&root, "saves").await; + let slot = fixture.child(&saves, "slot1.sav").await; + assert_eq!(fixture.cat(&slot, 0, 0).await.unwrap().contents, b"mine"); + + std::fs::remove_dir_all(dir.join("saves")).unwrap(); + symlink(&outside, dir.join("saves")).unwrap(); + + for status in [ + fixture.cat(&slot, 0, 0).await.map(|_| ()), + fixture.ls(&saves).await.map(|_| ()), + fixture.rm(&slot, "d").await.map(|_| ()), + fixture + .write_to(&slot, "", b"pwn", 0, true, "w") + .await + .map(|_| ()), + fixture + .write_to(&saves, "new.sav", b"pwn", 0, false, "w2") + .await + .map(|_| ()), + ] { + assert_eq!(status.unwrap_err().code(), Code::PermissionDenied); + } + assert_eq!(std::fs::read(outside.join("slot1.sav")).unwrap(), b"secret"); + assert!(!outside.join("new.sav").exists()); +} + +#[tokio::test] +async fn a_root_that_was_replaced_is_no_longer_the_approved_folder() { + let fixture = Fixture::new(FILES).await; + let dir = fixture.game_dir("g", &[("a.txt", b"a")]); + fixture.library_in(&[("fixture:1", None, "G", &dir)]); + fixture.user_approving(&dir); + let root = fixture.root_handle("id-fixture:1", ALL).await; + assert!(fixture.ls(&root).await.is_ok()); + + std::fs::rename(&dir, fixture.base().join("moved")).unwrap(); + assert_eq!(code(fixture.ls(&root).await), Code::FailedPrecondition); + // Another folder put in its place is not the one the user approved. + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("impostor.txt"), b"x").unwrap(); + assert_eq!(code(fixture.ls(&root).await), Code::FailedPrecondition); +} + +#[tokio::test] +async fn a_revoked_approval_or_grant_stops_its_handles_at_once() { + let fixture = Fixture::new(FILES).await; + let dir = fixture.game_dir("g", &[("a.txt", b"a")]); + fixture.library_in(&[("fixture:1", None, "G", &dir)]); + fixture.user_approving(&dir); + let root = fixture.root_handle("id-fixture:1", ALL).await; + let file = fixture.child(&root, "a.txt").await; + + // The user revokes this approval (the settings UI does this through the same store). + let id = { + let mut found = None; + let session = fixture.context().session_id; + found.replace(fixture.files.open_handle(&session, &root).unwrap().0); + found.unwrap() + }; + let caller = fixture.caller(); + let revoked = fixture + .storage + .run( + &caller, + |_| true, + move |namespace| namespace.revoke_approval(&id), + ) + .await + .unwrap(); + assert!(revoked); + assert_eq!(code(fixture.ls(&root).await), Code::NotFound); + assert_eq!(code(fixture.cat(&file, 0, 0).await), Code::NotFound); + assert_eq!(code(fixture.rm(&file, "d").await), Code::NotFound); + assert!(dir.join("a.txt").exists()); + + // Approving again makes a fresh approval, with its own handles. + let fresh = fixture.root_handle("id-fixture:1", ALL).await; + assert_eq!(names(&fixture.ls(&fresh).await.unwrap()), ["a.txt"]); + // And a revoked grant stops them even though the approval stands. + fixture + .api + .revoke_session_permission("fixture", cap::FILES_READ) + .await; + assert_eq!(code(fixture.ls(&fresh).await), Code::PermissionDenied); +} + +#[tokio::test] +async fn reads_are_bounded_and_resume_where_they_stopped() { + let fixture = Fixture::new(FILES).await; + let big = vec![7u8; 5 * 1024 * 1024]; + let dir = fixture.game_dir("g", &[("big.bin", &big), ("small.txt", b"0123456789")]); + fixture.library_in(&[("fixture:1", None, "G", &dir)]); + fixture.user_approving(&dir); + let root = fixture.root_handle("id-fixture:1", &["read"]).await; + + let file = fixture.child(&root, "big.bin").await; + // A huge budget is capped, and the default is smaller still. + let capped = fixture.cat(&file, 0, u64::MAX).await.unwrap(); + assert_eq!( + (capped.contents.len(), capped.eof), + (4 * 1024 * 1024, false) + ); + assert_eq!( + fixture.cat(&file, 0, 0).await.unwrap().contents.len(), + 1024 * 1024 + ); + let rest = fixture + .cat(&file, capped.next_offset, u64::MAX) + .await + .unwrap(); + assert_eq!((rest.contents.len(), rest.eof), (1024 * 1024, true)); + + let small = fixture.child(&root, "small.txt").await; + let mut offset = 0; + let mut text = Vec::new(); + loop { + let part = fixture.cat(&small, offset, 4).await.unwrap(); + text.extend_from_slice(&part.contents); + offset = part.next_offset; + if part.eof { + break; + } + } + assert_eq!(text, b"0123456789"); + assert!(fixture.cat(&small, 100, 4).await.unwrap().eof); +} + +#[tokio::test] +async fn listings_page_with_cursors_bound_to_the_directory() { + let fixture = Fixture::new(FILES).await; + let files: Vec<(String, &[u8])> = (0..5).map(|i| (format!("f{i}"), &b"x"[..])).collect(); + let refs: Vec<(&str, &[u8])> = files.iter().map(|(n, c)| (n.as_str(), *c)).collect(); + let dir = fixture.game_dir("g", &refs); + std::fs::create_dir_all(dir.join("other")).unwrap(); + fixture.library_in(&[("fixture:1", None, "G", &dir)]); + fixture.user_approving(&dir); + let root = fixture.root_handle("id-fixture:1", &["read"]).await; + + let first = fixture.ls_page(&root, 2, "").await.unwrap(); + assert_eq!(names(&first), ["f0", "f1"]); + let second = fixture.ls_page(&root, 2, &first.next_cursor).await.unwrap(); + assert_eq!(names(&second), ["f2", "f3"]); + let third = fixture + .ls_page(&root, 2, &second.next_cursor) + .await + .unwrap(); + assert_eq!(names(&third), ["f4", "other"]); + assert!(third.next_cursor.is_empty()); + // A cursor of one directory means nothing for another, or when edited. + let other = fixture.child(&root, "other").await; + assert_eq!( + code(fixture.ls_page(&other, 2, &first.next_cursor).await), + Code::InvalidArgument + ); + assert_eq!( + code( + fixture + .ls_page(&root, 2, &format!("{}00", first.next_cursor)) + .await + ), + Code::InvalidArgument + ); +} + +#[tokio::test] +async fn writes_are_validated_and_never_leave_the_folder_or_leave_holes() { + let fixture = Fixture::new(FILES).await; + let dir = fixture.game_dir("g", &[("a.txt", b"hello")]); + fixture.library_in(&[("fixture:1", None, "G", &dir)]); + fixture.user_approving(&dir); + let root = fixture + .root_handle("id-fixture:1", &["read", "write"]) + .await; + let file = fixture.child(&root, "a.txt").await; + + for bad in ["..", "../x", "a/b", "a\\b", "con", "x:y", "tail.", ""] { + let result = fixture.write_to(&root, bad, b"x", 0, false, "w").await; + if bad.is_empty() { + // No name: the directory handle is not a file. + assert_eq!(code(result), Code::FailedPrecondition); + } else { + assert_eq!(code(result), Code::InvalidArgument, "{bad:?}"); + } + } + assert_eq!( + code(fixture.write_to(&file, "", b"x", 6, false, "w1").await), + Code::OutOfRange + ); + assert_eq!( + code(fixture.write_to(&root, "new", b"x", 1, false, "w2").await), + Code::OutOfRange + ); + let too_big = vec![0u8; 4 * 1024 * 1024 + 1]; + assert_eq!( + code(fixture.write_to(&file, "", &too_big, 0, false, "w3").await), + Code::InvalidArgument + ); + // A file handle is not a directory to create inside. + assert_eq!( + code(fixture.write_to(&file, "child", b"x", 0, false, "w4").await), + Code::FailedPrecondition + ); + // Files carry no revision. + let status = fixture + .client() + .files_write(FilesWriteRequest { + mutation: Some(fixture.mutation("w5", 3)), + file_handle: file.clone(), + offset: 0, + contents: b"x".to_vec(), + truncate: false, + name: String::new(), + }) + .await + .unwrap_err(); + assert_eq!(status.code(), Code::InvalidArgument); + assert_eq!(std::fs::read(dir.join("a.txt")).unwrap(), b"hello"); + assert_eq!( + std::fs::read_dir(&dir).unwrap().count(), + 1, + "nothing was created" + ); +} + +#[tokio::test] +async fn retried_writes_and_deletes_return_the_original_outcome_and_a_reused_key_is_refused() { + let fixture = Fixture::new(FILES).await; + let dir = fixture.game_dir("g", &[("a.txt", b"")]); + fixture.library_in(&[("fixture:1", None, "G", &dir)]); + fixture.user_approving(&dir); + let root = fixture.root_handle("id-fixture:1", ALL).await; + let file = fixture.child(&root, "a.txt").await; + + // An append retried under its key is applied once. + let first = fixture + .write_to(&file, "", b"line;", 0, false, "append") + .await + .unwrap(); + let retry = fixture + .write_to(&file, "", b"line;", 0, false, "append") + .await + .unwrap(); + assert_eq!(first, retry); + assert_eq!(std::fs::read(dir.join("a.txt")).unwrap(), b"line;"); + // The key is for that request only. + assert_eq!( + code( + fixture + .write_to(&file, "", b"other", 0, false, "append") + .await + ), + Code::FailedPrecondition + ); + assert_eq!( + code(fixture.rm(&file, "append").await), + Code::FailedPrecondition + ); + + let deleted = fixture.rm(&file, "remove").await.unwrap(); + let again = fixture.rm(&file, "remove").await.unwrap(); + assert_eq!(deleted, again, "the retry is answered, not NOT_FOUND"); + // A new delete of the same file is a different request and the file is gone. + assert_eq!(code(fixture.rm(&file, "remove-2").await), Code::NotFound); +} + +#[tokio::test] +async fn requests_are_validated() { + let fixture = Fixture::new(FILES).await; + let dir = fixture.game_dir("g", &[]); + fixture.library_in(&[("fixture:1", None, "G", &dir)]); + let user = fixture.user_approving(&dir); + for (operations, kinds) in [ + (vec![], vec![]), + (vec!["execute"], vec![]), + (vec!["READ"], vec![]), + (vec!["read"], vec!["everything"]), + ] { + assert_eq!( + code( + fixture + .request_access("id-fixture:1", &operations, &kinds) + .await + ), + Code::InvalidArgument, + "{operations:?} {kinds:?}" + ); + } + assert_eq!( + code(fixture.request_access("", &["read"], &[]).await), + Code::InvalidArgument + ); + assert_eq!( + code( + fixture + .request_access(&"i".repeat(200), &["read"], &[]) + .await + ), + Code::InvalidArgument + ); + assert_eq!(user.asked(), 0); +} + +#[tokio::test] +async fn each_kind_is_approved_separately_and_only_installations_have_a_suggestion() { + let fixture = Fixture::new(FILES).await; + let dir = fixture.game_dir("g", &[("a.txt", b"a")]); + let saves = fixture.base().join("elsewhere"); + std::fs::create_dir_all(&saves).unwrap(); + std::fs::write(saves.join("save.dat"), b"s").unwrap(); + fixture.library_in(&[("fixture:1", None, "G", &dir)]); + let user = fixture.user_approving(&saves); + + let reply = fixture + .request_access("id-fixture:1", &["read"], &["save", "prefix", "save"]) + .await + .unwrap(); + assert_eq!( + reply + .handles + .iter() + .map(|h| h.resource_kind.as_str()) + .collect::>(), + ["save", "prefix"] + ); + assert!(!reply.handles[0].writable); + assert_eq!(user.asked(), 2); + assert!( + user.asked + .lock() + .unwrap() + .iter() + .all(|ask| ask.suggested.is_none()) + ); + for handle in &reply.handles { + assert_eq!( + names(&fixture.ls(&handle.handle).await.unwrap()), + ["save.dat"] + ); + } +} + +#[tokio::test] +async fn one_approval_waits_for_the_user_at_a_time() { + let fixture = Fixture::new(FILES_AND_STORAGE).await; + let dir = fixture.game_dir("g", &[("a.txt", b"a")]); + fixture.library_in(&[("fixture:1", None, "G", &dir)]); + let user = fixture.user_approving(&dir); + let gate = Arc::new(tokio::sync::Notify::new()); + *user.gate.lock().unwrap() = Some(gate.clone()); + + let waiting = { + let fixture_client = fixture.client(); + let request = FilesRequestAccessRequest { + mutation: Some(fixture.mutation("first", 0)), + game_id: String::new(), + installation_id: "id-fixture:1".into(), + requested_operations: vec!["read".into()], + resource_kinds: vec![], + declared_locations: vec![], + }; + tokio::spawn(async move { + let mut client = fixture_client; + client.files_request_access(request).await + }) + }; + let deadline = tokio::time::Instant::now() + Duration::from_secs(5); + while user.asked() == 0 { + assert!( + tokio::time::Instant::now() < deadline, + "the dialog never opened" + ); + tokio::time::sleep(Duration::from_millis(10)).await; + } + // The user is already deciding: a second request does not open a second dialog. + assert_eq!( + code(fixture.request_access("id-fixture:1", &["read"], &[]).await), + Code::Aborted + ); + assert_eq!(user.asked(), 1); + // Storage of the same plugin still answers while the user decides. + assert!(!fixture.load("k").await.unwrap().found); + + gate.notify_one(); + let reply = waiting.await.unwrap().unwrap(); + assert_eq!(reply.into_inner().handles.len(), 1); +} + +#[tokio::test] +async fn nothing_in_any_answer_is_a_path() { + let fixture = Fixture::new(FILES).await; + let dir = fixture.game_dir("secret-place", &[("a.txt", b"a")]); + fixture.library_in(&[("fixture:1", None, "G", &dir)]); + let user = fixture.user_approving(&dir); + let base = fixture.base().to_string_lossy().into_owned(); + + let mut shown = Vec::new(); + let reply = fixture + .request_access("id-fixture:1", ALL, &[]) + .await + .unwrap(); + shown.push(format!("{reply:?}")); + let root = reply.handles[0].handle.clone(); + shown.push(format!("{:?}", fixture.ls(&root).await.unwrap())); + let file = fixture.child(&root, "a.txt").await; + shown.push(format!("{:?}", fixture.cat(&file, 0, 0).await.unwrap())); + shown.push(format!( + "{:?}", + fixture + .write_to(&root, "w.txt", b"x", 0, false, "w") + .await + .unwrap() + )); + for failure in [ + fixture.cat("junk", 0, 0).await.map(|_| ()).unwrap_err(), + fixture.rm(&root, "d").await.map(|_| ()).unwrap_err(), + fixture + .write_to(&root, "..", b"x", 0, false, "w2") + .await + .map(|_| ()) + .unwrap_err(), + ] { + shown.push(format!("{} {:?}", failure.message(), failure.code())); + } + // Moving the root makes an error; it names no path either. + std::fs::rename(&dir, fixture.base().join("moved-away")).unwrap(); + shown.push(fixture.ls(&root).await.unwrap_err().message().to_owned()); + for text in &shown { + assert!( + !text.contains(&base) && !text.contains("secret-place"), + "{text}" + ); + } + assert!(user.asked() > 0); +} diff --git a/crates/app/src/plugin_host/resources/tests/fingerprints.rs b/crates/app/src/plugin_host/resources/tests/fingerprints.rs new file mode 100644 index 000000000..d40cee802 --- /dev/null +++ b/crates/app/src/plugin_host/resources/tests/fingerprints.rs @@ -0,0 +1,823 @@ +//! `Locations.GetFingerprint` and `Compare` over the real local socket (task 13.4): content +//! fingerprints of approved places, read fresh, and their comparison. + +use std::os::unix::fs::PermissionsExt; +use std::path::Path; +use std::sync::Mutex as StdMutex; +use std::time::{Duration as StdDuration, UNIX_EPOCH}; + +use sha2::{Digest, Sha256}; + +use super::saves::{INSTALLATION, directory, profile}; +use super::*; +use crate::plugin_host::fingerprints::{ALGORITHM, Record, tree_digest}; + +const INSPECT: &[&str] = &[ + cap::GAME_STORAGE_INSPECT, + cap::GAME_SAVES_INSPECT, + cap::GAME_SAVES_READ, + cap::GAME_SAVES_CREATE, + cap::GAME_SAVES_UPDATE, + cap::FILES_READ, +]; + +fn running_as_root() -> bool { + rustix::process::geteuid().is_root() +} + +impl Fixture { + async fn fingerprint( + &self, + key: &str, + handle: &str, + max_entries: u32, + ) -> Result { + self.host + .locations_client() + .get_fingerprint(LocationFingerprintRequest { + context: Some(self.context()), + approved_resource_handle: handle.into(), + algorithm: "sha256".into(), + require_fresh: true, + max_entries, + idempotency_key: key.into(), + }) + .await + .map(Response::into_inner) + } + + async fn diff( + &self, + before: &str, + after: &str, + page_size: u32, + cursor: &str, + ) -> Result { + self.host + .locations_client() + .compare(LocationCompareRequest { + context: Some(self.context()), + before_snapshot_id: before.into(), + after_snapshot_id: after.into(), + expected_revision: 0, + page_size, + cursor: cursor.into(), + }) + .await + .map(Response::into_inner) + } + + /// Fingerprints `handle` and returns the finished reply. + async fn take(&self, key: &str, handle: &str) -> LocationFingerprintReply { + let reply = self.fingerprint(key, handle, 0).await.unwrap(); + assert!(!reply.snapshot_id.is_empty(), "{reply:?}"); + reply + } +} + +fn sha(bytes: &[u8]) -> [u8; 32] { + Sha256::digest(bytes).into() +} + +fn set_time(path: &Path, seconds: u64) { + std::fs::File::options() + .write(true) + .open(path) + .unwrap() + .set_modified(UNIX_EPOCH + StdDuration::from_secs(seconds)) + .unwrap(); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_small_place_is_fingerprinted_at_once_with_the_documented_digest() { + let (fixture, saves) = Fixture::emulator(INSPECT).await; + let root = fixture.approve(INSTALLATION, "save", &saves).await; + let reply = fixture.fingerprint("k", &root, 0).await.unwrap(); + + assert_eq!(reply.algorithm, ALGORITHM); + assert!(reply.complete); + assert_eq!(reply.consistency, "best_effort"); + assert_eq!(reply.availability, InspectionAvailability::Available as i32); + assert!(!reply.job_id.is_empty() && reply.snapshot_id.starts_with("snap-")); + assert!(reply.observed_start_at > 0 && reply.observed_end_at >= reply.observed_start_at); + // The digest is the one the documentation describes, recomputed here from the files. + let record = |label: &str, directory: bool, size: u64, content: &[u8]| Record { + label: label.into(), + approval_id: String::new(), + path: vec![], + directory, + size, + digest: (!directory).then(|| sha(content)), + unreadable: false, + unstable: false, + }; + let expected = tree_digest(&[ + record("GC", true, 0, b""), + record("GC/USA", true, 0, b""), + record("GC/USA/card.gci", false, 4, b"card"), + record("states", true, 0, b""), + record("states/s1.sav", false, 5, b"state"), + ]); + assert_eq!(reply.digest, expected.to_vec()); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_retry_is_the_same_fingerprint_and_a_reused_key_for_another_place_is_refused() { + let (fixture, saves) = Fixture::emulator(INSPECT).await; + let root = fixture.approve(INSTALLATION, "save", &saves).await; + let states = fixture.child(&root, "states").await; + let first = fixture.fingerprint("same", &root, 0).await.unwrap(); + // The files change, and the retry still answers with the first result, not a second run. + std::fs::write(saves.join("GC/USA/card.gci"), b"CARD").unwrap(); + let again = fixture.fingerprint("same", &root, 0).await.unwrap(); + assert_eq!( + (again.snapshot_id, again.digest), + (first.snapshot_id, first.digest) + ); + assert_eq!( + fixture + .fingerprint("same", &states, 0) + .await + .unwrap_err() + .code(), + Code::FailedPrecondition + ); + assert_eq!( + fixture.fingerprint("", &root, 0).await.unwrap_err().code(), + Code::InvalidArgument + ); + let other = fixture + .host + .locations_client() + .get_fingerprint(LocationFingerprintRequest { + context: Some(fixture.context()), + approved_resource_handle: root.clone(), + algorithm: "md5".into(), + require_fresh: true, + max_entries: 0, + idempotency_key: "md5".into(), + }) + .await + .unwrap_err(); + assert_eq!(other.code(), Code::InvalidArgument); +} + +#[tokio::test(flavor = "multi_thread")] +async fn nothing_changed_is_unchanged_and_a_same_size_same_time_edit_is_found() { + let (fixture, saves) = Fixture::emulator(INSPECT).await; + let root = fixture.approve(INSTALLATION, "save", &saves).await; + let card = saves.join("GC/USA/card.gci"); + set_time(&card, 1_600_000_000); + let first = fixture.take("a", &root).await; + let second = fixture.take("b", &root).await; + assert_eq!(first.digest, second.digest); + let same = fixture + .diff(&first.snapshot_id, &second.snapshot_id, 0, "") + .await + .unwrap(); + assert_eq!((same.status.as_str(), same.changes.len()), ("unchanged", 0)); + + // The bytes change; the size and the modification time do not. + std::fs::write(&card, b"CARD").unwrap(); + set_time(&card, 1_600_000_000); + let third = fixture.take("c", &root).await; + assert_ne!(first.digest, third.digest); + let changed = fixture + .diff(&first.snapshot_id, &third.snapshot_id, 0, "") + .await + .unwrap(); + assert_eq!(changed.status, "changed"); + let [change] = changed.changes.try_into().unwrap(); + assert_eq!( + ( + change.change_kind.as_str(), + change.relative_path.as_str(), + change.previous_size_bytes, + change.current_size_bytes + ), + ("modified", "GC/USA/card.gci", 4, 4) + ); + // The entry that changed comes with a handle for the next call. + assert!(!change.entry_handle.is_empty()); + assert_eq!( + fixture + .cat(&change.entry_handle, 0, 10) + .await + .unwrap() + .contents, + b"CARD" + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn additions_deletions_empty_folders_and_renames_are_all_found_and_paged() { + let (fixture, saves) = Fixture::emulator(INSPECT).await; + let root = fixture.approve(INSTALLATION, "save", &saves).await; + std::fs::create_dir(saves.join("empty-old")).unwrap(); + std::fs::write(saves.join("old-name.sav"), b"rename me").unwrap(); + let before = fixture.take("a", &root).await; + + std::fs::remove_dir(saves.join("empty-old")).unwrap(); + std::fs::create_dir(saves.join("empty-new")).unwrap(); + std::fs::rename(saves.join("old-name.sav"), saves.join("new-name.sav")).unwrap(); + std::fs::remove_file(saves.join("states/s1.sav")).unwrap(); + std::fs::write(saves.join("fresh.sav"), b"fresh").unwrap(); + let after = fixture.take("b", &root).await; + assert_ne!(before.digest, after.digest); + + let all = fixture + .diff(&before.snapshot_id, &after.snapshot_id, 0, "") + .await + .unwrap(); + assert_eq!(all.status, "changed"); + let seen: Vec<_> = all + .changes + .iter() + .map(|c| (c.relative_path.as_str(), c.change_kind.as_str())) + .collect(); + assert_eq!( + seen, + [ + ("empty-new", "added"), + ("empty-old", "removed"), + ("fresh.sav", "added"), + ("new-name.sav", "added"), + ("old-name.sav", "removed"), + ("states/s1.sav", "removed"), + ] + ); + // What no longer exists has no handle; what does, has one. + let handles: Vec = all + .changes + .iter() + .map(|c| !c.entry_handle.is_empty()) + .collect(); + assert_eq!(handles, [true, false, true, true, false, false]); + + // Paged: two at a time, every change once. + let mut paged = Vec::new(); + let mut cursor = String::new(); + loop { + let page = fixture + .diff(&before.snapshot_id, &after.snapshot_id, 2, &cursor) + .await + .unwrap(); + assert!(page.changes.len() <= 2); + paged.extend(page.changes.iter().map(|c| c.relative_path.clone())); + if page.next_cursor.is_empty() { + break; + } + cursor = page.next_cursor; + } + assert_eq!(paged.len(), 6); + assert_eq!( + fixture + .diff(&before.snapshot_id, &after.snapshot_id, 2, "not-a-cursor") + .await + .unwrap_err() + .code(), + Code::InvalidArgument + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_file_that_cannot_be_read_makes_the_fingerprint_incomplete_and_never_unchanged() { + if running_as_root() { + return; // root reads everything + } + let (fixture, saves) = Fixture::emulator(INSPECT).await; + let root = fixture.approve(INSTALLATION, "save", &saves).await; + let complete = fixture.take("a", &root).await; + let locked = saves.join("states/s1.sav"); + std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o000)).unwrap(); + let partial = fixture.take("b", &root).await; + let again = fixture.take("c", &root).await; + std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o644)).unwrap(); + + assert!(!partial.complete); + assert!( + partial.digest.is_empty(), + "no digest is given for what was not wholly read" + ); + // Two incomplete fingerprints that look the same are still not "unchanged". + let verdict = fixture + .diff(&partial.snapshot_id, &again.snapshot_id, 0, "") + .await + .unwrap(); + assert_eq!(verdict.status, "indeterminate"); + let verdict = fixture + .diff(&complete.snapshot_id, &partial.snapshot_id, 0, "") + .await + .unwrap(); + assert_eq!(verdict.status, "indeterminate"); + assert!( + verdict.changes.is_empty(), + "the unreadable file is not reported as modified" + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_file_that_changes_while_it_is_read_makes_the_fingerprint_unstable() { + let (fixture, saves) = Fixture::emulator(INSPECT).await; + let root = fixture.approve(INSTALLATION, "save", &saves).await; + let stable = fixture.take("a", &root).await; + + // A game writes the save right after the host read it. + let target = saves.join("states/s1.sav"); + let written = Arc::new(StdMutex::new(false)); + fixture.snapshots.set_hook({ + let (target, written) = (target.clone(), written.clone()); + move |path| { + if path.last().map(String::as_str) == Some("s1.sav") { + *written.lock().unwrap() = true; + std::fs::write(&target, b"state, but longer").unwrap(); + } + } + }); + let unstable = fixture.fingerprint("b", &root, 0).await.unwrap(); + assert!(*written.lock().unwrap()); + assert!(!unstable.complete); + assert_eq!(unstable.consistency, "unstable"); + assert!(unstable.digest.is_empty()); + let verdict = fixture + .diff(&stable.snapshot_id, &unstable.snapshot_id, 0, "") + .await + .unwrap(); + assert_eq!(verdict.status, "indeterminate"); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_cut_walk_is_incomplete() { + let (fixture, saves) = Fixture::emulator(INSPECT).await; + let root = fixture.approve(INSTALLATION, "save", &saves).await; + let cut = fixture.fingerprint("a", &root, 2).await.unwrap(); + assert!(!cut.complete && cut.digest.is_empty()); + let whole = fixture.fingerprint("b", &root, 10).await.unwrap(); + assert!(whole.complete); + assert_eq!( + fixture + .diff(&cut.snapshot_id, &whole.snapshot_id, 0, "") + .await + .unwrap() + .status, + "indeterminate" + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_profile_fingerprints_what_its_rules_select_and_a_new_revision_is_another_place() { + let (fixture, saves) = Fixture::emulator(INSPECT).await; + let root = fixture.approve(INSTALLATION, "save", &saves).await; + let created = fixture + .make( + "p", + profile( + "Cards", + "rt", + vec![directory(&root, "Cards", &["**/*.gci"])], + ), + ) + .await + .unwrap(); + let before = fixture.take("a", &created.profile_id).await; + assert_eq!(before.revision, created.revision); + + // A file the rules do not select changes: the profile's fingerprint does not. + std::fs::write(saves.join("states/s1.sav"), b"STATE").unwrap(); + let same = fixture.take("b", &created.profile_id).await; + assert_eq!(before.digest, same.digest); + // A file they select changes. + std::fs::write(saves.join("GC/USA/card.gci"), b"CARD").unwrap(); + let changed = fixture.take("c", &created.profile_id).await; + assert_ne!(before.digest, changed.digest); + let verdict = fixture + .diff(&before.snapshot_id, &changed.snapshot_id, 0, "") + .await + .unwrap(); + assert_eq!(verdict.status, "changed"); + assert_eq!(verdict.changes[0].relative_path, "d0/GC/USA/card.gci"); + + // The profile is edited: what was taken before is of another revision and cannot be compared. + let edited = fixture + .patch( + "u", + &created.profile_id, + created.revision, + &["name"], + SaveProfile { + name: "Cards 2".into(), + ..SaveProfile::default() + }, + ) + .await + .unwrap(); + let later = fixture.take("d", &created.profile_id).await; + assert_eq!(later.revision, edited.revision); + let verdict = fixture + .diff(&changed.snapshot_id, &later.snapshot_id, 0, "") + .await + .unwrap(); + assert_eq!(verdict.status, "incomparable"); + assert!(verdict.changes.is_empty()); + // Asking at a revision the snapshots are not at is a conflict. + let stale = fixture + .host + .locations_client() + .compare(LocationCompareRequest { + context: Some(fixture.context()), + before_snapshot_id: later.snapshot_id.clone(), + after_snapshot_id: later.snapshot_id.clone(), + expected_revision: created.revision, + page_size: 0, + cursor: String::new(), + }) + .await + .unwrap_err(); + assert_eq!(stale.code(), Code::FailedPrecondition); +} + +#[tokio::test(flavor = "multi_thread")] +async fn snapshots_of_two_places_are_incomparable() { + let (fixture, saves) = Fixture::emulator(INSPECT).await; + let root = fixture.approve(INSTALLATION, "save", &saves).await; + let states = fixture.child(&root, "states").await; + let whole = fixture.take("a", &root).await; + let part = fixture.take("b", &states).await; + let verdict = fixture + .diff(&whole.snapshot_id, &part.snapshot_id, 0, "") + .await + .unwrap(); + assert_eq!(verdict.status, "incomparable"); + // A single file has a fingerprint of its own. + let file = fixture.child(&states, "s1.sav").await; + let one = fixture.take("c", &file).await; + assert!(one.complete && one.digest.len() == 32); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_place_that_is_gone_is_reported_without_a_digest_or_a_job() { + let (fixture, saves) = Fixture::emulator(INSPECT).await; + let root = fixture.approve(INSTALLATION, "save", &saves).await; + let away = saves.with_extension("away"); + std::fs::rename(&saves, &away).unwrap(); + let reply = fixture.fingerprint("a", &root, 0).await.unwrap(); + assert_eq!(reply.availability, InspectionAvailability::Missing as i32); + assert!(reply.job_id.is_empty() && reply.digest.is_empty() && !reply.complete); + assert_eq!(reply.consistency, "unavailable"); + assert!(!saves.exists(), "nothing is created in its place"); + std::fs::rename(&away, &saves).unwrap(); + // The same key asks again, since nothing was started. + assert!(fixture.fingerprint("a", &root, 0).await.unwrap().complete); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_long_fingerprint_answers_with_its_job_and_can_be_cancelled_or_waited_for() { + let (fixture, saves) = Fixture::emulator(INSPECT).await; + let root = fixture.approve(INSTALLATION, "save", &saves).await; + fixture + .snapshots + .set_fast_wait(StdDuration::from_millis(100)); + // The reading is held up until the test lets it go. + let (release, held) = std::sync::mpsc::channel::<()>(); + let held = Arc::new(StdMutex::new(held)); + fixture.snapshots.set_hook({ + let held = held.clone(); + move |_| { + let _ = held + .lock() + .unwrap() + .recv_timeout(StdDuration::from_secs(20)); + } + }); + + let pending = fixture.fingerprint("slow", &root, 0).await.unwrap(); + assert_eq!(pending.consistency, "pending"); + assert!( + !pending.job_id.is_empty() && pending.snapshot_id.is_empty() && pending.digest.is_empty() + ); + assert_eq!( + fixture.job(&pending.job_id).await.unwrap().state(), + JobState::Running + ); + // The plugin may have only one at a time; the retry of the same request is just the job. + assert_eq!( + fixture + .fingerprint("other", &root, 0) + .await + .unwrap_err() + .code(), + Code::ResourceExhausted + ); + assert_eq!( + fixture.fingerprint("slow", &root, 0).await.unwrap().job_id, + pending.job_id + ); + + // Let it go: the job ends and the same key gives the result. + for _ in 0..8 { + let _ = release.send(()); + } + let mut result = pending.clone(); + for _ in 0..200 { + result = fixture.fingerprint("slow", &root, 0).await.unwrap(); + if !result.snapshot_id.is_empty() { + break; + } + tokio::time::sleep(StdDuration::from_millis(25)).await; + } + assert!(result.complete && result.digest.len() == 32, "{result:?}"); + assert_eq!(result.job_id, pending.job_id); + let done = fixture.job(&pending.job_id).await.unwrap(); + assert_eq!( + (done.state(), done.result_code.as_str()), + (JobState::Succeeded, "fingerprint_ready") + ); + assert_eq!(done.message, result.snapshot_id); +} + +#[tokio::test(flavor = "multi_thread")] +async fn cancelling_the_job_stops_the_reading_keeps_nothing_and_frees_the_slot() { + let (fixture, saves) = Fixture::emulator(INSPECT).await; + let root = fixture.approve(INSTALLATION, "save", &saves).await; + fixture + .snapshots + .set_fast_wait(StdDuration::from_millis(100)); + let (release, held) = std::sync::mpsc::channel::<()>(); + let held = Arc::new(StdMutex::new(held)); + fixture.snapshots.set_hook({ + let held = held.clone(); + move |_| { + let _ = held + .lock() + .unwrap() + .recv_timeout(StdDuration::from_secs(20)); + } + }); + let pending = fixture.fingerprint("slow", &root, 0).await.unwrap(); + // Cancel while the first file is being held; only then let the reading go on and see it stop. + let (cancelled, ()) = tokio::join!(fixture.cancel_job("c", &pending.job_id), async { + tokio::time::sleep(StdDuration::from_millis(150)).await; + for _ in 0..8 { + let _ = release.send(()); + } + }); + let cancelled = cancelled.unwrap(); + assert_eq!(cancelled.state(), JobState::Cancelled); + + let reply = fixture.fingerprint("slow", &root, 0).await.unwrap(); + assert_eq!( + (reply.consistency.as_str(), reply.snapshot_id.as_str()), + ("cancelled", "") + ); + // Nothing of it was kept, and the plugin may take a new one at once. + fixture.snapshots.set_hook(|_| {}); + assert!(fixture.take("fresh", &root).await.complete); +} + +#[tokio::test(flavor = "multi_thread")] +async fn the_permission_and_the_owner_of_a_fingerprint_are_checked() { + let (fixture, saves) = Fixture::emulator(INSPECT).await; + let root = fixture.approve(INSTALLATION, "save", &saves).await; + let taken = fixture.take("a", &root).await; + // A fingerprint that is not this plugin's, or not at all, is not found. + assert_eq!( + fixture + .diff("snap-nothing", &taken.snapshot_id, 0, "") + .await + .unwrap_err() + .code(), + Code::NotFound + ); + assert_eq!( + fixture + .fingerprint("b", "forged", 0) + .await + .unwrap_err() + .code(), + Code::NotFound + ); + // Without the permission of the place, neither taking nor comparing works. + fixture + .api + .revoke_session_permission("fixture", cap::GAME_SAVES_INSPECT) + .await; + assert_eq!( + fixture.fingerprint("c", &root, 0).await.unwrap_err().code(), + Code::PermissionDenied + ); + assert_eq!( + fixture + .diff(&taken.snapshot_id, &taken.snapshot_id, 0, "") + .await + .unwrap_err() + .code(), + Code::PermissionDenied + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn hashing_needs_no_file_permission_and_changes_nothing() { + let (fixture, saves) = Fixture::emulator(INSPECT).await; + let root = fixture.approve(INSTALLATION, "save", &saves).await; + let file = saves.join("states/s1.sav"); + set_time(&file, 1_650_000_000); + let before = std::fs::metadata(&file).unwrap(); + fixture + .api + .revoke_session_permission("fixture", cap::FILES_READ) + .await; + let taken = fixture.take("a", &root).await; + assert!(taken.complete); + let after = std::fs::metadata(&file).unwrap(); + assert_eq!(after.modified().unwrap(), before.modified().unwrap()); + assert_eq!(std::fs::read(&file).unwrap(), b"state"); + assert_eq!( + fixture.ls(&root).await.unwrap_err().code(), + Code::PermissionDenied + ); +} + +const RUNTIME_INSPECT: &[&str] = &[ + cap::GAME_STORAGE_INSPECT, + cap::GAME_SAVES_INSPECT, + cap::GAME_RUNTIME_CREATE, + cap::GAME_RUNTIME_READ, + cap::FILES_READ, +]; + +#[tokio::test(flavor = "multi_thread")] +async fn a_runtime_executable_is_fingerprinted_freshly_and_compared_without_its_path() { + let (fixture, runtime, dir) = Fixture::approved_runtime(RUNTIME_INSPECT).await; + let executable = dir.join("emulator"); + set_time(&executable, 1_600_000_000); + let handle = runtime.executable_handle; + assert!(!handle.contains('/') && !handle.contains(dir.to_str().unwrap())); + + let first = fixture.take("a", &handle).await; + assert_eq!(first.consistency, "best_effort"); + assert_eq!( + first.digest, + tree_digest(&[Record { + label: "emulator".into(), + approval_id: String::new(), + path: vec![], + directory: false, + size: 6, + digest: Some(sha(b"binary")), + unreadable: false, + unstable: false, + }]) + .to_vec() + ); + // The job is the existing one; the same key answers with the stored snapshot. + assert!(!first.job_id.is_empty()); + let replay = fixture.fingerprint("a", &handle, 0).await.unwrap(); + assert_eq!( + (replay.snapshot_id.as_str(), replay.digest), + (first.snapshot_id.as_str(), first.digest.clone()) + ); + assert!(!format!("{first:?}").contains(dir.to_str().unwrap())); + + // The bytes change while size and modification time stay the same. + std::fs::write(&executable, b"BINARY").unwrap(); + set_time(&executable, 1_600_000_000); + let second = fixture.take("b", &handle).await; + assert_ne!(first.digest, second.digest); + let changed = fixture + .diff(&first.snapshot_id, &second.snapshot_id, 0, "") + .await + .unwrap(); + assert_eq!(changed.status, "changed"); + let change = changed.changes.first().unwrap(); + assert_eq!(changed.changes.len(), 1); + assert_eq!( + ( + change.change_kind.as_str(), + change.relative_path.as_str(), + change.previous_size_bytes, + change.current_size_bytes + ), + ("modified", "emulator", 6, 6) + ); + assert!(!change.entry_handle.is_empty() && !change.entry_handle.contains('/')); + assert!(!format!("{changed:?}").contains(dir.to_str().unwrap())); + // The entry handle is good for another fingerprint of the same runtime file. + assert!(fixture.take("c", &change.entry_handle).await.complete); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_runtime_fingerprint_is_fenced_by_its_session_approval_and_scope() { + let (fixture, runtime, dir) = Fixture::approved_runtime(RUNTIME_INSPECT).await; + let handle = runtime.executable_handle; + let caller = fixture.caller(); + let approval_id = fixture + .storage + .run_for_host( + caller.namespace.as_ref().unwrap(), + caller.profile_epoch, + |namespace| { + Ok(namespace + .approval_for(INSTALLATION, "installation")? + .unwrap() + .id) + }, + ) + .await + .unwrap(); + + // Forged and foreign-session handles are the same answer. + let foreign = + fixture + .files + .seal_handle("another-session", &approval_id, &["emulator".to_owned()]); + for denied in [ + fixture.fingerprint("f", "forged", 0).await.unwrap_err(), + fixture.fingerprint("g", &foreign, 0).await.unwrap_err(), + ] { + assert_eq!(denied.code(), Code::NotFound); + assert!(!denied.message().contains(dir.to_str().unwrap())); + } + + // A new game in the same folder changes the confirmed scope. + fixture.library_in(&[ + ("fixture:1", Some(3), "Emulated", &dir), + ("fixture:2", Some(4), "Also here", &dir), + ]); + assert_eq!( + fixture + .fingerprint("h", &handle, 0) + .await + .unwrap_err() + .code(), + Code::FailedPrecondition + ); + + // The approval going away fences the place. + fixture + .storage + .run_for_host( + caller.namespace.as_ref().unwrap(), + caller.profile_epoch, + move |namespace| namespace.revoke_approval(&approval_id), + ) + .await + .unwrap(); + assert_eq!( + fixture + .fingerprint("i", &handle, 0) + .await + .unwrap_err() + .code(), + Code::NotFound + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_runtime_fingerprint_needs_inspection_not_file_read() { + let (fixture, runtime, _) = Fixture::approved_runtime(RUNTIME_INSPECT).await; + let handle = runtime.executable_handle; + assert!(fixture.take("a", &handle).await.complete); + + fixture + .api + .revoke_session_permission("fixture", cap::FILES_READ) + .await; + assert!(fixture.take("b", &handle).await.complete); + + fixture + .api + .revoke_session_permission("fixture", cap::GAME_STORAGE_INSPECT) + .await; + assert_eq!( + fixture + .fingerprint("c", &handle, 0) + .await + .unwrap_err() + .code(), + Code::PermissionDenied + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn describe_api_lists_the_fingerprint_methods() { + let (fixture, _) = Fixture::emulator(INSPECT).await; + let described = fixture.host.describe_api().await.unwrap(); + let served: Vec<_> = described + .methods + .iter() + .filter(|method| method.service == "Locations") + .map(|method| method.method.as_str()) + .collect(); + assert_eq!( + served, + [ + "Inspect", + "WatchAvailability", + "GetSize", + "GetAccess", + "GetLastModified", + "GetFingerprint", + "Compare" + ] + ); +} diff --git a/crates/app/src/plugin_host/resources/tests/games.rs b/crates/app/src/plugin_host/resources/tests/games.rs new file mode 100644 index 000000000..a0a878c37 --- /dev/null +++ b/crates/app/src/plugin_host/resources/tests/games.rs @@ -0,0 +1,3499 @@ +//! `GamesRequestLaunch` and `GamesRequestInstall` over the real local socket (tasks 7.2 and +//! 10.10): the user's intent, the dialog, remembered confirmations and the scope per game. + +use std::collections::VecDeque; +use std::sync::Mutex as StdMutex; + +use tokio::sync::Notify; + +use super::*; +use crate::plugin_host::intents::{Answer, Binding, ConfirmationRequest, Operation, Prompter}; +use crate::plugin_host::jobs::JobOwner; + +const GRANTS: &[&str] = &[cap::GAME_LAUNCH, cap::GAMES_INSTALL]; +const ENTRY: &str = "fixture:1"; +const INSTALLATION: &str = "id-fixture:1"; + +/// The user's side of the dialog: answers in order (declining by default), optionally held until +/// the test lets it go, remembering what it was shown. +#[derive(Default)] +pub(super) struct Dialog { + answers: StdMutex>, + shown: StdMutex>, + held: Option>, +} + +#[tonic::async_trait] +impl Prompter for Dialog { + async fn confirm(&self, request: ConfirmationRequest) -> Result { + self.shown.lock().unwrap().push(request); + if let Some(gate) = &self.held { + gate.notified().await; + } + Ok(self.answers.lock().unwrap().pop_front().unwrap_or(Answer { + approved: false, + remember: false, + })) + } +} + +pub(super) const APPROVE: Answer = Answer { + approved: true, + remember: false, +}; +const APPROVE_AND_REMEMBER: Answer = Answer { + approved: true, + remember: true, +}; +const DECLINE: Answer = Answer { + approved: false, + remember: false, +}; + +/// A profile the user-Play path can resolve for the fixture plugin, with a fresh state layout. +async fn selected_recipe_profile( + fixture: &Fixture, + layout_name: &str, + permissions: &[&'static str], +) -> ( + crate::plugin_host::profile::PluginStateLayout, + crate::plugin_host::grants::PluginIdentity, + String, +) { + use crate::plugin_host::grants::{ + GrantScope, PermissionDecision, PermissionRequest, PluginIdentity, + }; + use crate::plugin_host::profile::PluginStateLayout; + + let profiles = fixture.api.profiles(); + let layout = PluginStateLayout::new(fixture.plugin_data.join(layout_name)); + profiles.set_state_layout(layout.clone()); + let profile = profiles.current().unwrap(); + let identity = PluginIdentity { + plugin_id: "fixture.plugin".into(), + publisher_fingerprint: "ab".repeat(32), + profile_id: profile.profile_id().to_owned(), + }; + let scope = GrantScope::Declared { + value: "host-selected-game".into(), + }; + let requests = permissions + .iter() + .map(|permission_id| PermissionRequest { + permission_id: (*permission_id).into(), + required: false, + allowed_scopes: [scope.clone()].into(), + }) + .collect::>(); + let decisions = permissions + .iter() + .map(|permission_id| PermissionDecision { + permission_id: (*permission_id).into(), + scope: scope.clone(), + granted: true, + }) + .collect::>(); + layout + .open_grants(&profile) + .unwrap() + .replace_grants(identity.clone(), &requests, &decisions) + .unwrap(); + layout + .open_activation(&profile) + .unwrap() + .set_enabled(&identity.plugin_id, true) + .unwrap(); + let owner = profiles + .resolver(&identity.plugin_id, &identity.publisher_fingerprint, None) + .unwrap() + .library_recipe_owner_key(); + (layout, identity, owner) +} + +impl Fixture { + /// A fixture with one own entry, a fake engine side and (when `dialog` is given) a dialog. + async fn game( + grants: &[&'static str], + dialog: Option, + ) -> (Self, Arc, Option>) { + let fixture = Self::new(grants).await; + fixture.library(&[(ENTRY, Some(3), "Game"), ("steam:1", Some(5), "Other")]); + let host = fixture.with_host(); + let dialog = dialog.map(Arc::new); + if let Some(dialog) = &dialog { + fixture.intents.set_prompter(dialog.clone()); + } + (fixture, host, dialog) + } + + pub(super) async fn extension_game( + grants: &[&'static str], + target: TargetGameContext, + dialog: Option, + ) -> (Self, Arc, Option>) { + let fixture = Fixture::start_with_target(grants, true, None, Some(target)).await; + fixture.library(&[ + ("steam:1", Some(5), "Selected Steam game"), + ("steam:2", Some(6), "Other Steam game"), + ("manual:1", Some(9), "Manual game"), + ]); + let host = fixture.with_host(); + let dialog = dialog.map(Arc::new); + if let Some(dialog) = &dialog { + fixture.intents.set_prompter(dialog.clone()); + } + (fixture, host, dialog) + } + + /// An extension fixture whose launch action the user has approved, for flows that need the + /// host-issued target context outside the launch tests themselves. + pub(super) async fn approved_extension_game( + grants: &[&'static str], + target: TargetGameContext, + ) -> (Self, Arc) { + let (fixture, host, _) = + Self::extension_game(grants, target, Some(answering(&[APPROVE]))).await; + (fixture, host) + } + + /// The revision of the fixture's own entry, as the host holds it. + async fn revision(&self) -> u64 { + let own = Scope { + own_provider: "fixture".into(), + read_all: false, + provider_filter: None, + }; + self.feed.target(&own, INSTALLATION).unwrap().1.revision + } + + async fn launch_game(&self, key: &str, intent: &str) -> Result { + let revision = self.revision().await; + self.launch_at(key, INSTALLATION, revision, intent).await + } + + async fn launch_at( + &self, + key: &str, + installation_id: &str, + expected_revision: u64, + intent: &str, + ) -> Result { + self.client() + .games_request_launch(GameLaunchRequest { + context: Some(self.context()), + game_id: String::new(), + installation_id: installation_id.into(), + expected_revision, + user_intent_id: intent.into(), + idempotency_key: key.into(), + }) + .await + .map(Response::into_inner) + } + + async fn install_game(&self, key: &str, intent: &str) -> Result { + self.client() + .games_request_install(GameInstallRequest { + context: Some(self.context()), + game_id: String::new(), + installation_id: INSTALLATION.into(), + user_intent_id: intent.into(), + idempotency_key: key.into(), + }) + .await + .map(Response::into_inner) + } + + /// What the host binds an intent to for the fixture's own entry. + async fn binding(&self, operation: Operation, target_revision: u64) -> Binding { + self.binding_for(operation, target_revision, "3", INSTALLATION, "") + .await + } + + async fn binding_for( + &self, + operation: Operation, + target_revision: u64, + game_id: &str, + installation_id: &str, + recipe_id: &str, + ) -> Binding { + let permission = match operation { + Operation::Launch => cap::GAME_LAUNCH, + Operation::CustomLaunch => cap::GAME_CUSTOM_LAUNCH, + Operation::Install => cap::GAMES_INSTALL, + Operation::BackupRestore => cap::BACKUPS_RESTORE, + Operation::RuntimeSessionContext => cap::GAME_SESSIONS_REPORT, + }; + let caller = self + .api + .authorize_resource(Some(&self.context()), permission) + .unwrap(); + let (_, entry) = self + .feed + .target( + &super::super::Scope { + own_provider: caller.provider_id.clone(), + read_all: true, + provider_filter: None, + }, + installation_id, + ) + .unwrap(); + let (recipe, dispatch, resources) = if operation == Operation::CustomLaunch { + let host = self.feed.host().unwrap(); + let recipe = host + .custom_launch_recipe( + super::super::mutations::mutation_owner(&caller), + recipe_id.to_owned(), + ) + .await + .unwrap() + .unwrap(); + let dispatch = host + .prepare_custom_launch(recipe.clone(), None, None, None) + .await + .unwrap(); + (Some(recipe), Some(dispatch), Vec::new()) + } else { + (None, None, Vec::new()) + }; + let plan = super::super::super::launch_plan::resolve( + &caller, + &entry, + target_revision, + recipe.as_ref(), + dispatch.as_ref(), + &resources, + ) + .unwrap(); + let plan_fingerprint = if matches!(operation, Operation::Launch | Operation::CustomLaunch) { + plan.fingerprint().unwrap() + } else { + String::new() + }; + Binding { + plugin_id: "fixture.plugin".into(), + publisher_fingerprint: "ab".repeat(32), + profile_epoch: caller.profile_epoch, + game_id: game_id.into(), + installation_id: installation_id.into(), + operation, + target_revision, + recipe_id: recipe_id.into(), + recipe_revision: u64::from(operation == Operation::CustomLaunch), + plan_fingerprint, + } + } + + fn game_owner(&self) -> JobOwner { + let permission = [ + cap::GAME_LAUNCH, + cap::GAME_CUSTOM_LAUNCH, + cap::GAMES_INSTALL, + cap::BACKUPS_RESTORE, + ] + .into_iter() + .find(|permission| self.capabilities.contains(permission)) + .expect("game fixture needs an action grant"); + JobOwner::of( + &self + .api + .authorize_resource(Some(&self.context()), permission) + .unwrap(), + ) + .unwrap() + } + + /// Waits until the job is over, reading the host's own record. + async fn ended(&self, id: &str) -> JobReply { + self.ended_for(&self.game_owner(), id).await + } + + async fn ended_for(&self, owner: &JobOwner, id: &str) -> JobReply { + for _ in 0..400 { + let reply = self.jobs.get(owner, id).unwrap(); + if !matches!(reply.state(), JobState::Queued | JobState::Running) { + return reply; + } + tokio::time::sleep(Duration::from_millis(5)).await; + } + panic!("the job did not end"); + } + + async fn dialog_shown(dialog: &Dialog, count: usize) { + for _ in 0..400 { + if dialog.shown.lock().unwrap().len() >= count { + return; + } + tokio::time::sleep(Duration::from_millis(5)).await; + } + panic!("the dialog was not shown"); + } +} + +fn held(answers: &[Answer]) -> (Dialog, Arc) { + let gate = Arc::new(Notify::new()); + ( + Dialog { + answers: StdMutex::new(answers.iter().copied().collect()), + held: Some(gate.clone()), + ..Dialog::default() + }, + gate, + ) +} + +pub(super) fn answering(answers: &[Answer]) -> Dialog { + Dialog { + answers: StdMutex::new(answers.iter().copied().collect()), + ..Dialog::default() + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn without_an_intent_the_job_waits_for_the_user_and_an_approval_starts_the_game() { + let (dialog, gate) = held(&[APPROVE]); + let (fixture, host, dialog) = Fixture::game(GRANTS, Some(dialog)).await; + let dialog = dialog.unwrap(); + + let reply = fixture.launch_game("one", "").await.unwrap(); + assert_eq!( + (reply.state(), reply.message.as_str()), + (JobState::Queued, "awaiting confirmation") + ); + Fixture::dialog_shown(&dialog, 1).await; + // Nothing starts while the user has not answered. + assert!(host.opened.lock().unwrap().is_empty()); + let shown = dialog.shown.lock().unwrap()[0].clone(); + assert_eq!( + ( + shown.plugin_id.as_str(), + shown.game_name.as_str(), + shown.operation + ), + ("fixture.plugin", "Game", Operation::Launch) + ); + assert_eq!( + fixture.job(&reply.job_id).await.unwrap().state(), + JobState::Queued + ); + + gate.notify_one(); + let done = fixture.ended(&reply.job_id).await; + assert_eq!( + (done.state(), done.result_code.as_str()), + (JobState::Succeeded, "opened") + ); + assert_eq!(*host.opened.lock().unwrap(), [(ENTRY.to_owned(), false)]); +} + +#[tokio::test(flavor = "multi_thread")] +async fn declining_starts_nothing() { + let (fixture, host, _) = Fixture::game(GRANTS, Some(answering(&[]))).await; + let reply = fixture.launch_game("one", "").await.unwrap(); + let done = fixture.ended(&reply.job_id).await; + assert_eq!( + (done.state(), done.result_code.as_str()), + (JobState::Failed, "declined") + ); + assert!(host.opened.lock().unwrap().is_empty()); +} + +#[tokio::test(flavor = "multi_thread")] +async fn cancelling_a_waiting_request_withdraws_it_and_frees_the_game() { + let (dialog, gate) = held(&[APPROVE]); + let (fixture, host, dialog) = Fixture::game(GRANTS, Some(dialog)).await; + let dialog = dialog.unwrap(); + let reply = fixture.launch_game("one", "").await.unwrap(); + Fixture::dialog_shown(&dialog, 1).await; + + // One dialog per game at a time: another request while it waits is refused. + assert_eq!( + fixture.launch_game("two", "").await.unwrap_err().code(), + Code::FailedPrecondition + ); + let withdrawn = fixture.cancel_job("c", &reply.job_id).await.unwrap(); + assert_eq!(withdrawn.state(), JobState::Cancelled); + // A late approval changes nothing. + gate.notify_one(); + tokio::time::sleep(Duration::from_millis(50)).await; + assert!(host.opened.lock().unwrap().is_empty()); + // The slot is free again. + let again = fixture.launch_game("three", "").await.unwrap(); + assert_eq!(again.state(), JobState::Queued); +} + +#[tokio::test(flavor = "multi_thread")] +async fn cancelling_an_install_review_prevents_the_provider_install_flow() { + let (dialog, gate) = held(&[APPROVE]); + let (fixture, host, dialog) = Fixture::game(GRANTS, Some(dialog)).await; + let reply = fixture.install_game("cancel-install", "").await.unwrap(); + Fixture::dialog_shown(&dialog.unwrap(), 1).await; + + assert_eq!(reply.message, "awaiting confirmation"); + assert!(host.opened.lock().unwrap().is_empty()); + let cancelled = fixture + .cancel_job("cancel-install-job", &reply.job_id) + .await + .unwrap(); + assert_eq!(cancelled.state(), JobState::Cancelled); + gate.notify_one(); + tokio::time::sleep(Duration::from_millis(50)).await; + assert!(host.opened.lock().unwrap().is_empty()); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_pre_issued_install_intent_skips_only_the_plugin_prompt() { + // Core's explicit action supplies an install intent; the request still enters the provider's + // install flow and has no launch target revision to validate or bind. + let (fixture, host, _) = Fixture::game(GRANTS, None).await; + let binding = fixture.binding(Operation::Install, 0).await; + let id = fixture.intents.issue(binding).unwrap(); + let reply = fixture + .install_game("preissued-install", &id) + .await + .unwrap(); + let done = fixture.ended(&reply.job_id).await; + assert_eq!( + (done.state(), done.result_code.as_str()), + (JobState::Succeeded, "opened") + ); + assert_eq!(*host.opened.lock().unwrap(), [(ENTRY.to_owned(), true)]); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_remembered_install_confirmation_is_scoped_to_install() { + let (fixture, host, dialog) = + Fixture::game(GRANTS, Some(answering(&[APPROVE_AND_REMEMBER, APPROVE]))).await; + let dialog = dialog.unwrap(); + + let first = fixture + .install_game("remember-install-one", "") + .await + .unwrap(); + assert_eq!(first.message, "awaiting confirmation"); + assert_eq!( + fixture.ended(&first.job_id).await.state(), + JobState::Succeeded + ); + assert_eq!(dialog.shown.lock().unwrap().len(), 1); + + let remembered = fixture + .install_game("remember-install-two", "") + .await + .unwrap(); + assert_ne!(remembered.message, "awaiting confirmation"); + assert_eq!( + fixture.ended(&remembered.job_id).await.state(), + JobState::Succeeded + ); + assert_eq!(dialog.shown.lock().unwrap().len(), 1); + assert_eq!(host.opened.lock().unwrap().len(), 2); + + // The same stored approval does not authorize launch. + let launch = fixture + .launch_game("remember-install-launch", "") + .await + .unwrap(); + assert_eq!(launch.message, "awaiting confirmation"); + assert_eq!(dialog.shown.lock().unwrap().len(), 2); +} + +#[tokio::test(flavor = "multi_thread")] +async fn revocation_during_install_review_prevents_dispatch() { + let (dialog, gate) = held(&[APPROVE]); + let (fixture, host, dialog) = Fixture::game(GRANTS, Some(dialog)).await; + let owner = fixture.game_owner(); + let reply = fixture.install_game("revoke-install", "").await.unwrap(); + Fixture::dialog_shown(&dialog.unwrap(), 1).await; + + fixture + .api + .revoke_session_permission("fixture", cap::GAMES_INSTALL) + .await; + gate.notify_one(); + let done = fixture.ended_for(&owner, &reply.job_id).await; + assert_eq!(done.state(), JobState::Failed); + assert!(host.opened.lock().unwrap().is_empty()); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_retry_opens_no_second_dialog() { + let (dialog, gate) = held(&[APPROVE]); + let (fixture, host, dialog) = Fixture::game(GRANTS, Some(dialog)).await; + let dialog = dialog.unwrap(); + let first = fixture.launch_game("same", "").await.unwrap(); + Fixture::dialog_shown(&dialog, 1).await; + let retry = fixture.launch_game("same", "").await.unwrap(); + assert_eq!(retry.job_id, first.job_id); + gate.notify_one(); + fixture.ended(&first.job_id).await; + // Even after it ended, the same request is still the same job. + assert_eq!( + fixture.launch_game("same", "").await.unwrap().job_id, + first.job_id + ); + assert_eq!(dialog.shown.lock().unwrap().len(), 1); + assert_eq!(host.opened.lock().unwrap().len(), 1); +} + +#[tokio::test(flavor = "multi_thread")] +async fn custom_launch_recipes_are_idempotent_requestable_and_removable() { + let (fixture, host, _) = Fixture::game( + &[cap::GAME_LAUNCH, cap::GAME_CUSTOM_LAUNCH], + Some(answering(&[APPROVE])), + ) + .await; + host.launch_target.store(1, Ordering::SeqCst); + let revision = fixture.revision().await; + let proposal = CustomLaunchRequest { + context: Some(fixture.context()), + game_id: "3".into(), + installation_id: INSTALLATION.into(), + expected_revision: revision, + idempotency_key: "propose-custom-1".into(), + uri: "steam://rungameid/3".into(), + ..CustomLaunchRequest::default() + }; + + let first = fixture + .client() + .games_propose_custom_launch(proposal.clone()) + .await + .unwrap() + .into_inner(); + let replay = fixture + .client() + .games_propose_custom_launch(proposal.clone()) + .await + .unwrap() + .into_inner(); + assert_eq!(replay.recipe_id, first.recipe_id); + assert_eq!(replay.recipe_revision, first.recipe_revision); + assert_eq!(host.custom_launch_recipes.lock().unwrap().len(), 1); + + let mut changed = proposal; + changed.uri = "steam://rungameid/4".into(); + assert_eq!( + fixture + .client() + .games_propose_custom_launch(changed) + .await + .unwrap_err() + .code(), + Code::FailedPrecondition + ); + + let intent = fixture + .intents + .issue( + fixture + .binding_for( + Operation::CustomLaunch, + 1, + "3", + INSTALLATION, + &first.recipe_id, + ) + .await, + ) + .unwrap(); + let request = CustomLaunchRequest { + context: Some(fixture.context()), + game_id: "3".into(), + installation_id: INSTALLATION.into(), + expected_revision: revision, + user_intent_id: intent, + idempotency_key: "execute-custom-1".into(), + recipe_id: first.recipe_id.clone(), + recipe_revision: first.recipe_revision, + ..CustomLaunchRequest::default() + }; + let reply = fixture + .client() + .games_request_custom_launch(request) + .await + .unwrap() + .into_inner(); + assert_eq!( + fixture.ended(&reply.job_id).await.state(), + JobState::Succeeded + ); + assert!(matches!( + host.custom_launch_dispatches.lock().unwrap().as_slice(), + [crate::plugin_host::library::CustomLaunchDispatch::Uri { uri, .. }] + if uri.as_str() == "steam://rungameid/3" + )); + + let removed = fixture + .client() + .games_remove_custom_launch(CustomLaunchRemoveRequest { + mutation: Some(fixture.mutation("remove-custom-1", first.recipe_revision)), + game_id: "3".into(), + recipe_id: first.recipe_id, + }) + .await + .unwrap() + .into_inner(); + assert_eq!(removed.outcome, MutationOutcome::Applied as i32); + assert!(host.custom_launch_recipes.lock().unwrap().is_empty()); +} + +#[tokio::test(flavor = "multi_thread")] +async fn user_play_reviews_selected_recipe_remembers_exact_plan_and_never_falls_back() { + let (fixture, host, dialog) = Fixture::game( + &[cap::GAME_LAUNCH, cap::GAME_CUSTOM_LAUNCH], + Some(answering(&[APPROVE_AND_REMEMBER])), + ) + .await; + host.launch_target.store(1, Ordering::SeqCst); + + let profiles = fixture.api.profiles(); + let layout = crate::plugin_host::profile::PluginStateLayout::new( + fixture.plugin_data.join("host-launch-profile"), + ); + profiles.set_state_layout(layout.clone()); + let profile = profiles.current().unwrap(); + let identity = crate::plugin_host::grants::PluginIdentity { + plugin_id: "fixture.plugin".into(), + publisher_fingerprint: "ab".repeat(32), + profile_id: profile.profile_id().to_owned(), + }; + let scope = crate::plugin_host::grants::GrantScope::Declared { + value: "host-selected-game".into(), + }; + let request = crate::plugin_host::grants::PermissionRequest { + permission_id: cap::GAME_CUSTOM_LAUNCH.into(), + required: false, + allowed_scopes: [scope.clone()].into(), + }; + layout + .open_grants(&profile) + .unwrap() + .replace_grants( + identity.clone(), + &[request], + &[crate::plugin_host::grants::PermissionDecision { + permission_id: cap::GAME_CUSTOM_LAUNCH.into(), + scope, + granted: true, + }], + ) + .unwrap(); + layout + .open_activation(&profile) + .unwrap() + .set_enabled(&identity.plugin_id, true) + .unwrap(); + + let revision = fixture.revision().await; + let recipe = fixture + .client() + .games_propose_custom_launch(CustomLaunchRequest { + context: Some(fixture.context()), + game_id: "3".into(), + installation_id: INSTALLATION.into(), + expected_revision: revision, + idempotency_key: "host-play-recipe".into(), + uri: "steam://rungameid/3".into(), + ..CustomLaunchRequest::default() + }) + .await + .unwrap() + .into_inner(); + let resolver = profiles + .resolver("fixture.plugin", &"ab".repeat(32), None) + .unwrap(); + host.launch_recipe_selections.lock().unwrap().insert( + "fixture:3".into(), + gamenode_core::library::LaunchRecipeSelection { + entry_key: "fixture:3".into(), + owner_key: resolver.library_recipe_owner_key(), + plugin_id: identity.plugin_id.clone(), + publisher_fingerprint: identity.publisher_fingerprint.clone(), + recipe_id: recipe.recipe_id, + recipe_revision: recipe.recipe_revision, + base_target_revision: 1, + approved_plan_fingerprint: String::new(), + }, + ); + + let api = fixture._server.resource_api(); + assert!( + api.launch_selected_recipe("fixture:3".into()) + .await + .unwrap() + ); + let shown = dialog.as_ref().unwrap().shown.lock().unwrap().clone(); + assert_eq!(shown.len(), 1); + let reviewed = shown[0].launch_plan.as_ref().unwrap(); + assert_eq!(reviewed.source_id, "fixture"); + assert_eq!(reviewed.target, "steam://rungameid/3"); + assert!(!reviewed.fingerprint.is_empty()); + + // The exact same plan uses the user-approved fingerprint and does not prompt again. + assert!( + api.launch_selected_recipe("fixture:3".into()) + .await + .unwrap() + ); + assert_eq!(dialog.as_ref().unwrap().shown.lock().unwrap().len(), 1); + assert_eq!(host.custom_launch_dispatches.lock().unwrap().len(), 2); + + // A changed detected target invalidates the selected recipe and blocks all dispatch. + host.launch_target.store(2, Ordering::SeqCst); + assert_eq!( + api.launch_selected_recipe("fixture:3".into()) + .await + .unwrap_err() + .code(), + Code::FailedPrecondition + ); + assert_eq!(host.custom_launch_dispatches.lock().unwrap().len(), 2); + + // Revoking custom-launch permission after approval is also fail-closed. + let revoked_request = crate::plugin_host::grants::PermissionRequest { + permission_id: cap::GAME_CUSTOM_LAUNCH.into(), + required: false, + allowed_scopes: [crate::plugin_host::grants::GrantScope::Declared { + value: "host-selected-game".into(), + }] + .into(), + }; + layout + .open_grants(&profile) + .unwrap() + .replace_grants(identity, &[revoked_request], &[]) + .unwrap(); + host.launch_target.store(1, Ordering::SeqCst); + assert_eq!( + api.launch_selected_recipe("fixture:3".into()) + .await + .unwrap_err() + .code(), + Code::PermissionDenied + ); + assert_eq!(host.custom_launch_dispatches.lock().unwrap().len(), 2); +} + +#[tokio::test(flavor = "multi_thread")] +async fn user_play_reviews_runtime_overlay_and_reprompts_when_runtime_revision_changes() { + use crate::plugin_host::profile::PluginStateLayout; + use gamenode_plugin_protocol::proto::{ + ContentPathArgument, RuntimeArgumentTemplate as RuntimeArgumentProto, RuntimeRecord, + runtime_argument_template::Value as RuntimeArgumentValue, + }; + + let target = TargetGameContext { + game_id: "5".into(), + installation_id: "id-steam:1".into(), + profile_id: "account-a".into(), + revision: "1".into(), + }; + let (fixture, host, dialog) = Fixture::extension_game( + &[ + cap::DISCOVERY, + cap::FILES_READ, + cap::GAME_CUSTOM_LAUNCH, + cap::GAME_RUNTIME_CREATE, + ], + target, + Some(answering(&[ + APPROVE_AND_REMEMBER, + Answer { + approved: false, + remember: false, + }, + ])), + ) + .await; + let dialog = dialog.unwrap(); + host.launch_target.store(1, Ordering::SeqCst); + + let content_root = fixture.game_dir( + "steam-runtime", + &[("zelda.sfc", b"rom"), ("emulator", b"runtime")], + ); + fixture.library_in(&[("steam:1", Some(5), "Selected Steam game", &content_root)]); + fixture.user_approving(&content_root); + let root = fixture.root_handle("id-steam:1", &["read"]).await; + let runtime_executable = fixture.child(&root, "emulator").await; + let content_handle = fixture.child(&root, "zelda.sfc").await; + let context = fixture.context(); + let caller = fixture + .api + .authorize_resource(Some(&context), cap::GAME_RUNTIME_CREATE) + .unwrap(); + let owner = super::super::mutations::mutation_owner(&caller); + + fixture + .client() + .runtimes_register(RuntimeRegisterRequest { + mutation: Some(fixture.mutation("register-runtime-for-play", 0)), + runtime: Some(RuntimeRecord { + id: "runtime:snes".into(), + name: "SNES runtime".into(), + version: "1.0".into(), + executable_handle: runtime_executable, + supported_formats: vec!["snes-rom".into()], + platform: std::env::consts::OS.into(), + argument_template: vec![RuntimeArgumentProto { + value: Some(RuntimeArgumentValue::ContentPath(ContentPathArgument {})), + }], + ..Default::default() + }), + }) + .await + .unwrap(); + fixture + .client() + .games_register_content(ContentRegistrationRequest { + mutation: Some(fixture.mutation("register-content-for-play", 0)), + game_id: "5".into(), + installation_id: "id-steam:1".into(), + content_handle, + content_kind: "snes-rom".into(), + runtime_id: "runtime:snes".into(), + supported_platforms: vec![std::env::consts::OS.into()], + content_id: "rom:zelda".into(), + }) + .await + .unwrap(); + + let revision = fixture.feed.revision_of("steam:1").unwrap(); + let recipe = fixture + .client() + .games_propose_custom_launch(CustomLaunchRequest { + context: Some(context), + game_id: "5".into(), + installation_id: "id-steam:1".into(), + expected_revision: revision, + idempotency_key: "runtime-recipe-for-play".into(), + runtime_handle: "runtime:snes".into(), + content_id: "rom:zelda".into(), + argv: vec!["--pixel-perfect".into()], + environment_set: [("GAME_MODE".into(), "fixture".into())].into(), + ..Default::default() + }) + .await + .unwrap() + .into_inner(); + let profiles = fixture.api.profiles(); + let layout = PluginStateLayout::new(fixture.plugin_data.join("host-runtime-play-profile")); + profiles.set_state_layout(layout.clone()); + let profile = profiles.current().unwrap(); + let identity = crate::plugin_host::grants::PluginIdentity { + plugin_id: "fixture.plugin".into(), + publisher_fingerprint: "ab".repeat(32), + profile_id: profile.profile_id().to_owned(), + }; + let scope = crate::plugin_host::grants::GrantScope::Declared { + value: "host-selected-game".into(), + }; + let requests = [cap::GAME_CUSTOM_LAUNCH, cap::FILES_READ] + .into_iter() + .map( + |permission_id| crate::plugin_host::grants::PermissionRequest { + permission_id: permission_id.into(), + required: false, + allowed_scopes: [scope.clone()].into(), + }, + ) + .collect::>(); + let decisions = [cap::GAME_CUSTOM_LAUNCH, cap::FILES_READ] + .into_iter() + .map( + |permission_id| crate::plugin_host::grants::PermissionDecision { + permission_id: permission_id.into(), + scope: scope.clone(), + granted: true, + }, + ) + .collect::>(); + layout + .open_grants(&profile) + .unwrap() + .replace_grants(identity.clone(), &requests, &decisions) + .unwrap(); + layout + .open_activation(&profile) + .unwrap() + .set_enabled("fixture.plugin", true) + .unwrap(); + let resolver = profiles + .resolver("fixture.plugin", &"ab".repeat(32), None) + .unwrap(); + let stored_recipe = host + .custom_launch_recipe( + resolver.library_recipe_owner_key(), + recipe.recipe_id.clone(), + ) + .await + .unwrap() + .unwrap(); + host.launch_recipe_selections.lock().unwrap().insert( + "steam:1".into(), + gamenode_core::library::LaunchRecipeSelection { + entry_key: "steam:1".into(), + owner_key: resolver.library_recipe_owner_key(), + plugin_id: identity.plugin_id, + publisher_fingerprint: identity.publisher_fingerprint, + recipe_id: stored_recipe.recipe_id.clone(), + recipe_revision: stored_recipe.revision, + base_target_revision: stored_recipe.base_target_revision, + approved_plan_fingerprint: String::new(), + }, + ); + + let api = fixture._server.resource_api(); + assert!(api.launch_selected_recipe("steam:1".into()).await.unwrap()); + let first_review = dialog.shown.lock().unwrap()[0].launch_plan.clone().unwrap(); + assert_eq!(first_review.source_id, "steam"); + assert_eq!(first_review.requester_plugin_id, "fixture.plugin"); + assert_eq!(first_review.arguments.len(), 2); + assert!(first_review.arguments[0].ends_with("/zelda.sfc")); + assert_eq!(first_review.arguments[1], "--pixel-perfect"); + assert_eq!(first_review.environment_set["GAME_MODE"], "fixture"); + assert!( + first_review + .components + .iter() + .any(|component| component.kind == "runtime" && component.id == "runtime:snes") + ); + assert!( + first_review + .differences + .contains(&"known-components".into()) + ); + assert!( + first_review + .differences + .contains(&"custom-arguments".into()) + ); + assert!( + first_review + .differences + .contains(&"environment-changes".into()) + ); + + // The same immutable plan reuses its approval and dispatches without a second dialog. + assert!(api.launch_selected_recipe("steam:1".into()).await.unwrap()); + assert_eq!(dialog.shown.lock().unwrap().len(), 1); + + // A changed runtime revision changes the reviewed plan and a user refusal stops dispatch. + let mut updated = host + .runtime_resource(owner.clone(), "runtime:snes".into()) + .await + .unwrap() + .unwrap(); + updated.version = "1.1".into(); + updated.revision += 1; + host.save_runtime_resource(owner, updated).await.unwrap(); + assert!(!api.launch_selected_recipe("steam:1".into()).await.unwrap()); + assert_eq!(dialog.shown.lock().unwrap().len(), 2); + assert_eq!(host.custom_launch_dispatches.lock().unwrap().len(), 2); + let stored = host + .custom_launch_recipes + .lock() + .unwrap() + .values() + .find(|stored| stored.recipe_id == recipe.recipe_id) + .cloned() + .unwrap(); + assert!(stored.validate()); +} + +#[tokio::test(flavor = "multi_thread")] +async fn user_play_reviews_mod_layer_overlay_and_never_accepts_an_unreviewed_layer() { + use gamenode_core::drm_free::CustomLaunchCommand; + use gamenode_plugin_protocol::proto::CustomLaunchModLayer; + + let target = TargetGameContext { + game_id: "5".into(), + installation_id: "id-steam:1".into(), + profile_id: "account-a".into(), + revision: "1".into(), + }; + let (fixture, host, dialog) = Fixture::extension_game( + &[cap::DISCOVERY, cap::GAME_CUSTOM_LAUNCH], + target, + Some(answering(&[APPROVE_AND_REMEMBER, DECLINE, DECLINE])), + ) + .await; + let dialog = dialog.unwrap(); + host.launch_target.store(1, Ordering::SeqCst); + *host.detected_launch_command.lock().unwrap() = Some(CustomLaunchCommand { + executable: "/fixture/detected-game".into(), + file_identity: "fixture-detected-identity".into(), + arguments: vec!["--detected-base".into()], + working_directory: "/fixture/detected-game".into(), + environment: Default::default(), + }); + + let revision = fixture.feed.revision_of("steam:1").unwrap(); + let recipe = fixture + .client() + .games_propose_custom_launch(CustomLaunchRequest { + context: Some(fixture.context()), + game_id: "5".into(), + installation_id: "id-steam:1".into(), + expected_revision: revision, + idempotency_key: "mod-layer-for-play".into(), + mod_layers: vec![CustomLaunchModLayer { + id: "texture-hd".into(), + name: "HD texture layer".into(), + version: "1.2".into(), + revision: 3, + argv: vec!["--mod=texture-hd".into()], + environment_set: [("MOD_LAYER".into(), "texture-hd".into())].into(), + environment_unset: vec!["VANILLA".into()], + }], + ..Default::default() + }) + .await + .unwrap() + .into_inner(); + let (_layout, identity, owner_key) = selected_recipe_profile( + &fixture, + "mod-layer-play-profile", + &[cap::GAME_CUSTOM_LAUNCH], + ) + .await; + let stored = host + .custom_launch_recipe(owner_key.clone(), recipe.recipe_id.clone()) + .await + .unwrap() + .unwrap(); + assert_eq!(stored.mod_layers.len(), 1); + host.launch_recipe_selections.lock().unwrap().insert( + "steam:1".into(), + gamenode_core::library::LaunchRecipeSelection { + entry_key: "steam:1".into(), + owner_key: owner_key.clone(), + plugin_id: identity.plugin_id, + publisher_fingerprint: identity.publisher_fingerprint, + recipe_id: stored.recipe_id.clone(), + recipe_revision: stored.revision, + base_target_revision: stored.base_target_revision, + approved_plan_fingerprint: String::new(), + }, + ); + + let api = fixture._server.resource_api(); + assert!(api.launch_selected_recipe("steam:1".into()).await.unwrap()); + let first_review = dialog.shown.lock().unwrap()[0].launch_plan.clone().unwrap(); + assert_eq!(first_review.target, "Detected target (revision 1)"); + assert_eq!( + first_review.arguments, + ["--detected-base", "--mod=texture-hd"] + ); + assert_eq!(first_review.environment_set["MOD_LAYER"], "texture-hd"); + assert_eq!(first_review.environment_unset, ["VANILLA"]); + assert_eq!(first_review.components.len(), 1); + assert_eq!(first_review.components[0].kind, "mod-layer"); + assert_eq!(first_review.components[0].id, "texture-hd"); + assert_eq!(first_review.components[0].version, "1.2"); + assert_eq!(first_review.components[0].revision, 3); + assert_eq!(first_review.components[0].owner_plugin_id, "fixture.plugin"); + assert!( + first_review + .differences + .contains(&"known-components".into()) + ); + assert!( + first_review + .differences + .contains(&"custom-arguments".into()) + ); + assert!( + first_review + .differences + .contains(&"environment-changes".into()) + ); + assert!(!first_review.differences.contains(&"custom-target".into())); + assert!(matches!( + host.custom_launch_dispatches.lock().unwrap().as_slice(), + [crate::plugin_host::library::CustomLaunchDispatch::Detected { command }] + if command.executable == "/fixture/detected-game" + && command.file_identity == "fixture-detected-identity" + && command.arguments == ["--detected-base", "--mod=texture-hd"] + && command.environment.set.get("MOD_LAYER").map(String::as_str) == Some("texture-hd") + && command.environment.unset.contains("VANILLA") + )); + + // The unchanged reviewed plan makes no second dialog. + assert!(api.launch_selected_recipe("steam:1".into()).await.unwrap()); + assert_eq!(dialog.shown.lock().unwrap().len(), 1); + assert_eq!(host.custom_launch_dispatches.lock().unwrap().len(), 2); + + // A changed layer is a new plan: the user is asked again, and refusing dispatches nothing. + let mut changed = stored.clone(); + changed.revision += 1; + changed.mod_layers[0].revision += 1; + changed.mod_layers[0].arguments = vec!["--mod=unreviewed".into()]; + host.custom_launch_recipes.lock().unwrap().insert( + (owner_key.clone(), changed.recipe_id.clone()), + changed.clone(), + ); + { + let mut selections = host.launch_recipe_selections.lock().unwrap(); + let selection = selections.get_mut("steam:1").unwrap(); + selection.recipe_revision = changed.revision; + } + let approved = host + .launch_recipe_selections + .lock() + .unwrap() + .get("steam:1") + .unwrap() + .approved_plan_fingerprint + .clone(); + assert!(!api.launch_selected_recipe("steam:1".into()).await.unwrap()); + assert_eq!(dialog.shown.lock().unwrap().len(), 2); + assert_eq!(host.custom_launch_dispatches.lock().unwrap().len(), 2); + assert_eq!( + host.launch_recipe_selections + .lock() + .unwrap() + .get("steam:1") + .unwrap() + .approved_plan_fingerprint, + approved + ); + + // A selection that is stale against the stored layer revision refuses without a dialog. + changed.revision += 1; + host.custom_launch_recipes + .lock() + .unwrap() + .insert((owner_key.clone(), changed.recipe_id.clone()), changed); + assert_eq!( + api.launch_selected_recipe("steam:1".into()) + .await + .unwrap_err() + .code(), + Code::FailedPrecondition + ); + assert_eq!(dialog.shown.lock().unwrap().len(), 2); + assert_eq!(host.custom_launch_dispatches.lock().unwrap().len(), 2); + + // Restoring the reviewed recipe reuses the approval the refusal preserved. + host.custom_launch_recipes.lock().unwrap().insert( + (owner_key.clone(), stored.recipe_id.clone()), + stored.clone(), + ); + host.launch_recipe_selections + .lock() + .unwrap() + .get_mut("steam:1") + .unwrap() + .recipe_revision = stored.revision; + assert!(api.launch_selected_recipe("steam:1".into()).await.unwrap()); + assert_eq!(dialog.shown.lock().unwrap().len(), 2); + assert_eq!(host.custom_launch_dispatches.lock().unwrap().len(), 3); + + // Execution can reference only the stored recipe revision; layers cannot be added on the wire. + let err = fixture + .client() + .games_request_custom_launch(CustomLaunchRequest { + context: Some(fixture.context()), + game_id: "5".into(), + installation_id: "id-steam:1".into(), + expected_revision: revision, + idempotency_key: "unreviewed-layer-on-wire".into(), + recipe_id: stored.recipe_id.clone(), + recipe_revision: stored.revision, + mod_layers: vec![CustomLaunchModLayer { + id: "unreviewed".into(), + revision: 1, + argv: vec!["--unreviewed".into()], + ..Default::default() + }], + ..Default::default() + }) + .await + .unwrap_err(); + assert_eq!(err.code(), Code::InvalidArgument); + assert_eq!(host.custom_launch_dispatches.lock().unwrap().len(), 3); +} + +#[tokio::test(flavor = "multi_thread")] +async fn user_play_reviews_parameter_only_overlay_and_preserves_approval_on_refusal() { + use gamenode_core::drm_free::CustomLaunchCommand; + + let target = TargetGameContext { + game_id: "5".into(), + installation_id: "id-steam:1".into(), + profile_id: "account-a".into(), + revision: "1".into(), + }; + let (fixture, host, dialog) = Fixture::extension_game( + &[cap::DISCOVERY, cap::GAME_CUSTOM_LAUNCH], + target, + Some(answering(&[APPROVE_AND_REMEMBER, DECLINE])), + ) + .await; + let dialog = dialog.unwrap(); + host.launch_target.store(1, Ordering::SeqCst); + *host.detected_launch_command.lock().unwrap() = Some(CustomLaunchCommand { + executable: "/fixture/detected-game".into(), + file_identity: "fixture-detected-identity".into(), + arguments: vec!["--detected-base".into()], + working_directory: "/fixture/detected-game".into(), + environment: Default::default(), + }); + + let revision = fixture.feed.revision_of("steam:1").unwrap(); + let recipe = fixture + .client() + .games_propose_custom_launch(CustomLaunchRequest { + context: Some(fixture.context()), + game_id: "5".into(), + installation_id: "id-steam:1".into(), + expected_revision: revision, + idempotency_key: "parameter-only-for-play".into(), + argv: vec!["--windowed".into()], + environment_set: [("GAME_PROFILE".into(), "consent-fixture".into())].into(), + ..Default::default() + }) + .await + .unwrap() + .into_inner(); + let (_layout, identity, owner_key) = selected_recipe_profile( + &fixture, + "parameter-overlay-play-profile", + &[cap::GAME_CUSTOM_LAUNCH], + ) + .await; + let stored = host + .custom_launch_recipe(owner_key.clone(), recipe.recipe_id.clone()) + .await + .unwrap() + .unwrap(); + host.launch_recipe_selections.lock().unwrap().insert( + "steam:1".into(), + gamenode_core::library::LaunchRecipeSelection { + entry_key: "steam:1".into(), + owner_key: owner_key.clone(), + plugin_id: identity.plugin_id, + publisher_fingerprint: identity.publisher_fingerprint, + recipe_id: stored.recipe_id.clone(), + recipe_revision: stored.revision, + base_target_revision: stored.base_target_revision, + approved_plan_fingerprint: String::new(), + }, + ); + + let api = fixture._server.resource_api(); + assert!(api.launch_selected_recipe("steam:1".into()).await.unwrap()); + let first_review = dialog.shown.lock().unwrap()[0].launch_plan.clone().unwrap(); + assert_eq!(first_review.target, "Detected target (revision 1)"); + assert_eq!(first_review.arguments, ["--detected-base", "--windowed"]); + assert_eq!( + first_review.environment_set["GAME_PROFILE"], + "consent-fixture" + ); + assert!(first_review.components.is_empty()); + assert!( + first_review + .differences + .contains(&"custom-arguments".into()) + ); + assert!( + first_review + .differences + .contains(&"environment-changes".into()) + ); + assert!(!first_review.differences.contains(&"custom-target".into())); + assert!(matches!( + host.custom_launch_dispatches.lock().unwrap().as_slice(), + [crate::plugin_host::library::CustomLaunchDispatch::Detected { command }] + if command.arguments == ["--detected-base", "--windowed"] + && command.executable == "/fixture/detected-game" + && command.environment.set.get("GAME_PROFILE").map(String::as_str) == Some("consent-fixture") + )); + + // The unchanged approved plan reuses its approval. + assert!(api.launch_selected_recipe("steam:1".into()).await.unwrap()); + assert_eq!(dialog.shown.lock().unwrap().len(), 1); + assert_eq!(host.custom_launch_dispatches.lock().unwrap().len(), 2); + + // A changed parameter is a new revision-bound plan; refusing keeps the earlier approval. + let mut changed = stored.clone(); + changed.revision += 1; + changed.arguments.push("--unreviewed-parameter".into()); + host.custom_launch_recipes.lock().unwrap().insert( + (owner_key.clone(), changed.recipe_id.clone()), + changed.clone(), + ); + host.launch_recipe_selections + .lock() + .unwrap() + .get_mut("steam:1") + .unwrap() + .recipe_revision = changed.revision; + let approved = host + .launch_recipe_selections + .lock() + .unwrap() + .get("steam:1") + .unwrap() + .approved_plan_fingerprint + .clone(); + assert!(!api.launch_selected_recipe("steam:1".into()).await.unwrap()); + assert_eq!(dialog.shown.lock().unwrap().len(), 2); + assert_eq!(host.custom_launch_dispatches.lock().unwrap().len(), 2); + assert_eq!( + host.launch_recipe_selections + .lock() + .unwrap() + .get("steam:1") + .unwrap() + .approved_plan_fingerprint, + approved + ); + + // Returning to the reviewed parameters reuses that preserved approval without a dialog. + host.custom_launch_recipes.lock().unwrap().insert( + (owner_key.clone(), stored.recipe_id.clone()), + stored.clone(), + ); + host.launch_recipe_selections + .lock() + .unwrap() + .get_mut("steam:1") + .unwrap() + .recipe_revision = stored.revision; + assert!(api.launch_selected_recipe("steam:1".into()).await.unwrap()); + assert_eq!(dialog.shown.lock().unwrap().len(), 2); + assert_eq!(host.custom_launch_dispatches.lock().unwrap().len(), 3); + + // Execution parameters cannot be supplied outside the stored recipe. + let err = fixture + .client() + .games_request_custom_launch(CustomLaunchRequest { + context: Some(fixture.context()), + game_id: "5".into(), + installation_id: "id-steam:1".into(), + expected_revision: revision, + idempotency_key: "unreviewed-parameter-on-wire".into(), + recipe_id: stored.recipe_id, + recipe_revision: stored.revision, + argv: vec!["--unreviewed-parameter".into()], + ..Default::default() + }) + .await + .unwrap_err(); + assert_eq!(err.code(), Code::InvalidArgument); + assert_eq!(host.custom_launch_dispatches.lock().unwrap().len(), 3); +} + +#[tokio::test(flavor = "multi_thread")] +async fn custom_launch_recipe_removal_during_confirmation_blocks_dispatch() { + let (dialog, gate) = held(&[APPROVE]); + let (fixture, host, dialog) = + Fixture::game(&[cap::GAME_LAUNCH, cap::GAME_CUSTOM_LAUNCH], Some(dialog)).await; + host.launch_target.store(1, Ordering::SeqCst); + let revision = fixture.revision().await; + let recipe = fixture + .client() + .games_propose_custom_launch(CustomLaunchRequest { + context: Some(fixture.context()), + game_id: "3".into(), + installation_id: INSTALLATION.into(), + expected_revision: revision, + idempotency_key: "propose-recipe-before-confirmation".into(), + uri: "steam://rungameid/3".into(), + ..CustomLaunchRequest::default() + }) + .await + .unwrap() + .into_inner(); + let pending = fixture + .client() + .games_request_custom_launch(CustomLaunchRequest { + context: Some(fixture.context()), + game_id: "3".into(), + installation_id: INSTALLATION.into(), + expected_revision: revision, + idempotency_key: "execute-recipe-after-confirmation".into(), + recipe_id: recipe.recipe_id.clone(), + recipe_revision: recipe.recipe_revision, + ..CustomLaunchRequest::default() + }) + .await + .unwrap() + .into_inner(); + Fixture::dialog_shown(&dialog.unwrap(), 1).await; + + let removed = fixture + .client() + .games_remove_custom_launch(CustomLaunchRemoveRequest { + mutation: Some(fixture.mutation("remove-during-confirmation", recipe.recipe_revision)), + game_id: "3".into(), + recipe_id: recipe.recipe_id, + }) + .await + .unwrap() + .into_inner(); + assert_eq!(removed.outcome, MutationOutcome::Applied as i32); + gate.notify_one(); + + let ended = fixture.ended(&pending.job_id).await; + assert_eq!(ended.state(), JobState::Failed); + assert_eq!(ended.result_code, "recipe_changed"); + assert!(host.custom_launch_dispatches.lock().unwrap().is_empty()); + assert!(host.opened.lock().unwrap().is_empty()); +} + +#[tokio::test(flavor = "multi_thread")] +async fn remembered_custom_launch_approval_is_bound_to_recipe_identity() { + let (fixture, host, dialog) = Fixture::game( + &[cap::GAME_LAUNCH, cap::GAME_CUSTOM_LAUNCH], + Some(answering(&[APPROVE_AND_REMEMBER, APPROVE])), + ) + .await; + let dialog = dialog.unwrap(); + host.launch_target.store(1, Ordering::SeqCst); + let revision = fixture.revision().await; + let propose = |key: &'static str, uri: &'static str| CustomLaunchRequest { + context: Some(fixture.context()), + game_id: "3".into(), + installation_id: INSTALLATION.into(), + expected_revision: revision, + idempotency_key: key.into(), + uri: uri.into(), + ..CustomLaunchRequest::default() + }; + let first = fixture + .client() + .games_propose_custom_launch(propose("remember-recipe-a", "steam://rungameid/3")) + .await + .unwrap() + .into_inner(); + let first_recipe_id = first.recipe_id.clone(); + let first_recipe_revision = first.recipe_revision; + let first_job = fixture + .client() + .games_request_custom_launch(CustomLaunchRequest { + context: Some(fixture.context()), + game_id: "3".into(), + installation_id: INSTALLATION.into(), + expected_revision: revision, + idempotency_key: "run-recipe-a".into(), + recipe_id: first.recipe_id, + recipe_revision: first.recipe_revision, + ..CustomLaunchRequest::default() + }) + .await + .unwrap() + .into_inner(); + assert_eq!( + fixture.ended(&first_job.job_id).await.state(), + JobState::Succeeded + ); + assert_eq!(dialog.shown.lock().unwrap().len(), 1); + let remembered_job = fixture + .client() + .games_request_custom_launch(CustomLaunchRequest { + context: Some(fixture.context()), + game_id: "3".into(), + installation_id: INSTALLATION.into(), + expected_revision: revision, + idempotency_key: "run-remembered-recipe-a".into(), + recipe_id: first_recipe_id, + recipe_revision: first_recipe_revision, + ..CustomLaunchRequest::default() + }) + .await + .unwrap() + .into_inner(); + assert_eq!( + fixture.ended(&remembered_job.job_id).await.state(), + JobState::Succeeded + ); + assert_eq!(dialog.shown.lock().unwrap().len(), 1); + + let second = fixture + .client() + .games_propose_custom_launch(propose("remember-recipe-b", "steam://rungameid/4")) + .await + .unwrap() + .into_inner(); + let second_job = fixture + .client() + .games_request_custom_launch(CustomLaunchRequest { + context: Some(fixture.context()), + game_id: "3".into(), + installation_id: INSTALLATION.into(), + expected_revision: revision, + idempotency_key: "run-recipe-b".into(), + recipe_id: second.recipe_id, + recipe_revision: second.recipe_revision, + ..CustomLaunchRequest::default() + }) + .await + .unwrap() + .into_inner(); + assert_eq!( + fixture.ended(&second_job.job_id).await.state(), + JobState::Succeeded + ); + assert_eq!(dialog.shown.lock().unwrap().len(), 2); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_pre_issued_intent_skips_the_dialog_and_is_spent_once() { + // No dialog at all in this build: the intent is enough. + let (fixture, host, _) = Fixture::game(GRANTS, None).await; + let id = fixture + .intents + .issue(fixture.binding(Operation::Launch, 0).await) + .unwrap(); + let reply = fixture.launch_game("one", &id).await.unwrap(); + let done = fixture.ended(&reply.job_id).await; + assert_eq!(done.state(), JobState::Succeeded); + assert_eq!(host.opened.lock().unwrap().len(), 1); + + // The same request again is the same job; the intent is not spent twice. + assert_eq!( + fixture.launch_game("one", &id).await.unwrap().job_id, + reply.job_id + ); + // The spent intent is worthless for a new request. + assert_eq!( + fixture.launch_game("two", &id).await.unwrap_err().code(), + Code::FailedPrecondition + ); + assert_eq!(host.opened.lock().unwrap().len(), 1); +} + +#[tokio::test(flavor = "multi_thread")] +async fn an_invalid_intent_falls_back_to_confirmation_for_the_current_action() { + let dialog = Dialog { + answers: StdMutex::new(vec![APPROVE; 3].into()), + ..Dialog::default() + }; + let (fixture, host, shown) = Fixture::game(GRANTS, Some(dialog)).await; + // Issued for an install: not a launch. + let install = fixture + .intents + .issue(fixture.binding(Operation::Install, 0).await) + .unwrap(); + // Issued for a target that is not the current one. + let stale = fixture + .intents + .issue(fixture.binding(Operation::Launch, 99).await) + .unwrap(); + for (key, intent) in [ + ("a", install.as_str()), + ("b", stale.as_str()), + ("c", "intent-forged"), + ] { + let reply = fixture.launch_game(key, intent).await.unwrap(); + assert_eq!( + fixture.ended(&reply.job_id).await.state(), + JobState::Succeeded + ); + } + assert_eq!(shown.unwrap().shown.lock().unwrap().len(), 3); + assert_eq!(host.opened.lock().unwrap().len(), 3); + // The mismatched intent was not spent: its operation can still redeem it. + let reply = fixture.install_game("d", &install).await.unwrap(); + assert_eq!( + fixture.ended(&reply.job_id).await.state(), + JobState::Succeeded + ); + assert_eq!(host.opened.lock().unwrap().len(), 4); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_build_without_a_dialog_cannot_ask_and_starts_no_job() { + let (fixture, host, _) = Fixture::game(GRANTS, None).await; + let status = fixture.launch_game("one", "").await.unwrap_err(); + assert_eq!(status.code(), Code::FailedPrecondition); + assert!(host.opened.lock().unwrap().is_empty()); + assert_eq!(fixture.jobs.active(), 0); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_remembered_confirmation_skips_the_dialog_until_the_target_or_operation_changes() { + let (fixture, host, dialog) = Fixture::game( + GRANTS, + Some(answering(&[ + APPROVE_AND_REMEMBER, + APPROVE, + APPROVE_AND_REMEMBER, + ])), + ) + .await; + let dialog = dialog.unwrap(); + + // The first launch asks, and the user chooses to remember. + let first = fixture.launch_game("one", "").await.unwrap(); + assert_eq!( + fixture.ended(&first.job_id).await.state(), + JobState::Succeeded + ); + assert_eq!(dialog.shown.lock().unwrap().len(), 1); + + // The next one starts at once: no dialog, no waiting job. + let second = fixture.launch_game("two", "").await.unwrap(); + assert_ne!(second.message, "awaiting confirmation"); + assert_eq!( + fixture.ended(&second.job_id).await.state(), + JobState::Succeeded + ); + assert_eq!(dialog.shown.lock().unwrap().len(), 1); + assert_eq!(host.opened.lock().unwrap().len(), 2); + + // The game's detected target changed: it asks again. + host.launch_target.store(41, Ordering::SeqCst); + let third = fixture.launch_game("three", "").await.unwrap(); + assert_eq!(third.message, "awaiting confirmation"); + fixture.ended(&third.job_id).await; + assert_eq!(dialog.shown.lock().unwrap().len(), 2); + + // Launching and installing are different approvals. + let install = fixture.install_game("four", "").await.unwrap(); + assert_eq!(install.message, "awaiting confirmation"); + fixture.ended(&install.job_id).await; + assert_eq!(dialog.shown.lock().unwrap().len(), 3); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_remembered_confirmation_survives_a_restart_and_can_be_revoked() { + let (fixture, _, dialog) = + Fixture::game(GRANTS, Some(answering(&[APPROVE_AND_REMEMBER, APPROVE]))).await; + let first = fixture.launch_game("one", "").await.unwrap(); + fixture.ended(&first.job_id).await; + + let caller = fixture + .api + .authorize_resource(Some(&fixture.context()), GRANTS[0]) + .unwrap(); + let listed = fixture + .storage + .run_for_host( + caller.namespace.as_ref().unwrap(), + caller.profile_epoch, + |namespace| namespace.intent_approvals(), + ) + .await + .unwrap(); + let [approval] = listed.try_into().unwrap(); + assert_eq!( + ( + approval.operation.as_str(), + approval.game_id.as_str(), + approval.game_name.as_str() + ), + ("launch", "3", "Game") + ); + + // Revoked from the settings: the next request asks again. + let id = approval.id.clone(); + assert!( + fixture + .storage + .run_for_host( + caller.namespace.as_ref().unwrap(), + caller.profile_epoch, + move |namespace| namespace.revoke_intent_approval(&id), + ) + .await + .unwrap() + ); + let again = fixture.launch_game("two", "").await.unwrap(); + assert_eq!(again.message, "awaiting confirmation"); + fixture.ended(&again.job_id).await; + assert_eq!(dialog.unwrap().shown.lock().unwrap().len(), 2); +} + +#[tokio::test(flavor = "multi_thread")] +async fn losing_the_permission_while_the_dialog_is_open_prevents_the_start() { + let (dialog, gate) = held(&[APPROVE]); + let (fixture, host, dialog) = Fixture::game(GRANTS, Some(dialog)).await; + let reply = fixture.launch_game("one", "").await.unwrap(); + Fixture::dialog_shown(&dialog.unwrap(), 1).await; + + // The host's own record needs no session, so keep the owner before the permission goes. + let owner = fixture.game_owner(); + fixture + .api + .revoke_session_permission("fixture", cap::GAME_LAUNCH) + .await; + gate.notify_one(); + let done = fixture.ended_for(&owner, &reply.job_id).await; + assert_eq!(done.state(), JobState::Failed); + assert!(host.opened.lock().unwrap().is_empty()); + // And the plugin can no longer ask for anything. + assert_eq!( + fixture.launch_game("two", "").await.unwrap_err().code(), + Code::PermissionDenied + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_target_that_changed_while_the_dialog_was_open_is_not_started() { + let (dialog, gate) = held(&[APPROVE]); + let (fixture, host, dialog) = Fixture::game(GRANTS, Some(dialog)).await; + let reply = fixture.launch_game("one", "").await.unwrap(); + Fixture::dialog_shown(&dialog.unwrap(), 1).await; + + host.launch_target.store(7, Ordering::SeqCst); + gate.notify_one(); + let done = fixture.ended(&reply.job_id).await; + assert_eq!( + (done.state(), done.result_code.as_str()), + (JobState::Failed, "target_changed") + ); + assert!(host.opened.lock().unwrap().is_empty()); +} + +#[tokio::test(flavor = "multi_thread")] +async fn an_install_opens_the_providers_flow_and_reports_what_it_cannot_do() { + let (fixture, host, _) = Fixture::game(GRANTS, Some(answering(&[APPROVE, APPROVE]))).await; + let reply = fixture.install_game("one", "").await.unwrap(); + assert_eq!(fixture.ended(&reply.job_id).await.result_code, "opened"); + assert_eq!(*host.opened.lock().unwrap(), [(ENTRY.to_owned(), true)]); + + // A provider with no such action: the job says so, instead of pretending. + *host.open_fails.lock().unwrap() = Some(Code::Unimplemented); + let unsupported = fixture.install_game("two", "").await.unwrap(); + let done = fixture.ended(&unsupported.job_id).await; + assert_eq!( + (done.state(), done.result_code.as_str()), + (JobState::Failed, "unsupported") + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn only_the_permission_of_the_operation_and_a_valid_request_get_this_far() { + let (dialog, _gate) = held(&[APPROVE]); + let (fixture, host, dialog) = Fixture::game(&[cap::GAME_LAUNCH], Some(dialog)).await; + let dialog = dialog.unwrap(); + // The launch grant is not an install grant, and nothing is asked. + assert_eq!( + fixture.install_game("a", "").await.unwrap_err().code(), + Code::PermissionDenied + ); + // A stale revision, a foreign game, an empty installation and a bad key never ask either. + let revision = fixture.revision().await; + assert_eq!( + fixture + .launch_at("b", INSTALLATION, revision + 1, "") + .await + .unwrap_err() + .code(), + Code::FailedPrecondition + ); + assert_eq!( + fixture + .launch_at("c", "id-steam:1", 0, "") + .await + .unwrap_err() + .code(), + Code::NotFound + ); + assert_eq!( + fixture.launch_at("d", "", 0, "").await.unwrap_err().code(), + Code::InvalidArgument + ); + assert_eq!( + fixture + .launch_at("", INSTALLATION, revision, "") + .await + .unwrap_err() + .code(), + Code::InvalidArgument + ); + assert_eq!( + fixture + .launch_at("e", INSTALLATION, revision, &"x".repeat(129)) + .await + .unwrap_err() + .code(), + Code::InvalidArgument + ); + assert!(dialog.shown.lock().unwrap().is_empty()); + assert!(host.opened.lock().unwrap().is_empty()); +} + +#[tokio::test(flavor = "multi_thread")] +async fn an_extension_session_reaches_only_its_target_and_reading_the_library_adds_nothing() { + let (fixture, _, _) = Fixture::game(&[cap::GAME_LAUNCH, cap::LIBRARY_READ_ALL], None).await; + let caller = fixture + .api + .authorize_resource(Some(&fixture.context()), GRANTS[0]) + .unwrap(); + let service = fixture.service(); + let extension = |installation: &str, game: &str| { + let mut context = fixture.context(); + context.session_kind = SessionKind::Extension as i32; + context.target_game = Some(TargetGameContext { + game_id: game.into(), + installation_id: installation.into(), + profile_id: String::new(), + revision: String::new(), + }); + context + }; + + // The selected game of another provider is reachable, whole library or not. + let (key, entry) = service + .action_target(&caller, &extension("id-steam:1", "5"), "", "id-steam:1") + .unwrap(); + assert_eq!( + (key.as_str(), entry.provider_id.as_str()), + ("steam:1", "steam") + ); + // Any other game is not, even though the plugin can read it. + for (context, installation) in [ + (extension("id-steam:1", "5"), INSTALLATION), + (extension("id-steam:1", "6"), "id-steam:1"), + (extension(INSTALLATION, "3"), "id-steam:1"), + ] { + assert_eq!( + service + .action_target(&caller, &context, "", installation) + .unwrap_err() + .code(), + Code::NotFound + ); + } + // An extension session with no selected game names nothing. + let mut bare = fixture.context(); + bare.session_kind = SessionKind::Extension as i32; + assert_eq!( + service + .action_target(&caller, &bare, "", INSTALLATION) + .unwrap_err() + .code(), + Code::NotFound + ); + // A provider session reaches only its own entries, whatever library.read.all says. + assert_eq!( + service + .action_target(&caller, &fixture.context(), "", "id-steam:1") + .unwrap_err() + .code(), + Code::NotFound + ); + assert!( + service + .action_target(&caller, &fixture.context(), "", INSTALLATION) + .is_ok() + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn runtime_content_discovery_requires_a_scoped_context_and_separate_file_grant() { + let target = TargetGameContext { + game_id: "5".into(), + installation_id: "id-steam:1".into(), + profile_id: "account-a".into(), + revision: "1".into(), + }; + let (fixture, _, _) = + Fixture::extension_game(&[cap::DISCOVERY, cap::GAME_CUSTOM_LAUNCH], target, None).await; + let context = fixture.context(); + assert!( + context.provider_id.is_empty(), + "extensions do not impersonate providers" + ); + let request = |context: Option, game_id: &str, installation_id: &str| { + ContentRegistrationRequest { + mutation: Some(MutationContext { + context, + operation_id: String::new(), + idempotency_key: "runtime-content-discovery".into(), + expected_revision: 0, + }), + game_id: game_id.into(), + installation_id: installation_id.into(), + content_handle: "approved-content-handle".into(), + content_kind: "snes-rom".into(), + runtime_id: "runtime-zsnes".into(), + supported_platforms: vec!["linux".into()], + content_id: "rom:zelda".into(), + } + }; + + // The extension's host-issued context is bound to the selected game. Omitting it or + // substituting another session/target cannot turn discovery into provider impersonation. + assert_eq!( + fixture + .client() + .games_register_content(request(None, "5", "id-steam:1")) + .await + .unwrap_err() + .code(), + Code::InvalidArgument + ); + let mut unscoped = context.clone(); + unscoped.target_game = None; + assert_eq!( + fixture + .client() + .games_register_content(request(Some(unscoped), "5", "id-steam:1")) + .await + .unwrap_err() + .code(), + Code::PermissionDenied + ); + let foreign = Fixture::new(&[cap::DISCOVERY]).await; + assert_eq!( + fixture + .client() + .games_register_content(request(Some(foreign.context()), "5", "id-steam:1",)) + .await + .unwrap_err() + .code(), + Code::Unauthenticated + ); + assert_eq!( + fixture + .client() + .games_register_content(request(Some(context.clone()), "6", "id-steam:2")) + .await + .unwrap_err() + .code(), + Code::PermissionDenied, + "discovery alone cannot read an approved content handle" + ); + + // A provider session with discovery alone cannot launch its own game; execution has an + // independent permission. Extensions also need a game-action grant to negotiate a session. + let launch_discovery_only = Fixture::new(&[cap::DISCOVERY]).await; + launch_discovery_only.library(&[("fixture:1", Some(5), "Observed game")]); + assert_eq!( + launch_discovery_only + .client() + .games_request_launch(GameLaunchRequest { + context: Some(launch_discovery_only.context()), + game_id: "5".into(), + installation_id: "id-fixture:1".into(), + expected_revision: 0, + user_intent_id: String::new(), + idempotency_key: "discovery-is-not-launch".into(), + }) + .await + .unwrap_err() + .code(), + Code::PermissionDenied + ); + + // A properly scoped but foreign game remains outside the extension's selected context even + // when file reading is independently granted. + let (with_file_read, _, _) = Fixture::extension_game( + &[cap::DISCOVERY, cap::FILES_READ, cap::GAME_CUSTOM_LAUNCH], + TargetGameContext { + game_id: "5".into(), + installation_id: "id-steam:1".into(), + profile_id: "account-a".into(), + revision: "1".into(), + }, + None, + ) + .await; + assert_eq!( + with_file_read + .client() + .games_register_content(request(Some(with_file_read.context()), "6", "id-steam:2",)) + .await + .unwrap_err() + .code(), + Code::NotFound + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn runtime_plugins_reconcile_observations_as_selectable_bindings_on_one_game() { + use gamenode_core::library::{ApprovedFileReference, RuntimeArgumentTemplate, RuntimeResource}; + + let target = TargetGameContext { + game_id: "5".into(), + installation_id: "id-steam:1".into(), + profile_id: "account-a".into(), + revision: "1".into(), + }; + let (fixture, host, _) = Fixture::extension_game( + &[cap::DISCOVERY, cap::FILES_READ, cap::GAME_CUSTOM_LAUNCH], + target, + None, + ) + .await; + let content_root = fixture.game_dir("selected-rom", &[("zelda.sfc", b"rom bytes")]); + fixture.library_in(&[ + ("steam:1", Some(5), "Selected Steam game", &content_root), + ("steam:2", Some(6), "Other Steam game", &content_root), + ]); + let library_revision = fixture.feed.revision(); + fixture.user_approving(&content_root); + let root = fixture.root_handle("id-steam:1", &["read"]).await; + let content_handle = fixture.child(&root, "zelda.sfc").await; + let context = fixture.context(); + let caller = fixture + .api + .authorize_resource(Some(&context), cap::DISCOVERY) + .unwrap(); + let owner = super::super::mutations::mutation_owner(&caller); + + for id in ["runtime-zsnes", "runtime-bsnes"] { + host.seed_runtime_resource( + owner.clone(), + RuntimeResource { + id: id.into(), + name: id.into(), + version: "1.0".into(), + executable: ApprovedFileReference { + approval_id: format!("runtime-approval-{id}"), + relative_path: vec!["bin".into(), "emulator".into()], + }, + platform: "linux".into(), + supported_formats: vec!["snes-rom".into()], + launch_arguments: vec![RuntimeArgumentTemplate::ContentPath], + revision: 1, + observed_at: 1, + provenance: Default::default(), + extensions: Default::default(), + }, + ); + } + + // The stable id came from the user's selected existing content context; this owner's + // namespace has no previous binding for it. + let content_id = "rom:zelda".to_owned(); + for (id, key) in [ + ("runtime-zsnes", "discover-zsnes"), + ("runtime-bsnes", "discover-bsnes"), + ] { + let reply = fixture + .client() + .games_register_content(ContentRegistrationRequest { + mutation: Some(MutationContext { + context: Some(context.clone()), + operation_id: String::new(), + idempotency_key: key.into(), + expected_revision: 0, + }), + game_id: "5".into(), + installation_id: "id-steam:1".into(), + content_handle: content_handle.clone(), + content_kind: "snes-rom".into(), + runtime_id: id.into(), + supported_platforms: vec!["linux".into()], + content_id: content_id.clone(), + }) + .await + .unwrap() + .into_inner(); + assert_eq!(reply.revision, 1); + assert_eq!(reply.outcome, MutationOutcome::Applied as i32); + assert_eq!(reply.resource_id, content_id); + } + + let bindings = host + .runtime_content_bindings(owner, 5, "id-steam:1".into()) + .await + .unwrap(); + assert_eq!(bindings.len(), 2); + assert!( + bindings + .iter() + .all(|binding| binding.content_id == content_id) + ); + assert_eq!( + bindings + .iter() + .map(|binding| binding.runtime_id.as_str()) + .collect::>(), + ["runtime-bsnes", "runtime-zsnes"].into() + ); + assert_eq!( + fixture.feed.revision(), + library_revision, + "runtime observations attach to existing entries and never create another library entry" + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn provider_content_discovery_keeps_legacy_owner_scope_and_requires_host_context() { + use gamenode_core::library::{ApprovedFileReference, RuntimeArgumentTemplate, RuntimeResource}; + + let (fixture, host, _) = Fixture::game(&[cap::DISCOVERY, cap::FILES_READ], None).await; + let content_root = fixture.game_dir("provider-content", &[("game.rom", b"fixture bytes")]); + fixture.library_in(&[("fixture:1", Some(3), "Provider game", &content_root)]); + fixture.user_approving(&content_root); + let root = fixture.root_handle("id-fixture:1", &["read"]).await; + let content_handle = fixture.child(&root, "game.rom").await; + let context = fixture.context(); + + // Legacy provider sessions have their provider identity and no selected-game extension + // authority. RegisterContent remains available through the host-issued resource context. + assert_eq!(context.session_kind(), SessionKind::Unspecified); + assert!(context.target_game.is_none()); + let caller = fixture + .api + .authorize_resource(Some(&context), cap::DISCOVERY) + .unwrap(); + let owner = super::super::mutations::mutation_owner(&caller); + host.seed_runtime_resource( + owner, + RuntimeResource { + id: "provider-runtime".into(), + name: "Provider runtime".into(), + version: "1.0".into(), + executable: ApprovedFileReference { + approval_id: "runtime-approval-provider".into(), + relative_path: vec!["bin".into(), "runtime".into()], + }, + platform: "linux".into(), + supported_formats: vec!["fixture-rom".into()], + launch_arguments: vec![RuntimeArgumentTemplate::ContentPath], + revision: 1, + observed_at: 1, + provenance: Default::default(), + extensions: Default::default(), + }, + ); + + let registration = |context: Option, game_id: &str, installation_id: &str| { + ContentRegistrationRequest { + mutation: Some(MutationContext { + context, + operation_id: String::new(), + idempotency_key: format!("provider-content-{game_id}-{installation_id}"), + expected_revision: 0, + }), + game_id: game_id.into(), + installation_id: installation_id.into(), + content_handle: content_handle.clone(), + content_kind: "fixture-rom".into(), + runtime_id: "provider-runtime".into(), + supported_platforms: vec!["linux".into()], + content_id: "provider-game:content".into(), + } + }; + + let applied = fixture + .client() + .games_register_content(registration(Some(context.clone()), "3", "id-fixture:1")) + .await + .unwrap() + .into_inner(); + assert_eq!(applied.outcome, MutationOutcome::Applied as i32); + assert_eq!(applied.resource_id, "provider-game:content"); + + // The provider may only discover content for its own catalog, even when it supplies a valid + // host-issued context and a file handle. A missing or altered context cannot use this route. + assert_eq!( + fixture + .client() + .games_register_content(registration(Some(context.clone()), "5", "id-steam:1")) + .await + .unwrap_err() + .code(), + Code::NotFound + ); + assert_eq!( + fixture + .client() + .games_register_content(registration(None, "3", "id-fixture:1")) + .await + .unwrap_err() + .code(), + Code::InvalidArgument + ); + let mut altered = context.clone(); + altered.target_game = Some(TargetGameContext { + game_id: "3".into(), + installation_id: "id-fixture:1".into(), + profile_id: "account-a".into(), + revision: "1".into(), + }); + assert_eq!( + fixture + .client() + .games_register_content(registration(Some(altered), "3", "id-fixture:1")) + .await + .unwrap_err() + .code(), + Code::PermissionDenied + ); + let foreign = Fixture::new(&[cap::DISCOVERY, cap::FILES_READ]).await; + assert_eq!( + fixture + .client() + .games_register_content(registration(Some(foreign.context()), "3", "id-fixture:1")) + .await + .unwrap_err() + .code(), + Code::Unauthenticated + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn extension_custom_overlay_targets_selected_steam_without_read_or_provider_identity() { + let target = TargetGameContext { + game_id: "5".into(), + installation_id: "id-steam:1".into(), + profile_id: "account-a".into(), + revision: "1".into(), + }; + let (fixture, host, _) = + Fixture::extension_game(&[cap::GAME_CUSTOM_LAUNCH], target, None).await; + host.launch_target.store(1, Ordering::SeqCst); + let context = fixture.context(); + assert_eq!(context.session_kind(), SessionKind::Extension); + assert!(context.provider_id.is_empty()); + assert_eq!( + context.target_game.as_ref().unwrap().installation_id, + "id-steam:1" + ); + assert_eq!( + fixture.list("").await.unwrap_err().code(), + Code::PermissionDenied + ); + + let revision = fixture.feed.revision_of("steam:1").unwrap(); + assert_eq!( + fixture + .client() + .games_request_launch(GameLaunchRequest { + context: Some(context.clone()), + game_id: "5".into(), + installation_id: "id-steam:1".into(), + expected_revision: revision, + user_intent_id: String::new(), + idempotency_key: "normal-without-grant".into(), + }) + .await + .unwrap_err() + .code(), + Code::PermissionDenied + ); + let proposal = CustomLaunchRequest { + context: Some(context.clone()), + game_id: "5".into(), + installation_id: "id-steam:1".into(), + expected_revision: revision, + idempotency_key: "extension-custom-proposal".into(), + uri: "steam://rungameid/5".into(), + ..CustomLaunchRequest::default() + }; + let recipe = fixture + .client() + .games_propose_custom_launch(proposal.clone()) + .await + .unwrap() + .into_inner(); + assert_eq!(host.custom_launch_recipes.lock().unwrap().len(), 1); + let stored = host + .custom_launch_recipes + .lock() + .unwrap() + .values() + .next() + .cloned() + .unwrap(); + assert_eq!( + (stored.game_id, stored.installation_id.as_str()), + (5, "id-steam:1") + ); + + let mut forged_provider = proposal.clone(); + forged_provider.context.as_mut().unwrap().provider_id = "steam".into(); + forged_provider.idempotency_key = "forged-provider".into(); + assert!( + fixture + .client() + .games_propose_custom_launch(forged_provider) + .await + .is_err() + ); + let mut other_game = proposal; + other_game.game_id = "6".into(); + other_game.installation_id = "id-steam:2".into(); + other_game.idempotency_key = "other-steam-game".into(); + assert_eq!( + fixture + .client() + .games_propose_custom_launch(other_game) + .await + .unwrap_err() + .code(), + Code::NotFound + ); + + let intent = fixture + .intents + .issue( + fixture + .binding_for( + Operation::CustomLaunch, + 1, + "5", + "id-steam:1", + &recipe.recipe_id, + ) + .await, + ) + .unwrap(); + let request = CustomLaunchRequest { + context: Some(context), + game_id: "5".into(), + installation_id: "id-steam:1".into(), + expected_revision: 1, + user_intent_id: intent, + idempotency_key: "extension-custom-execution".into(), + recipe_id: recipe.recipe_id.clone(), + recipe_revision: recipe.recipe_revision, + ..CustomLaunchRequest::default() + }; + let executed = fixture + .client() + .games_request_custom_launch(request.clone()) + .await + .unwrap() + .into_inner(); + let replay = fixture + .client() + .games_request_custom_launch(request.clone()) + .await + .unwrap() + .into_inner(); + assert_eq!(replay.job_id, executed.job_id); + assert_eq!( + fixture.ended(&executed.job_id).await.state(), + JobState::Succeeded + ); + let mut reused_intent = request; + reused_intent.idempotency_key = "extension-custom-reuse-intent".into(); + assert_eq!( + fixture + .client() + .games_request_custom_launch(reused_intent) + .await + .unwrap_err() + .code(), + Code::FailedPrecondition + ); + assert_eq!(host.custom_launch_dispatches.lock().unwrap().len(), 1); + assert!(host.opened.lock().unwrap().is_empty()); + let steam_scope = Scope { + own_provider: "steam".into(), + read_all: false, + provider_filter: None, + }; + let (_, selected_steam_entry) = fixture.feed.target(&steam_scope, "id-steam:1").unwrap(); + assert_eq!(selected_steam_entry.name, "Selected Steam game"); + assert_eq!(selected_steam_entry.game_id, Some(5)); +} + +#[tokio::test(flavor = "multi_thread")] +async fn normal_and_custom_launch_permissions_are_independent_for_extensions() { + let target = TargetGameContext { + game_id: "5".into(), + installation_id: "id-steam:1".into(), + profile_id: "account-a".into(), + revision: "1".into(), + }; + let (fixture, host, _) = Fixture::extension_game(&[cap::GAME_LAUNCH], target, None).await; + host.launch_target.store(1, Ordering::SeqCst); + let revision = fixture.feed.revision_of("steam:1").unwrap(); + let custom_proposal = fixture + .client() + .games_propose_custom_launch(CustomLaunchRequest { + context: Some(fixture.context()), + game_id: "5".into(), + installation_id: "id-steam:1".into(), + expected_revision: revision, + idempotency_key: "without-custom-grant".into(), + uri: "steam://rungameid/5".into(), + ..CustomLaunchRequest::default() + }) + .await + .unwrap_err(); + assert_eq!(custom_proposal.code(), Code::PermissionDenied); + + let intent = fixture + .intents + .issue( + fixture + .binding_for(Operation::Launch, 1, "5", "id-steam:1", "") + .await, + ) + .unwrap(); + let launched = fixture + .client() + .games_request_launch(GameLaunchRequest { + context: Some(fixture.context()), + game_id: "5".into(), + installation_id: "id-steam:1".into(), + expected_revision: 1, + user_intent_id: intent, + idempotency_key: "normal-launch".into(), + }) + .await + .unwrap() + .into_inner(); + assert_eq!( + fixture.ended(&launched.job_id).await.state(), + JobState::Succeeded + ); + assert_eq!(*host.opened.lock().unwrap(), [("steam:1".into(), false)]); + assert!(host.custom_launch_recipes.lock().unwrap().is_empty()); +} + +#[tokio::test(flavor = "multi_thread")] +async fn custom_launch_commit_serializes_with_permission_revocation() { + let (fixture, host, _) = Fixture::game( + &[cap::GAME_LAUNCH, cap::GAME_CUSTOM_LAUNCH], + Some(answering(&[APPROVE])), + ) + .await; + host.launch_target.store(1, Ordering::SeqCst); + let revision = fixture.revision().await; + let recipe = fixture + .client() + .games_propose_custom_launch(CustomLaunchRequest { + context: Some(fixture.context()), + game_id: "3".into(), + installation_id: INSTALLATION.into(), + expected_revision: revision, + idempotency_key: "race-recipe".into(), + uri: "steam://rungameid/3".into(), + ..CustomLaunchRequest::default() + }) + .await + .unwrap() + .into_inner(); + let intent = fixture + .intents + .issue( + fixture + .binding_for( + Operation::CustomLaunch, + 1, + "3", + INSTALLATION, + &recipe.recipe_id, + ) + .await, + ) + .unwrap(); + let gate = Arc::new(Notify::new()); + *host.custom_launch_gate.lock().unwrap() = Some(gate.clone()); + let entered = host.custom_launch_entered.notified(); + let owner = fixture.game_owner(); + let reply = fixture + .client() + .games_request_custom_launch(CustomLaunchRequest { + context: Some(fixture.context()), + game_id: "3".into(), + installation_id: INSTALLATION.into(), + expected_revision: revision, + user_intent_id: intent, + idempotency_key: "race-execute".into(), + recipe_id: recipe.recipe_id, + recipe_revision: recipe.recipe_revision, + ..CustomLaunchRequest::default() + }) + .await + .unwrap() + .into_inner(); + tokio::time::timeout(Duration::from_secs(5), entered) + .await + .unwrap(); + let provider = fixture.api.clone(); + let mut revoke = tokio::spawn(async move { + provider + .revoke_session_permission("fixture", cap::GAME_CUSTOM_LAUNCH) + .await + }); + assert!( + tokio::time::timeout(Duration::from_millis(100), &mut revoke) + .await + .is_err(), + "revocation must wait for the launch commit" + ); + gate.notify_one(); + tokio::time::timeout(Duration::from_secs(5), revoke) + .await + .unwrap() + .unwrap(); + assert_eq!( + fixture.ended_for(&owner, &reply.job_id).await.state(), + JobState::Succeeded + ); + assert_eq!(host.custom_launch_dispatches.lock().unwrap().len(), 1); + assert!( + fixture + .api + .authorize_resource(Some(&fixture.context()), cap::GAME_CUSTOM_LAUNCH) + .is_err() + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn custom_launch_revoked_before_approval_never_dispatches() { + let (dialog, gate) = held(&[APPROVE]); + let (fixture, host, dialog) = + Fixture::game(&[cap::GAME_LAUNCH, cap::GAME_CUSTOM_LAUNCH], Some(dialog)).await; + host.launch_target.store(1, Ordering::SeqCst); + let revision = fixture.revision().await; + let recipe = fixture + .client() + .games_propose_custom_launch(CustomLaunchRequest { + context: Some(fixture.context()), + game_id: "3".into(), + installation_id: INSTALLATION.into(), + expected_revision: revision, + idempotency_key: "revoke-recipe".into(), + uri: "steam://rungameid/3".into(), + ..CustomLaunchRequest::default() + }) + .await + .unwrap() + .into_inner(); + let owner = fixture.game_owner(); + let reply = fixture + .client() + .games_request_custom_launch(CustomLaunchRequest { + context: Some(fixture.context()), + game_id: "3".into(), + installation_id: INSTALLATION.into(), + expected_revision: revision, + idempotency_key: "revoke-execute".into(), + recipe_id: recipe.recipe_id, + recipe_revision: recipe.recipe_revision, + ..CustomLaunchRequest::default() + }) + .await + .unwrap() + .into_inner(); + Fixture::dialog_shown(&dialog.unwrap(), 1).await; + fixture + .api + .revoke_session_permission("fixture", cap::GAME_CUSTOM_LAUNCH) + .await; + gate.notify_one(); + let done = fixture.ended_for(&owner, &reply.job_id).await; + assert_ne!(done.state(), JobState::Succeeded); + assert!(host.custom_launch_dispatches.lock().unwrap().is_empty()); +} + +/// A second plugin session that may read the shared runtime catalog and the common content +/// availability projection, but has no runtime mutation or discovery authority. +async fn runtime_catalog_consumer(fixture: &Fixture) -> Session { + let capabilities = [ + cap::CONTEXT, + cap::LIBRARY_READ, + cap::LIBRARY_READ_ALL, + cap::GAME_RUNTIME_READ, + cap::FILES_READ, + ]; + fixture + .api + .register(Registration { + provider_id: "runtime-consumer".into(), + plugin_id: "org.example.runtime-consumer".into(), + kind: crate::plugin_host::provider::RegistrationKind::Provider, + declared_developer: "Runtime consumer developer".into(), + package_digest: vec![7; 32], + origin: RegistrationOrigin::ThirdParty { + publisher_fingerprint: "cd".repeat(32), + }, + capabilities: capabilities.iter().map(|cap| (*cap).into()).collect(), + shared_catalog: false, + playtime: Default::default(), + services: Arc::new(NoServices), + }) + .unwrap(); + let launch = fixture.api.begin_launch("runtime-consumer").unwrap(); + let credential = (0..launch.credential.len()) + .step_by(2) + .map(|i| u8::from_str_radix(&launch.credential[i..i + 2], 16).unwrap()) + .collect(); + let session = Session::open_with_options( + Launch { + endpoint: fixture.endpoint.clone(), + credential, + operation_id: "runtime-consumer-launch".into(), + }, + "org.example.runtime-consumer", + "runtime-consumer", + "1.0", + &capabilities, + SessionOptions { + min_api_major: 1, + min_api_minor: cap::THIRD_PARTY_API_MINOR, + max_api_major: 1, + max_api_minor: gamenode_plugin_protocol::API_MINOR, + ..SessionOptions::default() + }, + ) + .await + .unwrap(); + launch.ready.await.unwrap(); + session +} + +#[tokio::test(flavor = "multi_thread")] +async fn shared_runtime_catalog_and_content_availability_need_no_pairwise_grant() { + use crate::plugin_host::resources::ResourceApi; + use crate::plugin_host::shared_data::DataBroker; + use crate::plugin_host::sharing_policy::{ActivationReadGrant, SharedSharingPolicies}; + use gamenode_plugin_protocol::{ + prost_types, + proto::{ + CommonDataCategory, ContentPathArgument, ExtensionPayload, + RuntimeArgumentTemplate as RuntimeArgumentProto, + runtime_argument_template::Value as RuntimeArgumentValue, + }, + }; + use tokio::task::JoinHandle; + use tokio_stream::wrappers::TcpListenerStream; + + async fn serve(service: ResourceApi) -> (ResourceHostClient, JoinHandle<()>) { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let server = tokio::spawn(async move { + tonic::transport::Server::builder() + .add_service(resource_host_server::ResourceHostServer::new(service)) + .serve_with_incoming(TcpListenerStream::new(listener)) + .await + .unwrap(); + }); + let client = ResourceHostClient::connect(format!("http://{address}")) + .await + .unwrap(); + (client, server) + } + + let target = TargetGameContext { + game_id: "5".into(), + installation_id: "id-steam:1".into(), + profile_id: "account-a".into(), + revision: "1".into(), + }; + let (fixture, host, _) = Fixture::extension_game( + &[ + cap::DISCOVERY, + cap::FILES_READ, + cap::GAME_CUSTOM_LAUNCH, + cap::GAME_RUNTIME_CREATE, + cap::GAME_RUNTIME_READ, + ], + target, + Some(answering(&[APPROVE])), + ) + .await; + let content_root = fixture.game_dir("steam-runtime-catalog", &[("emulator", b"runtime")]); + fixture.user_approving(&content_root); + let root = fixture.root_handle("id-steam:1", &["read"]).await; + let runtime_executable = fixture.child(&root, "emulator").await; + + // A registers an owned runtime with a plugin-declared compatibility namespace. + let registration = fixture + .client() + .runtimes_register(RuntimeRegisterRequest { + mutation: Some(fixture.mutation("register-catalog-runtime", 0)), + runtime: Some(RuntimeRecord { + id: "runtime:catalog-snes".into(), + name: "Catalog SNES".into(), + version: "2.0".into(), + executable_handle: runtime_executable, + supported_formats: vec!["snes-rom".into(), "org.example.snes-patch".into()], + platform: std::env::consts::OS.into(), + argument_template: vec![RuntimeArgumentProto { + value: Some(RuntimeArgumentValue::ContentPath(ContentPathArgument {})), + }], + extensions: [( + "org.example.compatibility".into(), + ExtensionPayload { + schema_id: "org.example.compatibility.v1".into(), + schema_version: 1, + schema_digest: vec![3; 32], + data: Some(prost_types::Struct { + fields: [( + "console".into(), + prost_types::Value { + kind: Some(prost_types::value::Kind::StringValue( + "snes".into(), + )), + }, + )] + .into(), + }), + }, + )] + .into(), + ..Default::default() + }), + }) + .await + .unwrap() + .into_inner(); + assert_eq!(registration.outcome, MutationOutcome::Applied as i32); + assert_eq!( + registration + .runtime + .as_ref() + .unwrap() + .provenance + .as_ref() + .unwrap() + .producer_plugin_id, + "fixture.plugin" + ); + let context_a = fixture.context(); + let caller_a = fixture + .api + .authorize_resource(Some(&context_a), cap::GAME_RUNTIME_CREATE) + .unwrap(); + let owner_a = super::super::mutations::mutation_owner(&caller_a); + host.runtime_bindings.lock().unwrap().insert( + (owner_a, 5, "id-steam:1".into()), + vec![gamenode_core::library::RuntimeContentBinding { + game_id: 5, + installation_id: "id-steam:1".into(), + content_id: "rom:zelda".into(), + content: gamenode_core::library::ApprovedFileReference { + approval_id: "content-approval".into(), + relative_path: vec!["zelda.sfc".into()], + }, + content_kind: "snes-rom".into(), + runtime_id: "runtime:catalog-snes".into(), + supported_platforms: vec![std::env::consts::OS.into()], + revision: 1, + }], + ); + + // B gets only the two common category reads, with no source-to-recipient policy. + let consumer = runtime_catalog_consumer(&fixture).await; + let context_b = consumer.host.resource_context().unwrap().clone(); + let identity_b = { + let caller = fixture + .api + .authorize_resource_session(Some(&context_b)) + .unwrap(); + ResourceApi::data_identity(&caller).unwrap() + }; + let policies = Arc::new(SharedSharingPolicies::default()); + policies + .set_activation_grants( + &identity_b, + ActivationReadGrant::new( + [ + CommonDataCategory::RuntimeCatalog, + CommonDataCategory::ContentAvailability, + ], + [], + ) + .unwrap(), + ) + .unwrap(); + let service = ResourceApi::new( + fixture.api.clone(), + fixture.feed.clone(), + fixture.storage.clone(), + fixture.files.clone(), + fixture.network.clone(), + fixture.notifications.clone(), + fixture.jobs.clone(), + fixture.intents.clone(), + fixture.saves.clone(), + fixture.snapshots.clone(), + fixture.leases.clone(), + fixture.processes.clone(), + ) + .with_shared_data(Arc::new(DataBroker::new()), policies.clone()); + let (mut client, server) = serve(service).await; + + // Private-only default: B sees no foreign runtime and no availability. + let private = client + .runtimes_list(DomainListRequest { + page: Some(PageRequest { + context: Some(context_b.clone()), + page_size: 10, + ..Default::default() + }), + ..Default::default() + }) + .await + .unwrap() + .into_inner(); + assert!(private.runtimes.is_empty()); + let private_entry = client + .library_get(LibraryGetRequest { + context: Some(context_b.clone()), + installation_id: "id-steam:1".into(), + ..Default::default() + }) + .await + .unwrap() + .into_inner() + .entry + .unwrap(); + assert!(private_entry.runtime_availability.is_empty()); + + // Without the current category grant, the explicit selector is denied rather than narrowed. + let selector = CommonDataSelector { + categories: vec![CommonDataCategory::RuntimeCatalog as i32], + selected_record_ids: Vec::new(), + }; + policies.clear_activation_grants(&identity_b).unwrap(); + let denied = client + .runtimes_list(DomainListRequest { + page: Some(PageRequest { + context: Some(context_b.clone()), + page_size: 10, + common_data_categories: Some(selector.clone()), + ..Default::default() + }), + ..Default::default() + }) + .await + .unwrap_err(); + assert_eq!(denied.code(), Code::PermissionDenied); + policies + .set_activation_grants( + &identity_b, + ActivationReadGrant::new( + [ + CommonDataCategory::RuntimeCatalog, + CommonDataCategory::ContentAvailability, + ], + [], + ) + .unwrap(), + ) + .unwrap(); + + // The explicit common selector returns A's runtime with provenance and its metadata, but no + // executable handle and no filesystem path. + let shared = client + .runtimes_list(DomainListRequest { + page: Some(PageRequest { + context: Some(context_b.clone()), + page_size: 10, + common_data_categories: Some(selector.clone()), + ..Default::default() + }), + ..Default::default() + }) + .await + .unwrap() + .into_inner(); + assert_eq!(shared.runtimes.len(), 1); + let runtime = &shared.runtimes[0]; + assert_eq!(runtime.id, "runtime:catalog-snes"); + assert_eq!(runtime.name, "Catalog SNES"); + assert_eq!(runtime.version, "2.0"); + assert_eq!( + runtime.supported_formats, + ["snes-rom", "org.example.snes-patch"] + ); + assert!(runtime.executable_handle.is_empty()); + assert_eq!(runtime.argument_template.len(), 1); + let provenance = runtime.provenance.as_ref().unwrap(); + assert_eq!(provenance.producer_plugin_id, "fixture.plugin"); + assert_eq!(provenance.publisher_fingerprint, "ab".repeat(32)); + let compatibility = runtime.extensions.get("org.example.compatibility").unwrap(); + assert_eq!(compatibility.schema_id, "org.example.compatibility.v1"); + assert_eq!(compatibility.schema_version, 1); + let field = &compatibility.data.as_ref().unwrap().fields["console"]; + assert_eq!( + field.kind, + Some(prost_types::value::Kind::StringValue("snes".into())) + ); + + // The same runtime is reachable by id, and a watch replays it after a reset. + let by_id = client + .runtimes_get(DomainGetRequest { + context: Some(context_b.clone()), + resource_id: "runtime:catalog-snes".into(), + shared_records: Some(selector.clone()), + ..Default::default() + }) + .await + .unwrap() + .into_inner(); + assert_eq!( + by_id + .runtime + .unwrap() + .provenance + .unwrap() + .producer_plugin_id, + "fixture.plugin" + ); + let mut watch = client + .runtimes_watch(DomainWatchRequest { + context: Some(context_b.clone()), + after_revision: 0, + shared_records: Some(selector.clone()), + ..Default::default() + }) + .await + .unwrap() + .into_inner(); + let reset = tokio::time::timeout(std::time::Duration::from_secs(2), watch.message()) + .await + .unwrap() + .unwrap() + .unwrap(); + assert_eq!(reset.event_type, "reset"); + let upserted = tokio::time::timeout(std::time::Duration::from_secs(2), watch.message()) + .await + .unwrap() + .unwrap() + .unwrap(); + assert_eq!(upserted.event_type, "upserted"); + assert_eq!(upserted.runtime.unwrap().id, "runtime:catalog-snes"); + + // Common content availability reaches B's Library projection without a path or handle. + let availability_selector = CommonDataSelector { + categories: vec![CommonDataCategory::ContentAvailability as i32], + selected_record_ids: Vec::new(), + }; + let entry = client + .library_get(LibraryGetRequest { + context: Some(context_b.clone()), + installation_id: "id-steam:1".into(), + common_data_categories: Some(availability_selector), + ..Default::default() + }) + .await + .unwrap() + .into_inner() + .entry + .unwrap(); + assert_eq!(entry.runtime_availability.len(), 1); + let available = &entry.runtime_availability[0]; + assert_eq!(available.content_id, "rom:zelda"); + assert_eq!(available.content_kind, "snes-rom"); + assert_eq!(available.runtime_id, "runtime:catalog-snes"); + assert_eq!(available.runtime_name, "Catalog SNES"); + assert_eq!(available.publisher_id, "fixture.plugin"); + assert_eq!(available.platform, std::env::consts::OS); + + // A Library watch delivers the same safe projection when an entry changes. + let listed = client + .library_list(LibraryListRequest { + provider_id: "steam".into(), + page: Some(PageRequest { + context: Some(context_b.clone()), + page_size: 10, + common_data_categories: Some(CommonDataSelector { + categories: vec![CommonDataCategory::ContentAvailability as i32], + selected_record_ids: Vec::new(), + }), + ..Default::default() + }), + ..Default::default() + }) + .await + .unwrap() + .into_inner(); + let mut availability_watch = client + .library_watch(LibraryWatchRequest { + context: Some(context_b.clone()), + after_revision: listed.revision, + provider_id: "steam".into(), + common_data_categories: Some(CommonDataSelector { + categories: vec![CommonDataCategory::ContentAvailability as i32], + selected_record_ids: Vec::new(), + }), + }) + .await + .unwrap() + .into_inner(); + fixture.library(&[ + ("steam:1", Some(5), "Selected Steam game renamed"), + ("steam:2", Some(6), "Other Steam game"), + ("manual:1", Some(9), "Manual game"), + ]); + let changed = tokio::time::timeout( + std::time::Duration::from_secs(2), + availability_watch.message(), + ) + .await + .unwrap() + .unwrap() + .unwrap(); + assert_eq!(changed.event_type, "upserted"); + let watched = changed.entry.unwrap(); + assert_eq!(watched.name, "Selected Steam game renamed"); + assert_eq!(watched.runtime_availability.len(), 1); + assert_eq!( + watched.runtime_availability[0].runtime_id, + "runtime:catalog-snes" + ); + + // A category read is not a mutation authority. + let update = client + .runtimes_update(RuntimeUpdateRequest { + mutation: Some(fixture.mutation("consumer-updates-runtime", 1)), + runtime: Some(RuntimeRecord { + id: "runtime:catalog-snes".into(), + name: "Hijacked".into(), + ..Default::default() + }), + field_mask: vec!["name".into()], + extension_patch: None, + }) + .await + .unwrap_err(); + assert_eq!(update.code(), Code::PermissionDenied); + let remove = client + .runtimes_remove(DomainRemoveRequest { + mutation: Some(fixture.mutation("consumer-removes-runtime", 1)), + resource_id: "runtime:catalog-snes".into(), + }) + .await + .unwrap_err(); + assert_eq!(remove.code(), Code::PermissionDenied); + + let snapshot = policies.recipient_snapshot(&identity_b).unwrap(); + assert!(snapshot.source_recipient_policies.is_empty()); + server.abort(); +} + +/// One reviewed shared emulator resource must reach a real spawned runtime tree and hold its use +/// lease until that tree is confirmed gone. This drives the public RPCs for runtime registration, +/// save-profile declaration and consent, then hands the host-resolved dispatch to the same launch +/// supervisor the desktop uses. +#[cfg(target_os = "linux")] +#[tokio::test(flavor = "multi_thread")] +async fn reviewed_shared_resource_use_is_held_by_a_spawned_runtime_tree() { + use crate::plugin_host::launch_supervisor::{LaunchSupervisor, spawn_native}; + use crate::plugin_host::profile::PluginStateLayout; + use gamenode_plugin_protocol::proto::{ + RuntimeArgumentTemplate as RuntimeArgumentProto, RuntimeRecord, + runtime_argument_template::Value as RuntimeArgumentValue, + }; + use std::os::unix::fs::PermissionsExt; + + use gamenode_core::drm_free::InstallationHost; + + if std::env::var_os("GAMENODE_TEST_HELPER_BINARY").is_none() { + return; + } + let target = TargetGameContext { + game_id: "5".into(), + installation_id: "id-steam:1".into(), + profile_id: "account-a".into(), + revision: "1".into(), + }; + let (fixture, host, _dialog) = Fixture::extension_game( + &[ + cap::FILES_READ, + cap::GAME_CUSTOM_LAUNCH, + cap::GAME_RUNTIME_CREATE, + cap::GAME_SAVES_READ, + cap::GAME_SAVES_CREATE, + ], + target, + Some(answering(&[APPROVE_AND_REMEMBER])), + ) + .await; + host.launch_target.store(1, Ordering::SeqCst); + + let content_root = fixture.game_dir("runtime-shared", &[("card/keep.sav", b"card")]); + // A real executable inside the approved installation so the helper can start and fence it. + std::fs::copy("/bin/sh", content_root.join("emulator")).unwrap(); + std::fs::set_permissions( + content_root.join("emulator"), + std::fs::Permissions::from_mode(0o755), + ) + .unwrap(); + fixture.library_in(&[("steam:1", Some(5), "Selected Steam game", &content_root)]); + let revision_before = fixture.feed.revision_of("steam:1").unwrap(); + + fixture.user_approving(&content_root); + let root = fixture.root_handle("id-steam:1", &["read"]).await; + let runtime_executable = fixture.child(&root, "emulator").await; + fixture + .client() + .runtimes_register(RuntimeRegisterRequest { + mutation: Some(fixture.mutation("register-shared-runtime", 0)), + runtime: Some(RuntimeRecord { + id: "runtime-shared".into(), + name: "Shared card runtime".into(), + version: "1.0".into(), + executable_handle: runtime_executable, + supported_formats: vec!["snes-rom".into()], + platform: std::env::consts::OS.into(), + argument_template: vec![RuntimeArgumentProto { + value: Some(RuntimeArgumentValue::Literal("-c".into())), + }], + ..Default::default() + }), + }) + .await + .unwrap(); + + // The shared folder is a reviewed save folder inside the installation. Its approval already + // resolves the complete affected set, including this installation. + let card = content_root.join("card"); + let card_handle = fixture.approve("id-steam:1", "save", &card).await; + let mut new = super::saves::profile( + "Shared card", + "runtime-shared", + vec![super::saves::directory(&card_handle, "", &["*.sav"])], + ); + new.installation_id = "id-steam:1".into(); + new.shared_resources = vec![gamenode_plugin_protocol::proto::SharedResourceDeclaration { + resource_id: "memory-card".into(), + approved_resource_handle: card_handle, + display_name: "Memory card".into(), + consent: 0, + }]; + let created = fixture.make("shared-card-profile", new).await.unwrap(); + + // Before consent, the host refuses use with an explicit review requirement. + let reviews = crate::plugin_host::shared_resources::PluginSharedResources::new( + fixture.storage.clone(), + fixture.api.profiles(), + fixture.files.clone(), + fixture.feed.clone(), + ); + let publisher = "ab".repeat(32); + assert!( + reviews + .prepared("fixture.plugin", &publisher, &created.profile_id) + .await + .is_err() + ); + reviews + .accept( + "fixture.plugin", + &publisher, + &created.profile_id, + "memory-card", + ) + .await + .unwrap(); + + let recipe = fixture + .client() + .games_propose_custom_launch(CustomLaunchRequest { + context: Some(fixture.context()), + game_id: "5".into(), + installation_id: "id-steam:1".into(), + expected_revision: revision_before, + idempotency_key: "shared-runtime-recipe".into(), + runtime_handle: "runtime-shared".into(), + argv: vec!["sleep 30 & wait".into()], + ..Default::default() + }) + .await + .unwrap() + .into_inner(); + + // The user-approved plan is persisted for the host-side selection, as the desktop does. + let profiles = fixture.api.profiles(); + let layout = PluginStateLayout::new(fixture.plugin_data.join("shared-resource-play-profile")); + profiles.set_state_layout(layout.clone()); + let profile = profiles.current().unwrap(); + let identity = crate::plugin_host::grants::PluginIdentity { + plugin_id: "fixture.plugin".into(), + publisher_fingerprint: publisher.clone(), + profile_id: profile.profile_id().to_owned(), + }; + let scope = crate::plugin_host::grants::GrantScope::Declared { + value: "host-selected-game".into(), + }; + let requests = [cap::GAME_CUSTOM_LAUNCH, cap::FILES_READ] + .into_iter() + .map( + |permission_id| crate::plugin_host::grants::PermissionRequest { + permission_id: permission_id.into(), + required: false, + allowed_scopes: [scope.clone()].into(), + }, + ) + .collect::>(); + let decisions = [cap::GAME_CUSTOM_LAUNCH, cap::FILES_READ] + .into_iter() + .map( + |permission_id| crate::plugin_host::grants::PermissionDecision { + permission_id: permission_id.into(), + scope: scope.clone(), + granted: true, + }, + ) + .collect::>(); + layout + .open_grants(&profile) + .unwrap() + .replace_grants(identity.clone(), &requests, &decisions) + .unwrap(); + layout + .open_activation(&profile) + .unwrap() + .set_enabled("fixture.plugin", true) + .unwrap(); + let resolver = profiles + .resolver("fixture.plugin", &publisher, None) + .unwrap(); + let stored_recipe = host + .custom_launch_recipe( + resolver.library_recipe_owner_key(), + recipe.recipe_id.clone(), + ) + .await + .unwrap() + .unwrap(); + host.launch_recipe_selections.lock().unwrap().insert( + "steam:1".into(), + gamenode_core::library::LaunchRecipeSelection { + entry_key: "steam:1".into(), + owner_key: resolver.library_recipe_owner_key(), + plugin_id: identity.plugin_id, + publisher_fingerprint: identity.publisher_fingerprint, + recipe_id: stored_recipe.recipe_id.clone(), + recipe_revision: stored_recipe.revision, + base_target_revision: stored_recipe.base_target_revision, + approved_plan_fingerprint: String::new(), + }, + ); + + let api = fixture._server.resource_api(); + assert!(api.launch_selected_recipe("steam:1".into()).await.unwrap()); + let dispatch = host + .custom_launch_dispatches + .lock() + .unwrap() + .last() + .cloned() + .unwrap(); + let crate::plugin_host::library::CustomLaunchDispatch::Runtime { + mut command, + lease_keys, + .. + } = dispatch + else { + panic!("the runtime recipe must dispatch a runtime launch"); + }; + assert_eq!(lease_keys.len(), 1, "one reviewed resource, one host lease"); + assert_eq!( + lease_keys[0], + crate::plugin_host::resource_leases::ResourceLeaseKey::from_backing_identity( + std::fs::canonicalize(&card) + .unwrap() + .to_str() + .unwrap() + .as_bytes() + ) + .unwrap() + ); + assert!(command.executable.ends_with("emulator")); + + // The fake host does not inspect the executable; the real adapter does, so bind the identity + // the helper will verify before it spawns anything. It also leaves the working directory to + // the caller, exactly as a reviewed host launch does. + command.file_identity = gamenode_platform::installations::LinuxInstallations + .inspect(&command.executable) + .unwrap() + .file_identity; + command.working_directory = "/".into(); + let supervisor = LaunchSupervisor::start_monitor().unwrap(); + let id = supervisor + .start_for_entry( + fixture.leases.as_ref(), + &lease_keys, + Some("steam:1".into()), + || spawn_native(&command), + ) + .unwrap(); + assert_eq!(supervisor.active_ids().unwrap(), vec![id]); + assert_eq!( + supervisor.ids_for_entry("steam:1").unwrap(), + vec![id], + "the launched tree belongs to the game entry" + ); + assert!( + fixture.leases.lease_exclusive(&lease_keys).is_err(), + "an active supervised tree blocks exclusive backup or restore" + ); + + supervisor.stop(id).unwrap(); + assert!(supervisor.active_ids().unwrap().is_empty()); + assert!( + fixture.leases.lease_exclusive(&lease_keys).is_ok(), + "the confirmed exit releases the use lease" + ); + + // The launch never changed the game identity, its save bytes or the library revision. + assert_eq!( + fixture.feed.revision_of("steam:1").unwrap(), + revision_before + ); + assert_eq!(std::fs::read(card.join("keep.sav")).unwrap(), b"card"); +} + +#[tokio::test(flavor = "multi_thread")] +async fn sdk_client_reviews_custom_launch_and_never_executes_a_declined_or_ungranted_request() { + use gamenode_plugin_sdk::{CustomLaunchRecipe, idempotency_key}; + + let (fixture, host, dialog) = Fixture::game( + &[cap::GAME_LAUNCH, cap::GAME_CUSTOM_LAUNCH], + Some(answering(&[APPROVE, DECLINE])), + ) + .await; + let dialog = dialog.unwrap(); + host.launch_target.store(1, Ordering::SeqCst); + let revision = fixture.revision().await; + let resources = fixture + .host + .resources() + .expect("an API 1.6 session exposes the typed client"); + let actions = fixture + .host + .actions() + .expect("an API 1.6 session exposes the typed client"); + + // Proposing stores the reviewable recipe; it does not ask the user or start anything. + let recipe = CustomLaunchRecipe { + game_id: "3".into(), + installation_id: INSTALLATION.into(), + expected_revision: revision, + uri: "steam://rungameid/3".into(), + argv: vec!["--literal value".into(), "$(not-a-shell)".into()], + environment_set: [("FIXTURE_MODE".into(), "reviewed".into())].into(), + environment_unset: vec!["FIXTURE_LEGACY_MODE".into()], + ..CustomLaunchRecipe::default() + }; + let proposed = resources + .propose_custom_launch(&recipe, "", &idempotency_key()) + .await + .unwrap(); + assert!(!proposed.recipe_id.is_empty()); + assert_eq!(proposed.recipe_revision, 1); + assert!(proposed.job_id.is_empty()); + assert_eq!(proposed.state, JobState::Unspecified as i32); + assert!(proposed.refusal_code.is_empty()); + assert_eq!(dialog.shown.lock().unwrap().len(), 0); + { + let stored = host.custom_launch_recipes.lock().unwrap(); + assert_eq!(stored.len(), 1); + let stored = stored.values().next().unwrap(); + assert_eq!(stored.arguments, recipe.argv); + assert_eq!(stored.uri, recipe.uri); + assert_eq!( + stored + .environment_set + .get("FIXTURE_MODE") + .map(String::as_str), + Some("reviewed") + ); + assert_eq!( + stored + .environment_unset + .iter() + .map(String::as_str) + .collect::>(), + ["FIXTURE_LEGACY_MODE"] + ); + } + + // Requesting execution opens the common launch review; approving it runs the exact recipe. + let requested = resources + .request_custom_launch( + "3", + INSTALLATION, + revision, + &proposed.recipe_id, + proposed.recipe_revision, + "", + &idempotency_key(), + ) + .await + .unwrap(); + assert_eq!(requested.state, JobState::Queued as i32); + assert_eq!(requested.message, "awaiting confirmation"); + let approved = super::action_recipes::wait_for_job(&actions, &requested.job_id) + .await + .unwrap(); + assert_eq!( + (approved.state, approved.result_code.as_str()), + (JobState::Succeeded, "opened") + ); + assert_eq!(dialog.shown.lock().unwrap().len(), 1); + let review = dialog.shown.lock().unwrap()[0] + .launch_plan + .as_ref() + .expect("custom launches use the shared launch review") + .clone(); + assert_eq!(review.source_id, "fixture"); + assert_eq!(review.target, "steam://rungameid/3"); + assert_eq!(review.arguments, recipe.argv); + assert_eq!( + review + .environment_set + .get("FIXTURE_MODE") + .map(String::as_str), + Some("reviewed") + ); + assert_eq!(review.environment_unset, ["FIXTURE_LEGACY_MODE"]); + assert!(review.differences.contains(&"custom-arguments".into())); + assert_eq!(host.custom_launch_dispatches.lock().unwrap().len(), 1); + + // Declining the next review fails the job and dispatches nothing. + let declined = resources + .request_custom_launch( + "3", + INSTALLATION, + revision, + &proposed.recipe_id, + proposed.recipe_revision, + "", + &idempotency_key(), + ) + .await + .unwrap(); + let refused = super::action_recipes::wait_for_job(&actions, &declined.job_id) + .await + .unwrap(); + assert_eq!( + (refused.state, refused.result_code.as_str()), + (JobState::Failed, "declined") + ); + assert_eq!(dialog.shown.lock().unwrap().len(), 2); + assert_eq!(host.custom_launch_dispatches.lock().unwrap().len(), 1); + assert!(host.opened.lock().unwrap().is_empty()); + + // Revoking the grant denies proposal and execution; the SDK never falls back to standard + // launch, so no process starts. + fixture + .api + .revoke_session_permission("fixture", cap::GAME_CUSTOM_LAUNCH) + .await; + let denied = resources + .propose_custom_launch(&recipe, "", &idempotency_key()) + .await + .expect_err("a proposal without the grant must be denied"); + assert_eq!(denied.code(), Code::PermissionDenied); + let denied = resources + .request_custom_launch( + "3", + INSTALLATION, + revision, + &proposed.recipe_id, + proposed.recipe_revision, + "", + &idempotency_key(), + ) + .await + .expect_err("execution without the grant must be denied"); + assert_eq!(denied.code(), Code::PermissionDenied); + assert_eq!(dialog.shown.lock().unwrap().len(), 2); + assert_eq!(host.custom_launch_dispatches.lock().unwrap().len(), 1); + assert!(host.opened.lock().unwrap().is_empty()); +} diff --git a/crates/app/src/plugin_host/resources/tests/jobs.rs b/crates/app/src/plugin_host/resources/tests/jobs.rs new file mode 100644 index 000000000..71f984950 --- /dev/null +++ b/crates/app/src/plugin_host/resources/tests/jobs.rs @@ -0,0 +1,456 @@ +//! `JobsGet`, `JobsWatch` and `JobsCancel` over the real local socket (task 7.1). +//! +//! No operation returns a job yet (installs and backups come with 7.2 onward), so the tests +//! start jobs from the host side the way those operations will: `ResourceApi::start_job`. + +use std::sync::atomic::AtomicUsize; + +use tokio::sync::Notify; +use tokio_stream::StreamExt; + +use super::*; +use crate::plugin_host::jobs::{JobContext, JobOwner, Outcome, work}; + +/// The permission of the operation that creates the test jobs. +const WRITE: &str = cap::STORAGE_WRITE; +const GRANTS: &[&str] = &[cap::STORAGE_WRITE, cap::STORAGE_READ]; + +impl Fixture { + pub(super) fn service(&self) -> ResourceApi { + ResourceApi::new( + self.api.clone(), + self.feed.clone(), + self.storage.clone(), + self.files.clone(), + self.network.clone(), + self.notifications.clone(), + self.jobs.clone(), + self.intents.clone(), + self.saves.clone(), + self.snapshots.clone(), + self.leases.clone(), + self.processes.clone(), + ) + } + + fn job_caller(&self) -> ResourceCaller { + self.api + .authorize_resource(Some(&self.context()), WRITE) + .unwrap() + } + + fn owner(&self) -> JobOwner { + JobOwner::of(&self.job_caller()).unwrap() + } + + /// What the operation that returns a job does: starts it for the authenticated caller. + fn start_job(&self, key: &str, hash: u8, run: crate::plugin_host::jobs::Work) -> JobReply { + self.service() + .start_job( + &self.job_caller(), + self.context(), + WRITE, + key, + [hash; 32], + None, + run, + ) + .unwrap() + .0 + } + + pub(super) async fn job(&self, id: &str) -> Result { + self.client() + .jobs_get(JobGetRequest { + context: Some(self.context()), + job_id: id.into(), + }) + .await + .map(Response::into_inner) + } + + pub(super) async fn cancel_job(&self, key: &str, id: &str) -> Result { + self.client() + .jobs_cancel(JobCancelRequest { + mutation: Some(self.mutation(key, 0)), + job_id: id.into(), + }) + .await + .map(Response::into_inner) + } + + async fn watch_job( + &self, + id: &str, + after_sequence: u64, + ) -> Result, Status> { + self.client() + .jobs_watch(JobWatchRequest { + context: Some(self.context()), + job_id: id.into(), + after_sequence, + }) + .await + .map(Response::into_inner) + } + + /// Waits for the job to end, reading the host's own record: it needs no session. + async fn job_over(&self, owner: &JobOwner, id: &str) -> JobReply { + for _ in 0..400 { + let reply = self.jobs.get(owner, id).unwrap(); + if matches!( + reply.state(), + JobState::Succeeded | JobState::Failed | JobState::Cancelled + ) { + return reply; + } + tokio::time::sleep(Duration::from_millis(5)).await; + } + panic!("the job did not finish"); + } +} + +/// Work that waits for `go`, then commits one effect if its fence still allows it. +fn commits_after(go: Arc, effects: Arc) -> crate::plugin_host::jobs::Work { + work(move |ctx: JobContext| async move { + go.notified().await; + ctx.progress(50); + match ctx.check() { + Ok(()) => { + effects.fetch_add(1, Ordering::SeqCst); + Outcome::succeeded("committed", "") + } + Err(status) => Outcome::stopped(&status), + } + }) +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_plugin_reads_cancels_and_watches_its_own_job() { + let fixture = Fixture::new(GRANTS).await; + let go = Arc::new(Notify::new()); + let effects = Arc::new(AtomicUsize::new(0)); + let started = fixture.start_job("one", 1, commits_after(go.clone(), effects.clone())); + + let reply = fixture.job(&started.job_id).await.unwrap(); + assert_eq!(reply.job_id, started.job_id); + assert!(matches!( + reply.state(), + JobState::Queued | JobState::Running + )); + + let mut events = fixture.watch_job(&started.job_id, 0).await.unwrap(); + go.notify_one(); + let mut seen = Vec::new(); + while let Some(event) = events.next().await { + seen.push(event.unwrap()); + } + // The stream replays from the start, in order, and ends after the outcome. + let sequences: Vec<_> = seen.iter().map(|e| e.sequence).collect(); + assert_eq!(sequences, (1..=seen.len() as u64).collect::>()); + let last = seen.last().unwrap(); + assert_eq!( + ( + last.state(), + last.result_code.as_str(), + last.progress_percent + ), + (JobState::Succeeded, "committed", 100) + ); + assert!(seen.iter().all(|e| e.job_id == started.job_id)); + assert_eq!(effects.load(Ordering::SeqCst), 1); + + // Resuming after an event gives what followed; a position in the future is refused. + let mut rest = fixture + .watch_job(&started.job_id, last.sequence - 1) + .await + .unwrap(); + assert_eq!(rest.next().await.unwrap().unwrap().sequence, last.sequence); + assert!(rest.next().await.is_none()); + let future = fixture + .watch_job(&started.job_id, last.sequence + 1) + .await + .unwrap_err(); + assert_eq!(future.code(), Code::OutOfRange); + + // Cancelling a finished job says how it finished. + let cancelled = fixture.cancel_job("c", &started.job_id).await.unwrap(); + assert_eq!(cancelled.state(), JobState::Succeeded); +} + +#[tokio::test(flavor = "multi_thread")] +async fn cancelling_a_running_job_stops_it_before_it_commits() { + let fixture = Fixture::new(GRANTS).await; + let effects = Arc::new(AtomicUsize::new(0)); + let id = fixture + .start_job( + "one", + 1, + work({ + let effects = effects.clone(); + move |mut ctx: JobContext| async move { + ctx.cancelled().await; + match ctx.check() { + Ok(()) => { + effects.fetch_add(1, Ordering::SeqCst); + Outcome::succeeded("committed", "") + } + Err(status) => Outcome::stopped(&status), + } + } + }), + ) + .job_id; + let reply = fixture.cancel_job("stop", &id).await.unwrap(); + assert_eq!(reply.state(), JobState::Cancelled); + assert_eq!(effects.load(Ordering::SeqCst), 0); + // Asking again, even with a new key, is the same answer. + let again = fixture.cancel_job("stop-again", &id).await.unwrap(); + assert_eq!( + (again.state(), again.revision), + (JobState::Cancelled, reply.revision) + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn bad_requests_are_refused_without_naming_anything() { + let fixture = Fixture::new(GRANTS).await; + let id = fixture + .start_job("one", 1, work(|_| async { Outcome::succeeded("ok", "") })) + .job_id; + + let unknown = fixture.job("job-0000").await.unwrap_err(); + assert_eq!(unknown.code(), Code::NotFound); + assert_eq!( + fixture.job("").await.unwrap_err().code(), + Code::InvalidArgument + ); + assert_eq!( + fixture.job(&"x".repeat(129)).await.unwrap_err().code(), + Code::InvalidArgument + ); + // The cancel call needs a key like every mutation, and its context. + assert_eq!( + fixture.cancel_job("", &id).await.unwrap_err().code(), + Code::InvalidArgument + ); + let no_context = fixture + .client() + .jobs_get(JobGetRequest { + context: None, + job_id: id.clone(), + }) + .await + .unwrap_err(); + assert_eq!(no_context.code(), Code::Unauthenticated); + // A forged context is not accepted either. + let mut forged = fixture.context(); + forged.session_credential = vec![0; forged.session_credential.len()]; + let denied = fixture + .client() + .jobs_get(JobGetRequest { + context: Some(forged), + job_id: id, + }) + .await + .unwrap_err(); + assert_eq!(denied.code(), Code::PermissionDenied); +} + +#[tokio::test(flavor = "multi_thread")] +async fn losing_the_creating_permission_denies_every_call_and_blocks_the_commit() { + let fixture = Fixture::new(GRANTS).await; + let go = Arc::new(Notify::new()); + let effects = Arc::new(AtomicUsize::new(0)); + let id = fixture + .start_job("one", 1, commits_after(go.clone(), effects.clone())) + .job_id; + let owner = fixture.owner(); + let mut events = fixture.watch_job(&id, 0).await.unwrap(); + assert_eq!(events.next().await.unwrap().unwrap().sequence, 1); + + // The plugin loses the permission of the operation that made the job. + fixture + .api + .revoke_session_permission("fixture", WRITE) + .await; + for denied in [ + fixture.job(&id).await.unwrap_err(), + fixture.cancel_job("c", &id).await.unwrap_err(), + fixture.watch_job(&id, 0).await.unwrap_err(), + ] { + assert_eq!(denied.code(), Code::PermissionDenied); + } + // A watch that was open ends with the denial instead of going on delivering. + go.notify_one(); + let mut ended = None; + while let Some(item) = events.next().await { + if let Err(status) = item { + ended = Some(status); + break; + } + } + assert_eq!( + ended.expect("the watch must end").code(), + Code::PermissionDenied + ); + + // The work reached its commit and was stopped: no effect, and the host's own record says why. + let over = fixture.job_over(&owner, &id).await; + assert_eq!(effects.load(Ordering::SeqCst), 0); + assert_eq!( + (over.state(), over.result_code.as_str()), + (JobState::Failed, "permission_denied") + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_changed_grant_set_stops_the_commit_even_if_the_permission_is_kept() { + let fixture = Fixture::new(GRANTS).await; + let go = Arc::new(Notify::new()); + let effects = Arc::new(AtomicUsize::new(0)); + let id = fixture + .start_job("one", 1, commits_after(go.clone(), effects.clone())) + .job_id; + let owner = fixture.owner(); + + // Another permission goes: the creating one is still held, so the plugin can still ask... + fixture + .api + .revoke_session_permission("fixture", cap::STORAGE_READ) + .await; + assert!(fixture.job(&id).await.is_ok()); + // ...but the effect, which was authorized under the old grants, is not committed. + go.notify_one(); + let over = fixture.job_over(&owner, &id).await; + assert_eq!(effects.load(Ordering::SeqCst), 0); + assert_eq!( + (over.state(), over.result_code.as_str()), + (JobState::Failed, "failed_precondition") + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_restarted_plugin_finds_its_jobs_but_not_the_authority_to_commit() { + let mut fixture = Fixture::new(GRANTS).await; + let owner = fixture.owner(); + let go = Arc::new(Notify::new()); + let effects = Arc::new(AtomicUsize::new(0)); + let finished = fixture.start_job("done", 1, quick()).job_id; + fixture.job_over(&owner, &finished).await; + let waiting = fixture + .start_job("waiting", 2, commits_after(go.clone(), effects.clone())) + .job_id; + + // The same plugin in a new session owns both jobs... + fixture.reconnect().await; + let reply = fixture.job(&finished).await.unwrap(); + assert_eq!(reply.state(), JobState::Succeeded); + assert_eq!(fixture.job(&waiting).await.unwrap().job_id, waiting); + // ...and a retry of a start, in the new session, is the same job. + let (retry, replayed) = fixture + .service() + .start_job( + &fixture.job_caller(), + fixture.context(), + WRITE, + "done", + [1; 32], + None, + quick(), + ) + .unwrap(); + assert!(replayed); + assert_eq!(retry.job_id, finished); + + // The waiting job was authorized by the session that is gone: it commits nothing. + go.notify_one(); + let over = fixture.job_over(&owner, &waiting).await; + assert_eq!(effects.load(Ordering::SeqCst), 0); + assert_eq!( + (over.state(), over.result_code.as_str()), + (JobState::Failed, "session_ended") + ); + assert_eq!( + fixture.job(&waiting).await.unwrap().result_code, + "session_ended" + ); + + // An owner of another plugin gets nothing, not even a different refusal. + let stranger = JobOwner::for_tests(9, fixture.job_caller().profile_epoch); + assert_eq!( + fixture.jobs.get(&stranger, &waiting).unwrap_err().code(), + Code::NotFound + ); +} + +fn quick() -> crate::plugin_host::jobs::Work { + work(|_| async { Outcome::succeeded("ok", "") }) +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_profile_switch_hides_the_old_jobs_and_stops_their_commit() { + let mut fixture = Fixture::new(GRANTS).await; + let go = Arc::new(Notify::new()); + let effects = Arc::new(AtomicUsize::new(0)); + let id = fixture + .start_job("one", 1, commits_after(go.clone(), effects.clone())) + .job_id; + let old_owner = fixture.owner(); + + // Another account signs in. The plugin restarts into its profile, which has no such job. + fixture.api.profiles().update(Some("b"), true); + fixture.api.fence_third_party_sessions().await; + fixture.reconnect().await; + assert_eq!(fixture.job(&id).await.unwrap_err().code(), Code::NotFound); + assert_eq!( + fixture.cancel_job("c", &id).await.unwrap_err().code(), + Code::NotFound + ); + assert_eq!( + fixture.watch_job(&id, 0).await.unwrap_err().code(), + Code::NotFound + ); + + // The old job was ended and its effect never committed, even if the work wakes up now. + go.notify_one(); + for _ in 0..400 { + if fixture.jobs.active() == 0 { + break; + } + tokio::time::sleep(Duration::from_millis(5)).await; + } + assert_eq!(effects.load(Ordering::SeqCst), 0); + // The same plugin and key in the new profile start a job of their own. + let (fresh, replayed) = fixture + .service() + .start_job( + &fixture.job_caller(), + fixture.context(), + WRITE, + "one", + [1; 32], + None, + quick(), + ) + .unwrap(); + assert!(!replayed); + assert_ne!(fresh.job_id, id); + assert_ne!(fixture.owner(), old_owner); +} + +#[tokio::test] +async fn describe_api_lists_the_jobs_methods_without_a_permission_of_their_own() { + let served: Vec<_> = crate::plugin_host::resources::SERVED + .iter() + .filter(|served| served.method.starts_with("Jobs")) + .collect(); + assert_eq!( + served + .iter() + .map(|served| served.method) + .collect::>(), + ["JobsGet", "JobsWatch", "JobsCancel"] + ); + assert!(served.iter().all(|served| served.permission.is_empty())); +} diff --git a/crates/app/src/plugin_host/resources/tests/libraries.rs b/crates/app/src/plugin_host/resources/tests/libraries.rs new file mode 100644 index 000000000..1fb0d854d --- /dev/null +++ b/crates/app/src/plugin_host/resources/tests/libraries.rs @@ -0,0 +1,682 @@ +//! Logical libraries over the real local socket, with scripted folder consent and Core dispatch. +use super::*; + +const GRANTS: &[&str] = &[ + cap::LIBRARY_ROOTS_READ, + cap::LIBRARY_ROOTS_CREATE, + cap::LIBRARY_ROOTS_UPDATE, + cap::LIBRARY_ROOTS_DELETE, +]; +impl Fixture { + async fn make_library(&self, key: &str) -> LibraryMutationReply { + self.client() + .libraries_create(LibraryCreateRequest { + mutation: Some(self.mutation(key, 0)), + name: "Games".into(), + description: "Local library".into(), + }) + .await + .unwrap() + .into_inner() + } + async fn logical_library(&self, id: &str) -> Result { + self.client() + .libraries_get(DomainGetRequest { + context: Some(self.context()), + resource_id: id.into(), + ..Default::default() + }) + .await + .map(|r| r.into_inner().library.unwrap()) + } + async fn add_library_root( + &self, + key: &str, + library: &LibraryMutationReply, + display: &str, + suggestions: Vec, + ) -> Result { + self.client() + .libraries_add_root(LibraryRootAddRequest { + mutation: Some(self.mutation(key, library.revision)), + library_id: library.resource_id.clone(), + display_name: display.into(), + declared_locations: suggestions, + ..Default::default() + }) + .await + .map(Response::into_inner) + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn library_crud_is_revision_checked_replayable_private_and_durable() { + let f = Fixture::new(GRANTS).await; + let created = f.make_library("create").await; + assert_eq!(f.make_library("create").await, created); + let edited = f + .client() + .libraries_update(LibraryUpdateRequest { + mutation: Some(f.mutation("rename", created.revision)), + library_id: created.resource_id.clone(), + name: "Renamed".into(), + field_mask: vec!["name".into()], + ..Default::default() + }) + .await + .unwrap() + .into_inner(); + assert!(edited.revision > created.revision); + let conflict = f + .client() + .libraries_update(LibraryUpdateRequest { + mutation: Some(f.mutation("stale", created.revision)), + library_id: created.resource_id.clone(), + name: "Lost".into(), + field_mask: vec!["name".into()], + ..Default::default() + }) + .await + .unwrap() + .into_inner(); + assert_eq!(conflict.outcome, MutationOutcome::RevisionConflict as i32); + assert_eq!( + f.logical_library(&created.resource_id).await.unwrap().name, + "Renamed" + ); + assert_eq!( + f.logical_library("library-foreign") + .await + .unwrap_err() + .code(), + Code::NotFound + ); + let restarted = Fixture::restarted(GRANTS, f.plugin_data.clone()).await; + assert_eq!( + restarted + .logical_library(&created.resource_id) + .await + .unwrap() + .name, + "Renamed" + ); + f.client() + .libraries_remove(DomainRemoveRequest { + mutation: Some(f.mutation("remove", edited.revision)), + resource_id: created.resource_id.clone(), + }) + .await + .unwrap(); + assert_eq!( + f.logical_library(&created.resource_id) + .await + .unwrap_err() + .code(), + Code::NotFound + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn roots_need_consent_without_an_installation_and_disclose_both_scanners() { + let f = Fixture::new(GRANTS).await; + let host = f.with_host(); + let library = f.make_library("create").await; + let folder = f.game_dir("unregistered", &[("game.exe", b"fictional")]); + let approver = f.user_approving(&folder); + let added = f + .add_library_root( + "root", + &library, + "Chosen root", + vec![DeclaredLocation { + kind: "library".into(), + location: folder.to_str().unwrap().into(), + description: "Suggested, unverified".into(), + }], + ) + .await + .unwrap(); + let row = f.logical_library(&library.resource_id).await.unwrap(); + assert_eq!(row.roots.len(), 1); + assert_eq!(row.roots[0].id, added.resource_id); + assert_eq!( + row.roots[0].availability, + InspectionAvailability::Available as i32 + ); + let confirmed = approver.confirmed.lock().unwrap(); + assert_eq!(confirmed[0].kind, "library"); + assert!(confirmed[0].declared_by_plugin); + assert_eq!( + confirmed[0].operations, + vec!["read", "plugin_discovery", "core_executable_discovery"] + ); + drop(confirmed); + let scans = host.scan_roots.lock().unwrap(); + let roots = scans.values().flatten().collect::>(); + assert_eq!(roots.len(), 1); + assert!((roots[0].valid)().is_ok()); + assert!(roots[0].root.declared); + assert_eq!( + std::fs::read(folder.join("game.exe")).unwrap(), + b"fictional" + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn declined_or_invalid_suggestions_never_register_or_dispatch_a_root() { + let f = Fixture::new(GRANTS).await; + let host = f.with_host(); + let library = f.make_library("create").await; + let folder = f.game_dir("suggested", &[]); + let approver = f.user_approving(&folder); + approver.consent.store(false, Ordering::SeqCst); + assert_eq!( + f.add_library_root( + "declined", + &library, + "Root", + vec![DeclaredLocation { + kind: "library".into(), + location: folder.to_str().unwrap().into(), + description: "Unverified".into() + }] + ) + .await + .unwrap_err() + .code(), + Code::PermissionDenied + ); + assert!( + f.logical_library(&library.resource_id) + .await + .unwrap() + .roots + .is_empty() + ); + assert!( + host.scan_roots + .lock() + .unwrap() + .values() + .all(|r| r.is_empty()) + ); + assert_eq!( + f.add_library_root( + "invalid", + &library, + "Root", + vec![DeclaredLocation { + kind: "library".into(), + location: "../escape".into(), + description: String::new() + }] + ) + .await + .unwrap_err() + .code(), + Code::InvalidArgument + ); + assert_eq!(approver.asked.lock().unwrap().len(), 1); +} + +#[tokio::test(flavor = "multi_thread")] +async fn unavailable_roots_do_not_prevent_healthy_additions_and_removing_roots_deletes_no_files() { + let f = Fixture::new(GRANTS).await; + let host = f.with_host(); + let library = f.make_library("create").await; + let folder = f.game_dir("one", &[("save", b"keep")]); + f.user_approving(&folder); + let first = f + .add_library_root("first", &library, "First", vec![]) + .await + .unwrap(); + let previous = host + .scan_roots + .lock() + .unwrap() + .values() + .flatten() + .next() + .unwrap() + .clone(); + let away = folder.with_extension("away"); + std::fs::rename(&folder, &away).unwrap(); + let second_folder = f.game_dir("two", &[]); + f.user_approving(&second_folder); + let revision = LibraryMutationReply { + resource_id: library.resource_id.clone(), + revision: first.revision, + outcome: first.outcome, + }; + let second = f + .add_library_root("second", &revision, "Second", vec![]) + .await + .unwrap(); + assert!( + (previous.valid)().is_err(), + "a changed contribution fences the old scan" + ); + let row = f.logical_library(&library.resource_id).await.unwrap(); + assert_eq!( + row.roots[0].availability, + InspectionAvailability::Disconnected as i32 + ); + assert_eq!( + row.roots[1].availability, + InspectionAvailability::Available as i32 + ); + f.client() + .libraries_remove_root(LibraryRootRemoveRequest { + mutation: Some(f.mutation("remove-root", second.revision)), + library_id: library.resource_id.clone(), + root_id: first.resource_id, + }) + .await + .unwrap(); + let scans = host.scan_roots.lock().unwrap(); + let roots = scans.values().flatten().collect::>(); + assert_eq!(roots.len(), 1); + assert_eq!(roots[0].root.path, second_folder.to_str().unwrap()); + drop(scans); + assert_eq!(std::fs::read(away.join("save")).unwrap(), b"keep"); + assert!(!folder.exists()); +} + +#[tokio::test(flavor = "multi_thread")] +async fn crud_revocation_ends_api_delivery_but_only_session_loss_fences_approved_core_work() { + let f = Fixture::new(GRANTS).await; + let host = f.with_host(); + let mut watch = f + .client() + .libraries_watch(DomainWatchRequest { + context: Some(f.context()), + ..Default::default() + }) + .await + .unwrap() + .into_inner(); + let library = f.make_library("create").await; + let event = tokio::time::timeout(Duration::from_secs(5), watch.message()) + .await + .unwrap() + .unwrap() + .unwrap(); + assert_eq!(event.library.unwrap().id, library.resource_id); + let folder = f.game_dir("root", &[]); + f.user_approving(&folder); + f.add_library_root("root", &library, "Root", vec![]) + .await + .unwrap(); + let scan = host + .scan_roots + .lock() + .unwrap() + .values() + .flatten() + .next() + .unwrap() + .clone(); + f.api + .revoke_session_permission("fixture", cap::LIBRARY_ROOTS_CREATE) + .await; + assert!( + (scan.valid)().is_ok(), + "standing root approval is independent of create permission" + ); + assert!( + f.logical_library(&library.resource_id).await.is_ok(), + "read remains independently granted" + ); + f.api + .revoke_session_permission("fixture", cap::LIBRARY_ROOTS_READ) + .await; + assert_eq!( + f.logical_library(&library.resource_id) + .await + .unwrap_err() + .code(), + Code::PermissionDenied + ); + // A change already delivered before revocation can precede the terminal refusal. + let denied = tokio::time::timeout(Duration::from_secs(5), async { + loop { + match watch.message().await { + Err(e) => break e, + Ok(Some(_)) => {} + Ok(None) => panic!("watch ended without denial"), + } + } + }) + .await + .unwrap(); + assert_eq!(denied.code(), Code::PermissionDenied); + assert!((scan.valid)().is_ok()); + f.api.disconnect("fixture").await; + assert!( + (scan.valid)().is_err(), + "a disconnected plugin cannot continue Core work" + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn library_operations_have_independent_grants_and_unknown_ids_reveal_nothing() { + let f = Fixture::new(&[cap::LIBRARY_ROOTS_CREATE]).await; + let library = f.make_library("create").await; + assert_eq!( + f.logical_library(&library.resource_id) + .await + .unwrap_err() + .code(), + Code::PermissionDenied + ); + assert_eq!( + f.client() + .libraries_remove(DomainRemoveRequest { + mutation: Some(f.mutation("remove", library.revision)), + resource_id: library.resource_id + }) + .await + .unwrap_err() + .code(), + Code::PermissionDenied + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn library_watch_reports_volume_availability_without_a_configuration_edit() { + let f = Fixture::new(GRANTS).await; + f.with_host(); + let library = f.make_library("create").await; + let folder = f.game_dir("watched", &[]); + f.user_approving(&folder); + let added = f + .add_library_root("root", &library, "Root", vec![]) + .await + .unwrap(); + let mut watch = f + .client() + .libraries_watch(DomainWatchRequest { + context: Some(f.context()), + after_revision: added.revision, + ..Default::default() + }) + .await + .unwrap() + .into_inner(); + // Let the first metadata observation establish its baseline, then remove the path. + tokio::time::sleep(Duration::from_millis(1200)).await; + let away = folder.with_extension("away"); + std::fs::rename(&folder, &away).unwrap(); + let event = tokio::time::timeout(Duration::from_secs(5), watch.message()) + .await + .unwrap() + .unwrap() + .unwrap(); + assert_eq!(event.event_type, "availability_changed"); + assert_eq!( + event.library.unwrap().roots[0].availability, + InspectionAvailability::Disconnected as i32 + ); + assert!(!folder.exists()); +} + +#[tokio::test(flavor = "multi_thread")] +async fn provider_free_plugins_cannot_replay_each_others_mutation_receipts() { + let f = Fixture::new(GRANTS).await; + let mut first = f + .api + .authorize_resource(Some(&f.context()), cap::LIBRARY_ROOTS_CREATE) + .unwrap(); + first.provider_id.clear(); + let mut second = first.clone(); + let mut identity = first.namespace.as_ref().unwrap().identity().clone(); + identity.plugin_id = "org.example.other".into(); + second.namespace = Some( + crate::plugin_host::namespace::ExternalNamespaceResolver::new( + identity, + None, + second.profile_epoch, + ) + .unwrap(), + ); + let receipts = super::super::mutations::Mutations::default(); + let hash = [7u8; 32]; + receipts.remember( + &first, + "same-key", + hash, + &MutationReply { + resource_id: "private-library".into(), + revision: 1, + outcome: MutationOutcome::Applied as i32, + }, + ); + assert!( + receipts + .replay(&second, "same-key", hash) + .unwrap() + .is_none() + ); + assert_eq!( + receipts + .replay(&first, "same-key", hash) + .unwrap() + .unwrap() + .resource_id, + "private-library" + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn approved_library_handles_allow_scoped_reads_only_and_replacement_fences_old_handles() { + let mut grants = GRANTS.to_vec(); + grants.extend([cap::FILES_READ, cap::FILES_WRITE]); + let f = Fixture::new(&grants).await; + f.with_host(); + let library = f.make_library("create").await; + let one = f.game_dir("source-one", &[("game.exe", b"first")]); + f.user_approving(&one); + let added = f + .add_library_root("root", &library, "Source", vec![]) + .await + .unwrap(); + let record = f.logical_library(&library.resource_id).await.unwrap(); + let handle = &record.roots[0].approved_root_handle; + let file = f.child(handle, "game.exe").await; + assert_eq!(f.cat(&file, 0, 20).await.unwrap().contents, b"first"); + assert_eq!( + f.client() + .files_write(FilesWriteRequest { + mutation: Some(f.mutation("write", 0)), + file_handle: file.clone(), + contents: b"forbidden".to_vec(), + ..Default::default() + }) + .await + .unwrap_err() + .code(), + Code::PermissionDenied + ); + let two = f.game_dir("source-two", &[("game.exe", b"second")]); + f.user_approving(&two); + let updated = f + .client() + .libraries_update_root(LibraryRootUpdateRequest { + mutation: Some(f.mutation("replace", added.revision)), + library_id: library.resource_id.clone(), + root_id: added.resource_id.clone(), + field_mask: vec!["folder".into()], + ..Default::default() + }) + .await + .unwrap() + .into_inner(); + assert_eq!(f.ls(handle).await.unwrap_err().code(), Code::NotFound); + assert_eq!( + f.cat(&file, 0, 20).await.unwrap_err().code(), + Code::NotFound + ); + let replacement = f.logical_library(&library.resource_id).await.unwrap(); + assert_eq!(replacement.roots[0].id, added.resource_id); + let current = &replacement.roots[0].approved_root_handle; + assert_eq!( + f.cat(&f.child(current, "game.exe").await, 0, 20) + .await + .unwrap() + .contents, + b"second" + ); + f.client() + .libraries_remove_root(LibraryRootRemoveRequest { + mutation: Some(f.mutation("remove", updated.revision)), + library_id: library.resource_id, + root_id: added.resource_id, + }) + .await + .unwrap(); + assert_eq!(f.ls(current).await.unwrap_err().code(), Code::NotFound); + assert_eq!(std::fs::read(one.join("game.exe")).unwrap(), b"first"); + assert_eq!(std::fs::read(two.join("game.exe")).unwrap(), b"second"); +} + +#[tokio::test(flavor = "multi_thread")] +async fn root_approval_resumes_on_session_start_without_any_crud_permission() { + let f = Fixture::new(GRANTS).await; + f.with_host(); + let library = f.make_library("create").await; + let folder = f.game_dir("persistent-root", &[]); + f.user_approving(&folder); + f.add_library_root("root", &library, "Persistent", vec![]) + .await + .unwrap(); + let reopened = Fixture::restarted(&[cap::NOTIFICATIONS_PUBLISH], f.plugin_data.clone()).await; + let host = reopened.with_host(); + tokio::time::timeout(Duration::from_secs(5), async { + loop { + let started = host + .scan_roots + .lock() + .unwrap() + .values() + .flatten() + .any(|r| r.root.path == folder.to_str().unwrap() && (r.valid)().is_ok()); + if started { + break; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .unwrap(); + assert_eq!( + reopened + .logical_library(&library.resource_id) + .await + .unwrap_err() + .code(), + Code::PermissionDenied + ); + reopened.api.disconnect("fixture").await; + assert!( + host.scan_roots + .lock() + .unwrap() + .values() + .flatten() + .all(|r| (r.valid)().is_err()) + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn disabling_one_approved_root_stops_its_contribution_and_leaves_the_other_enabled() { + let f = Fixture::new(GRANTS).await; + let host = f.with_host(); + let library = f.make_library("create").await; + let first = f.game_dir("first", &[]); + f.user_approving(&first); + let added = f + .add_library_root("first", &library, "First", vec![]) + .await + .unwrap(); + let second = f.game_dir("second", &[]); + f.user_approving(&second); + let parent = LibraryMutationReply { + resource_id: library.resource_id.clone(), + revision: added.revision, + outcome: added.outcome, + }; + let added_second = f + .add_library_root("second", &parent, "Second", vec![]) + .await + .unwrap(); + f.client() + .libraries_update_root(LibraryRootUpdateRequest { + mutation: Some(f.mutation("disable", added_second.revision)), + library_id: library.resource_id, + root_id: added.resource_id, + watching: false, + field_mask: vec!["watching".into()], + ..Default::default() + }) + .await + .unwrap(); + let roots = host.scan_roots.lock().unwrap(); + let current = roots + .values() + .flatten() + .filter(|r| (r.valid)().is_ok()) + .collect::>(); + assert_eq!(current.len(), 1); + assert_eq!(current[0].root.path, second.to_str().unwrap()); + assert!(first.exists()); + assert!(second.exists()); +} + +#[tokio::test(flavor = "multi_thread")] +async fn account_switch_fences_old_monitor_contexts_without_exposing_or_resuming_its_roots() { + let mut f = Fixture::new(GRANTS).await; + let host = f.with_host(); + let library = f.make_library("create").await; + let folder = f.game_dir("account-a-root", &[]); + f.user_approving(&folder); + f.add_library_root("root", &library, "A", vec![]) + .await + .unwrap(); + let old = host + .scan_roots + .lock() + .unwrap() + .values() + .flatten() + .next() + .unwrap() + .clone(); + let original_epoch = f.context().profile_epoch; + f.api.profiles().update(Some("b"), true); + assert!((old.valid)().is_err()); + assert!( + f.api + .resource_session_contexts() + .iter() + .all(|context| context.profile_epoch == original_epoch), + "lifecycle contexts must retain the original epoch" + ); + f.api.fence_third_party_sessions().await; + f.reconnect().await; + assert_eq!( + f.logical_library(&library.resource_id) + .await + .unwrap_err() + .code(), + Code::NotFound + ); + assert!( + host.scan_roots + .lock() + .unwrap() + .values() + .flatten() + .all(|r| (r.valid)().is_err()) + ); + assert!(folder.exists()); +} diff --git a/crates/app/src/plugin_host/resources/tests/locations.rs b/crates/app/src/plugin_host/resources/tests/locations.rs new file mode 100644 index 000000000..63d8d469f --- /dev/null +++ b/crates/app/src/plugin_host/resources/tests/locations.rs @@ -0,0 +1,1074 @@ +//! The `Locations` service over the real local socket (task 13.3): the size, the access and the +//! modification times of approved places, read from metadata alone. + +use std::os::unix::fs::PermissionsExt; +use std::path::Path; +use std::time::{Duration as StdDuration, UNIX_EPOCH}; + +use super::saves::{INSTALLATION, directory, profile}; +use super::*; + +const INSPECT: &[&str] = &[ + cap::GAME_STORAGE_INSPECT, + cap::GAME_SAVES_INSPECT, + cap::GAME_SAVES_READ, + cap::GAME_SAVES_CREATE, + cap::FILES_READ, +]; + +fn running_as_root() -> bool { + rustix::process::geteuid().is_root() +} + +impl Fixture { + fn locations( + &self, + ) -> gamenode_plugin_protocol::proto::locations_client::LocationsClient { + self.host.locations_client() + } + + async fn size(&self, handle: &str, max_entries: u32) -> Result { + self.locations() + .get_size(LocationSizeRequest { + context: Some(self.context()), + approved_resource_handle: handle.into(), + max_entries, + }) + .await + .map(Response::into_inner) + } + + async fn access(&self, handle: &str, entries: &[&str]) -> Result { + self.locations() + .get_access(LocationAccessRequest { + context: Some(self.context()), + approved_resource_handle: handle.into(), + entry_handles: entries.iter().map(|entry| (*entry).into()).collect(), + }) + .await + .map(Response::into_inner) + } + + async fn modified( + &self, + handle: &str, + max_entries: u32, + ) -> Result { + self.locations() + .get_last_modified(LocationLastModifiedRequest { + context: Some(self.context()), + approved_resource_handle: handle.into(), + max_entries, + }) + .await + .map(Response::into_inner) + } +} + +fn set_time(path: &Path, seconds: u64, nanos: u32) { + std::fs::File::options() + .write(true) + .open(path) + .unwrap() + .set_modified(UNIX_EPOCH + StdDuration::new(seconds, nanos)) + .unwrap(); +} + +#[tokio::test(flavor = "multi_thread")] +async fn the_size_of_an_approved_folder_is_its_logical_bytes_and_counts() { + let (fixture, saves) = Fixture::emulator(INSPECT).await; + let root = fixture.approve(INSTALLATION, "save", &saves).await; + let size = fixture.size(&root, 0).await.unwrap(); + assert_eq!( + ( + size.logical_bytes, + size.file_count, + size.directory_count, + size.complete + ), + (4 + 5, 2, 3, true) // card.gci and s1.sav; GC, USA and states + ); + assert_eq!(size.availability, InspectionAvailability::Available as i32); + // A folder below the approved one measures what is in it. + let states = fixture.child(&root, "states").await; + let below = fixture.size(&states, 0).await.unwrap(); + assert_eq!( + (below.logical_bytes, below.file_count, below.directory_count), + (5, 1, 0) + ); + // A single file is its own size. + let file = fixture.child(&states, "s1.sav").await; + let one = fixture.size(&file, 0).await.unwrap(); + assert_eq!( + (one.logical_bytes, one.file_count, one.directory_count), + (5, 1, 0) + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn the_permission_follows_the_kind_of_folder_and_needs_no_file_permission() { + let (fixture, saves) = Fixture::emulator(INSPECT).await; + let install = fixture.approve(INSTALLATION, "installation", &saves).await; + let save = fixture.approve(INSTALLATION, "save", &saves).await; + assert!(fixture.size(&install, 0).await.is_ok()); + assert!(fixture.size(&save, 0).await.is_ok()); + + // Losing the permission of one kind ends that kind only. + fixture + .api + .revoke_session_permission("fixture", cap::GAME_STORAGE_INSPECT) + .await; + assert_eq!( + fixture.size(&install, 0).await.unwrap_err().code(), + Code::PermissionDenied + ); + assert!(fixture.size(&save, 0).await.is_ok()); + fixture + .api + .revoke_session_permission("fixture", cap::GAME_SAVES_INSPECT) + .await; + assert_eq!( + fixture.size(&save, 0).await.unwrap_err().code(), + Code::PermissionDenied + ); + for denied in [ + fixture.access(&save, &[]).await.unwrap_err(), + fixture.modified(&save, 0).await.unwrap_err(), + ] { + assert_eq!(denied.code(), Code::PermissionDenied); + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn inspecting_needs_no_right_to_read_files() { + let (fixture, saves) = Fixture::emulator(INSPECT).await; + let root = fixture.approve(INSTALLATION, "save", &saves).await; + let file = fixture + .child(&fixture.child(&root, "states").await, "s1.sav") + .await; + fixture + .api + .revoke_session_permission("fixture", cap::FILES_READ) + .await; + // The metadata is still there, and the content still cannot be read. + assert_eq!(fixture.size(&root, 0).await.unwrap().file_count, 2); + assert_eq!(fixture.size(&file, 0).await.unwrap().logical_bytes, 5); + assert_eq!( + fixture.ls(&root).await.unwrap_err().code(), + Code::PermissionDenied + ); + assert_eq!( + fixture.cat(&file, 0, 10).await.unwrap_err().code(), + Code::PermissionDenied + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_forged_unknown_or_revoked_place_is_not_found_and_another_plugins_profile_is_not_there() { + let (fixture, saves) = Fixture::emulator(INSPECT).await; + let root = fixture.approve(INSTALLATION, "save", &saves).await; + for handle in ["forged", "profile-unknown", &format!("{root}x")] { + assert_eq!( + fixture.size(handle, 0).await.unwrap_err().code(), + Code::NotFound, + "{handle}" + ); + } + assert_eq!( + fixture.size("", 0).await.unwrap_err().code(), + Code::InvalidArgument + ); + + // Revoke the approval: its handle stops working at once. + let caller = fixture.caller(); + fixture + .storage + .run_for_host( + caller.namespace.as_ref().unwrap(), + caller.profile_epoch, + |namespace| { + let id = namespace.approval_for(INSTALLATION, "save")?.unwrap().id; + namespace.revoke_approval(&id) + }, + ) + .await + .unwrap(); + assert_eq!( + fixture.size(&root, 0).await.unwrap_err().code(), + Code::NotFound + ); + // A forged or missing context is refused. + let mut forged = fixture.context(); + forged.session_credential = vec![0; forged.session_credential.len()]; + let denied = fixture + .locations() + .get_size(LocationSizeRequest { + context: Some(forged), + approved_resource_handle: root, + max_entries: 0, + }) + .await + .unwrap_err(); + assert_eq!(denied.code(), Code::PermissionDenied); + assert_eq!( + fixture + .locations() + .get_size(LocationSizeRequest::default()) + .await + .unwrap_err() + .code(), + Code::Unauthenticated + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_walk_that_was_cut_says_it_is_not_complete() { + let (fixture, saves) = Fixture::emulator(INSPECT).await; + let root = fixture.approve(INSTALLATION, "save", &saves).await; + let cut = fixture.size(&root, 2).await.unwrap(); + assert!(!cut.complete); + assert!(cut.file_count + cut.directory_count <= 2); + assert!(fixture.size(&root, 5).await.unwrap().complete); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_folder_that_is_gone_or_unreadable_is_reported_by_availability_not_as_zero_bytes() { + let (fixture, saves) = Fixture::emulator(INSPECT).await; + let root = fixture.approve(INSTALLATION, "save", &saves).await; + + if !running_as_root() { + std::fs::set_permissions(&saves, std::fs::Permissions::from_mode(0o000)).unwrap(); + let locked = fixture.size(&root, 0).await; + std::fs::set_permissions(&saves, std::fs::Permissions::from_mode(0o755)).unwrap(); + let locked = locked.unwrap(); + assert_eq!( + locked.availability, + InspectionAvailability::Inaccessible as i32 + ); + assert!(!locked.complete); + } + + // The folder is moved away (an unmounted drive looks the same to this layer): it is missing, + // and nothing is created in its place. + let away = saves.with_extension("away"); + std::fs::rename(&saves, &away).unwrap(); + let missing = fixture.size(&root, 0).await.unwrap(); + assert_eq!(missing.availability, InspectionAvailability::Missing as i32); + assert!(!missing.complete); + assert!(!saves.exists(), "no replacement folder is made"); + for reply in [ + fixture.modified(&root, 0).await.unwrap().availability, + fixture.access(&root, &[]).await.unwrap().entries[0].availability, + ] { + assert_eq!(reply, InspectionAvailability::Missing as i32); + } + + // It comes back and answers again, with what is there. + std::fs::rename(&away, &saves).unwrap(); + assert_eq!(fixture.size(&root, 0).await.unwrap().file_count, 2); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_profile_measures_the_union_of_its_folders_narrowed_by_its_rules_counting_overlaps_once() +{ + let (fixture, saves) = Fixture::emulator(INSPECT).await; + let root = fixture.approve(INSTALLATION, "save", &saves).await; + let states = fixture.child(&root, "states").await; + std::fs::write(saves.join("states/old.tmp"), b"tmp!").unwrap(); + std::fs::write(saves.join("notes.txt"), b"notes").unwrap(); + + // The whole folder and the folder below it overlap: states/ files count once. + let overlapping = fixture + .make( + "a", + profile( + "Everything", + "rt", + vec![ + directory(&root, "All", &[]), + directory(&states, "States", &[]), + ], + ), + ) + .await + .unwrap(); + let all = fixture.size(&overlapping.profile_id, 0).await.unwrap(); + // card.gci 4 + s1.sav 5 + old.tmp 4 + notes.txt 5, each once. + assert_eq!( + (all.logical_bytes, all.file_count, all.complete), + (18, 4, true) + ); + + // Rules narrow the selection: only .gci anywhere and .sav in states, minus temporary files. + let narrowed = fixture + .make( + "b", + profile( + "Saves only", + "rt", + vec![directory( + &root, + "Cards", + &["**/*.gci", "**/*.sav", "!**/*.tmp"], + )], + ), + ) + .await + .unwrap(); + let only = fixture.size(&narrowed.profile_id, 0).await.unwrap(); + assert_eq!((only.logical_bytes, only.file_count), (4 + 5, 2)); + + // A rule that selects nothing is a total of zero that is complete, which is an honest zero. + let nothing = fixture + .make( + "c", + profile("None", "rt", vec![directory(&root, "x", &["*.nothing"])]), + ) + .await + .unwrap(); + let zero = fixture.size(¬hing.profile_id, 0).await.unwrap(); + assert_eq!( + (zero.logical_bytes, zero.file_count, zero.complete), + (0, 0, true) + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_profile_with_a_folder_whose_approval_is_gone_gives_a_partial_total() { + let (fixture, saves) = Fixture::emulator(INSPECT).await; + let root = fixture.approve(INSTALLATION, "save", &saves).await; + let other = fixture.game_dir("other-emulator", &[("x.sav", b"123456")]); + let second = fixture.approve(INSTALLATION, "prefix", &other).await; + let created = fixture + .make( + "a", + profile( + "Two", + "rt", + vec![directory(&root, "", &[]), directory(&second, "", &[])], + ), + ) + .await + .unwrap(); + assert!(fixture.size(&created.profile_id, 0).await.unwrap().complete); + + let caller = fixture.caller(); + fixture + .storage + .run_for_host( + caller.namespace.as_ref().unwrap(), + caller.profile_epoch, + |namespace| { + let id = namespace.approval_for(INSTALLATION, "prefix")?.unwrap().id; + namespace.revoke_approval(&id) + }, + ) + .await + .unwrap(); + let partial = fixture.size(&created.profile_id, 0).await.unwrap(); + // What can still be reached is counted; the total says it is not the whole. + assert_eq!((partial.file_count, partial.complete), (2, false)); +} + +#[tokio::test(flavor = "multi_thread")] +async fn last_modified_gives_each_entry_its_time_and_the_newest_apart_from_the_folders_own() { + let (fixture, saves) = Fixture::emulator(INSPECT).await; + let root = fixture.approve(INSTALLATION, "save", &saves).await; + set_time(&saves.join("GC/USA/card.gci"), 1_700_000_100, 250_000_000); + set_time(&saves.join("states/s1.sav"), 1_700_000_200, 0); + // The folder itself was touched later than any file in it. + set_time_dir(&saves, 1_800_000_000); + + let reply = fixture.modified(&root, 0).await.unwrap(); + assert_eq!(reply.availability, InspectionAvailability::Available as i32); + // The folder's own time comes first, under the handle that was asked about. + let own = &reply.entries[0]; + assert_eq!( + (own.entry_handle.as_str(), own.modified_at), + (root.as_str(), 1_800_000_000) + ); + // The newest is the newest of the entries below, not the folder's time. + assert_eq!(reply.aggregate_latest_at, Some(1_700_000_200)); + let by_time: Vec<_> = reply.entries[1..] + .iter() + .map(|entry| (entry.modified_at, entry.precision.as_str())) + .collect(); + assert!(by_time.contains(&(1_700_000_100, "subsecond"))); + assert!(by_time.contains(&(1_700_000_200, "whole_second"))); + // Each entry comes with a handle that is good for the next call. + assert!( + reply + .entries + .iter() + .all(|entry| !entry.entry_handle.is_empty()) + ); + let one = fixture.size(&reply.entries[1].entry_handle, 0).await; + assert!(one.is_ok()); + + // The list is bounded. + let few = fixture.modified(&root, 1).await.unwrap(); + assert_eq!(few.entries.len(), 2, "the folder and one entry"); +} + +fn set_time_dir(path: &Path, seconds: u64) { + std::fs::File::open(path) + .unwrap() + .set_modified(UNIX_EPOCH + StdDuration::from_secs(seconds)) + .unwrap(); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_profiles_last_modified_covers_its_selected_files_only() { + let (fixture, saves) = Fixture::emulator(INSPECT).await; + let root = fixture.approve(INSTALLATION, "save", &saves).await; + set_time(&saves.join("GC/USA/card.gci"), 1_700_000_100, 0); + set_time(&saves.join("states/s1.sav"), 1_700_000_900, 0); + let created = fixture + .make( + "a", + profile("Cards", "rt", vec![directory(&root, "", &["GC/**/*.gci"])]), + ) + .await + .unwrap(); + let reply = fixture.modified(&created.profile_id, 0).await.unwrap(); + assert_eq!(reply.aggregate_latest_at, Some(1_700_000_100)); + assert_eq!(reply.entries.len(), 1); +} + +#[tokio::test(flavor = "multi_thread")] +async fn access_tells_read_only_metadata_apart_from_what_the_user_may_do() { + let (fixture, saves) = Fixture::emulator(INSPECT).await; + let root = fixture.approve(INSTALLATION, "save", &saves).await; + let states = fixture.child(&root, "states").await; + let file = fixture.child(&states, "s1.sav").await; + let path = saves.join("states/s1.sav"); + + // The folder itself, when no entry is named. + let folder = fixture.access(&root, &[]).await.unwrap(); + assert_eq!( + folder.availability, + InspectionAvailability::Available as i32 + ); + let [entry] = folder.entries.try_into().unwrap(); + assert_eq!(entry.entry_handle, root); + assert_eq!(entry.read_only_state, "writable"); + assert!( + entry + .effective_access + .starts_with("read=allowed write=allowed create=allowed") + ); + + // A file whose mode says read-only: the metadata and the real answer are separate fields. + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o444)).unwrap(); + let reply = fixture.access(&root, &[&file]).await.unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap(); + let [locked] = reply.entries.try_into().unwrap(); + assert_eq!(locked.entry_handle, file); + assert_eq!(locked.read_only_state, "read_only"); + assert!(locked.effective_access.starts_with("read=allowed")); + if !running_as_root() { + assert!(locked.effective_access.contains("write=denied")); + } + // "create" does not apply to a file, and nothing is guessed for it. + assert!(locked.effective_access.contains("create=unknown")); +} + +#[tokio::test(flavor = "multi_thread")] +async fn access_refuses_entries_of_another_place_and_too_many() { + let (fixture, saves) = Fixture::emulator(INSPECT).await; + let root = fixture.approve(INSTALLATION, "save", &saves).await; + let elsewhere = fixture.game_dir("elsewhere", &[("a.sav", b"1")]); + let theirs = fixture.approve("id-fixture:2", "save", &elsewhere).await; + let theirs_file = fixture.child(&theirs, "a.sav").await; + // An entry of another approval is not an entry of this place. + assert_eq!( + fixture + .access(&root, &[&theirs_file]) + .await + .unwrap_err() + .code(), + Code::NotFound + ); + assert_eq!( + fixture.access(&root, &["forged"]).await.unwrap_err().code(), + Code::NotFound + ); + let many: Vec = (0..101).map(|n| format!("h{n}")).collect(); + let refs: Vec<&str> = many.iter().map(String::as_str).collect(); + assert_eq!( + fixture.access(&root, &refs).await.unwrap_err().code(), + Code::InvalidArgument + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_profiles_access_lists_each_of_its_folders_and_reports_a_lost_one_as_missing() { + let (fixture, saves) = Fixture::emulator(INSPECT).await; + let root = fixture.approve(INSTALLATION, "save", &saves).await; + let other = fixture.game_dir("other-emulator", &[("x.sav", b"123456")]); + let second = fixture.approve(INSTALLATION, "prefix", &other).await; + let created = fixture + .make( + "a", + profile( + "Two", + "rt", + vec![directory(&root, "", &[]), directory(&second, "", &[])], + ), + ) + .await + .unwrap(); + let reply = fixture.access(&created.profile_id, &[]).await.unwrap(); + assert_eq!(reply.entries.len(), 2); + assert!( + reply + .entries + .iter() + .all(|e| e.availability == InspectionAvailability::Available as i32) + ); + // A profile is inspected as a whole. + assert_eq!( + fixture + .access(&created.profile_id, &["h"]) + .await + .unwrap_err() + .code(), + Code::InvalidArgument + ); + // Revoke one folder's approval: that folder is reported missing, the other still answers. + let caller = fixture.caller(); + fixture + .storage + .run_for_host( + caller.namespace.as_ref().unwrap(), + caller.profile_epoch, + |namespace| { + let id = namespace.approval_for(INSTALLATION, "prefix")?.unwrap().id; + namespace.revoke_approval(&id) + }, + ) + .await + .unwrap(); + let after = fixture.access(&created.profile_id, &[]).await.unwrap(); + let states: Vec = after.entries.iter().map(|e| e.availability).collect(); + assert!(states.contains(&(InspectionAvailability::Missing as i32))); + assert!(states.contains(&(InspectionAvailability::Available as i32))); +} + +#[tokio::test(flavor = "multi_thread")] +async fn inspecting_changes_nothing() { + let (fixture, saves) = Fixture::emulator(INSPECT).await; + let root = fixture.approve(INSTALLATION, "save", &saves).await; + let file = saves.join("states/s1.sav"); + set_time(&file, 1_650_000_000, 7); + let before = std::fs::metadata(&file).unwrap(); + let dir_mode = std::fs::metadata(&saves).unwrap().permissions().mode(); + let dir_time = std::fs::metadata(&saves).unwrap().modified().unwrap(); + let created = fixture + .make("a", profile("P", "rt", vec![directory(&root, "", &[])])) + .await + .unwrap(); + + for handle in [root.as_str(), created.profile_id.as_str()] { + fixture.size(handle, 0).await.unwrap(); + fixture.modified(handle, 0).await.unwrap(); + fixture.access(handle, &[]).await.unwrap(); + } + let after = std::fs::metadata(&file).unwrap(); + assert_eq!(after.modified().unwrap(), before.modified().unwrap()); + assert_eq!(after.permissions().mode(), before.permissions().mode()); + assert_eq!(std::fs::read(&file).unwrap(), b"state"); + assert_eq!( + std::fs::metadata(&saves).unwrap().permissions().mode(), + dir_mode + ); + assert_eq!( + std::fs::metadata(&saves).unwrap().modified().unwrap(), + dir_time + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn describe_api_lists_inspection_methods_and_requires_a_resource() { + let (fixture, _) = Fixture::emulator(INSPECT).await; + let described = fixture.host.describe_api().await.unwrap(); + let served: Vec<_> = described + .methods + .iter() + .filter(|method| method.service == "Locations") + .map(|method| (method.method.as_str(), method.permissions.clone())) + .collect(); + let either = vec![ + cap::GAME_STORAGE_INSPECT.to_owned(), + cap::GAME_SAVES_INSPECT.to_owned(), + ]; + assert_eq!( + served, + [ + ("Inspect", either.clone()), + ("WatchAvailability", either.clone()), + ("GetSize", either.clone()), + ("GetAccess", either.clone()), + ("GetLastModified", either.clone()), + ("GetFingerprint", either.clone()), + ("Compare", either), + ] + ); + let mut client = fixture.locations(); + let context = Some(fixture.context()); + assert_eq!( + client + .inspect(LocationInspectRequest { + context: context.clone(), + ..Default::default() + }) + .await + .unwrap_err() + .code(), + Code::InvalidArgument + ); + assert_eq!( + client + .watch_availability(LocationAvailabilityWatchRequest { + context, + ..Default::default() + }) + .await + .unwrap_err() + .code(), + Code::InvalidArgument + ); +} + +impl Fixture { + async fn inspect_volume(&self, handle: &str) -> Result { + self.locations() + .inspect(LocationInspectRequest { + context: Some(self.context()), + approved_resource_handle: handle.into(), + ..Default::default() + }) + .await + .map(tonic::Response::into_inner) + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn volume_inspection_reports_separate_dimensions_and_missing_folders_preserve_profiles() { + let (fixture, saves) = Fixture::emulator(INSPECT).await; + let root = fixture.approve(INSTALLATION, "save", &saves).await; + let original = fixture + .inspect_volume(&root) + .await + .unwrap() + .location + .unwrap(); + assert_eq!( + original.availability, + InspectionAvailability::Available as i32 + ); + assert!(!original.volume_identity_token.is_empty()); + assert!(!original.interface_type.is_empty()); + assert!(!original.attachment.is_empty()); + assert!(!original.evidence.is_empty()); + let created = fixture + .make( + "volume-profile", + profile("Keep", "rt", vec![directory(&root, "", &[])]), + ) + .await + .unwrap(); + let away = saves.with_extension("away"); + std::fs::rename(&saves, &away).unwrap(); + let missing = fixture + .inspect_volume(&root) + .await + .unwrap() + .location + .unwrap(); + assert_eq!(missing.availability, InspectionAvailability::Missing as i32); + assert!(!saves.exists()); + assert!(fixture.inspect_volume(&created.profile_id).await.is_ok()); + std::fs::rename(&away, &saves).unwrap(); + assert_eq!( + fixture + .inspect_volume(&root) + .await + .unwrap() + .location + .unwrap() + .volume_identity_token, + original.volume_identity_token + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn replaced_volume_identity_cannot_inherit_scope_and_watch_reports_the_change() { + let (fixture, saves) = Fixture::emulator(INSPECT).await; + let root = fixture.approve(INSTALLATION, "save", &saves).await; + let mut stream = fixture + .locations() + .watch_availability(LocationAvailabilityWatchRequest { + context: Some(fixture.context()), + approved_resource_handle: root.clone(), + after_sequence: 0, + }) + .await + .unwrap() + .into_inner(); + let first = stream.message().await.unwrap().unwrap(); + assert_eq!(first.availability, InspectionAvailability::Available as i32); + // Simulate a platform observation whose identity differs from the persisted approval. + let caller = fixture.caller(); + fixture + .storage + .run_for_host( + caller.namespace.as_ref().unwrap(), + caller.profile_epoch, + |namespace| { + let mut approval = namespace.approval_for(INSTALLATION, "save")?.unwrap(); + approval.volume_token = "a-different-volume".into(); + { + let guard: crate::plugin_host::library::CommitGuard = Box::new(|| Ok(())); + namespace.save_approval(&approval, &guard) + } + }, + ) + .await + .unwrap(); + let event = tokio::time::timeout(StdDuration::from_secs(5), stream.message()) + .await + .unwrap() + .unwrap() + .unwrap(); + assert!(event.sequence > first.sequence); + assert_eq!( + event.availability, + InspectionAvailability::Disconnected as i32 + ); + assert!(event.volume_identity_token.is_empty()); + assert!(!fixture.size(&root, 0).await.unwrap().complete); + assert_eq!( + fixture + .inspect_volume(&root) + .await + .unwrap() + .location + .unwrap() + .capacity_bytes, + 0 + ); + fixture + .api + .revoke_session_permission("fixture", cap::GAME_SAVES_INSPECT) + .await; + assert_eq!( + tokio::time::timeout(StdDuration::from_secs(5), stream.message()) + .await + .unwrap() + .unwrap_err() + .code(), + Code::PermissionDenied + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_removed_save_is_missing_while_its_approved_storage_remains_available() { + let (fixture, saves) = Fixture::emulator(INSPECT).await; + let root = fixture.approve(INSTALLATION, "save", &saves).await; + let states = fixture.child(&root, "states").await; + let file = fixture.child(&states, "s1.sav").await; + std::fs::remove_file(saves.join("states/s1.sav")).unwrap(); + assert_eq!( + fixture + .inspect_volume(&root) + .await + .unwrap() + .location + .unwrap() + .availability, + InspectionAvailability::Available as i32 + ); + assert_eq!( + fixture + .inspect_volume(&file) + .await + .unwrap() + .location + .unwrap() + .availability, + InspectionAvailability::Missing as i32 + ); + let total = fixture.size(&root, 0).await.unwrap(); + assert!(total.complete); + assert_eq!(total.file_count, 1); + assert!(!saves.join("states/s1.sav").exists()); +} + +const RUNTIME: &[&str] = &[ + cap::GAME_STORAGE_INSPECT, + cap::GAME_SAVES_INSPECT, + cap::GAME_RUNTIME_CREATE, + cap::GAME_RUNTIME_READ, + cap::GAME_RUNTIME_UPDATE, + cap::FILES_READ, +]; + +#[tokio::test(flavor = "multi_thread")] +async fn a_runtime_executable_is_inspected_without_exposing_its_path() { + let (fixture, runtime, dir) = Fixture::approved_runtime(RUNTIME).await; + set_time(&dir.join("emulator"), 1_700_000_123, 500_000_000); + let handle = runtime.executable_handle; + assert!(!handle.contains('/') && !handle.contains(dir.to_str().unwrap())); + + let size = fixture.size(&handle, 0).await.unwrap(); + assert_eq!( + ( + size.logical_bytes, + size.file_count, + size.directory_count, + size.complete + ), + (6, 1, 0, true), + "the runtime executable is a single approved file" + ); + assert_eq!(size.availability, InspectionAvailability::Available as i32); + + let access = fixture.access(&handle, &[]).await.unwrap(); + let entry = access.entries.first().unwrap(); + assert_eq!(access.entries.len(), 1); + assert_eq!(entry.entry_handle, handle); + assert_eq!(entry.read_only_state, "writable"); + assert!(entry.effective_access.starts_with("read=allowed")); + assert_eq!( + access.availability, + InspectionAvailability::Available as i32 + ); + + let modified = fixture.modified(&handle, 0).await.unwrap(); + let stamp = modified.entries.first().unwrap(); + assert_eq!(modified.entries.len(), 1); + assert_eq!(stamp.modified_at, 1_700_000_123); + assert_eq!(stamp.precision, "subsecond"); + assert!(!stamp.entry_handle.is_empty() && stamp.entry_handle != handle); + assert_eq!(modified.aggregate_latest_at, Some(1_700_000_123)); + assert_eq!( + fixture + .size(&stamp.entry_handle, 0) + .await + .unwrap() + .logical_bytes, + 6 + ); + + // No answer carries the folder or file path: only opaque handles and observations. + for reply in [ + format!("{size:?}"), + format!("{access:?}"), + format!("{modified:?}"), + ] { + assert!(!reply.contains(dir.to_str().unwrap()), "{reply}"); + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_runtime_revision_mints_a_new_handle_without_redirecting_the_old_one() { + let (fixture, runtime, dir) = Fixture::approved_runtime(RUNTIME).await; + std::fs::write(dir.join("other-emulator"), b"other executable").unwrap(); + let root = fixture + .request_access("id-fixture:1", &["read"], &["installation"]) + .await + .unwrap() + .handles + .remove(0) + .handle; + let other = fixture.child(&root, "other-emulator").await; + let updated = fixture.update_runtime_executable(&runtime, other).await; + + assert_eq!(updated.revision, runtime.revision + 1); + assert_ne!(updated.executable_handle, runtime.executable_handle); + // A revision points the new handle at the new file, and leaves the old handle where it was. + assert_eq!( + fixture + .size(&updated.executable_handle, 0) + .await + .unwrap() + .logical_bytes, + 16 + ); + assert_eq!( + fixture + .size(&runtime.executable_handle, 0) + .await + .unwrap() + .logical_bytes, + 6 + ); + assert!(!updated.executable_handle.contains(dir.to_str().unwrap())); + assert!(!format!("{updated:?}").contains(dir.to_str().unwrap())); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_runtime_handle_is_fenced_by_its_session_approval_and_scope() { + let (fixture, runtime, dir) = Fixture::approved_runtime(RUNTIME).await; + let handle = runtime.executable_handle; + let caller = fixture.caller(); + let approval_id = fixture + .storage + .run_for_host( + caller.namespace.as_ref().unwrap(), + caller.profile_epoch, + |namespace| { + Ok(namespace + .approval_for(INSTALLATION, "installation")? + .unwrap() + .id) + }, + ) + .await + .unwrap(); + + // A handle sealed for another session is not this session's, even with the same approval. + let foreign = + fixture + .files + .seal_handle("another-session", &approval_id, &["emulator".to_owned()]); + // A well-formed handle still cannot name a path outside its approval. + let escape = fixture.files.seal_handle( + &caller.session_id, + &approval_id, + &["..".to_owned(), "outside".to_owned()], + ); + for denied in [ + fixture.size("forged", 0).await.unwrap_err(), + fixture.size(&foreign, 0).await.unwrap_err(), + fixture.access(&foreign, &[]).await.unwrap_err(), + fixture.modified(&foreign, 0).await.unwrap_err(), + ] { + assert_eq!(denied.code(), Code::NotFound); + assert!(!denied.message().contains(dir.to_str().unwrap())); + } + assert_eq!( + fixture.size(&escape, 0).await.unwrap_err().code(), + Code::PermissionDenied + ); + + // A game now installed in the same folder was never part of the confirmed scope. + fixture.library_in(&[ + ("fixture:1", Some(3), "Emulated", &dir), + ("fixture:2", Some(4), "Also here", &dir), + ]); + for denied in [ + fixture.size(&handle, 0).await.unwrap_err(), + fixture.access(&handle, &[]).await.unwrap_err(), + fixture.modified(&handle, 0).await.unwrap_err(), + ] { + assert_eq!(denied.code(), Code::FailedPrecondition); + } + + // Revoking the approval takes the place with it, as it does for a save folder. + fixture + .storage + .run_for_host( + caller.namespace.as_ref().unwrap(), + caller.profile_epoch, + move |namespace| namespace.revoke_approval(&approval_id), + ) + .await + .unwrap(); + assert_eq!( + fixture.size(&handle, 0).await.unwrap_err().code(), + Code::NotFound + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_runtime_handle_needs_installation_inspection_not_file_read() { + let (fixture, runtime, _) = Fixture::approved_runtime(RUNTIME).await; + let handle = runtime.executable_handle; + assert_eq!(fixture.size(&handle, 0).await.unwrap().file_count, 1); + + fixture + .api + .revoke_session_permission("fixture", cap::FILES_READ) + .await; + assert_eq!(fixture.size(&handle, 0).await.unwrap().file_count, 1); + assert_eq!(fixture.access(&handle, &[]).await.unwrap().entries.len(), 1); + assert_eq!(fixture.modified(&handle, 0).await.unwrap().entries.len(), 1); + + fixture + .api + .revoke_session_permission("fixture", cap::GAME_STORAGE_INSPECT) + .await; + for denied in [ + fixture.size(&handle, 0).await.unwrap_err(), + fixture.access(&handle, &[]).await.unwrap_err(), + fixture.modified(&handle, 0).await.unwrap_err(), + ] { + assert_eq!(denied.code(), Code::PermissionDenied); + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn unavailable_storage_never_creates_a_source_folder_or_erases_its_profile() { + let (fixture, saves) = Fixture::emulator(INSPECT).await; + let root = fixture.approve(INSTALLATION, "save", &saves).await; + let created = fixture + .make( + "unavailable", + profile("Keep", "rt", vec![directory(&root, "", &[])]), + ) + .await + .unwrap(); + let away = saves.with_extension("away"); + std::fs::rename(&saves, &away).unwrap(); + let caller = fixture.caller(); + // Model a mount whose approved identity is no longer visible, independently + // of the existing ancestor's storage. No privileged native unmount is needed. + fixture + .storage + .run_for_host( + caller.namespace.as_ref().unwrap(), + caller.profile_epoch, + |namespace| { + let mut approval = namespace.approval_for(INSTALLATION, "save")?.unwrap(); + approval.volume_token = "unavailable-volume".into(); + let guard: crate::plugin_host::library::CommitGuard = Box::new(|| Ok(())); + namespace.save_approval(&approval, &guard) + }, + ) + .await + .unwrap(); + for handle in [&root, &created.profile_id] { + let description = fixture + .inspect_volume(handle) + .await + .unwrap() + .location + .unwrap(); + assert_eq!( + description.availability, + InspectionAvailability::Disconnected as i32 + ); + assert_eq!(description.capacity_bytes, 0); + assert!(!fixture.size(handle, 0).await.unwrap().complete); + assert!( + !saves.exists(), + "inspection must never recreate an absent mount source" + ); + } + fixture + .storage + .run_for_host( + caller.namespace.as_ref().unwrap(), + caller.profile_epoch, + move |namespace| { + let row = namespace.save_profile(&created.profile_id)?.unwrap(); + assert_eq!(row.revision, created.revision); + Ok(()) + }, + ) + .await + .unwrap(); + assert_eq!(std::fs::read(away.join("states/s1.sav")).unwrap(), b"state"); +} diff --git a/crates/app/src/plugin_host/resources/tests/network.rs b/crates/app/src/plugin_host/resources/tests/network.rs new file mode 100644 index 000000000..452d52f7c --- /dev/null +++ b/crates/app/src/plugin_host/resources/tests/network.rs @@ -0,0 +1,836 @@ +//! `NetworkFetch` over the real local socket (task 6.3). The fetch itself is a scripted stand-in; +//! the address, redirect, size and deadline rules are tested with the real client in +//! `gamenode_platform::plugin_network`, and the real client is used here for the destinations it +//! must refuse. + +use std::sync::Mutex as StdMutex; +use std::sync::atomic::AtomicUsize; + +use async_trait::async_trait; +use gamenode_platform::plugin_network::{FetchError, Request as Fetch, Response as Fetched}; +use gamenode_plugin_protocol::prost::Message; + +use super::*; +use crate::plugin_host::grants::{ + PermissionDecision, PluginIdentity, manifest_permission_requests, +}; +use crate::plugin_host::network::{ + AllowOrigin, ApprovedOrigins, Fetcher, OriginScopes, canonical_origin, +}; +use crate::plugin_host::profile::PluginStateLayout; +use futures_util::future::BoxFuture; + +const NETWORK: &[&str] = &[cap::NETWORK_FETCH]; + +/// What the fake saw of one request. +#[derive(Clone, Debug)] +pub(super) struct Seen { + pub(super) url: String, + pub(super) method: String, + pub(super) headers: Vec<(String, String)>, + pub(super) body: Vec, + pub(super) max_response_bytes: usize, + pub(super) timeout: Duration, +} + +type Script = + Arc BoxFuture<'static, Result> + Send + Sync>; + +#[derive(Default)] +pub(super) struct FakeFetcher { + calls: StdMutex>, + script: StdMutex>, + gate: StdMutex>>, + started: AtomicUsize, +} + +#[async_trait] +impl Fetcher for FakeFetcher { + async fn fetch(&self, request: Fetch, allow: AllowOrigin) -> Result { + let seen = Seen { + url: request.url().to_string(), + method: request.method().to_owned(), + headers: request.headers().to_vec(), + body: request.body().to_vec(), + max_response_bytes: request.max_response_bytes(), + timeout: request.timeout(), + }; + self.calls.lock().unwrap().push(seen.clone()); + self.started.fetch_add(1, Ordering::SeqCst); + let gate = self.gate.lock().unwrap().clone(); + if let Some(gate) = gate { + gate.acquire().await.unwrap().forget(); + } + let script = self.script.lock().unwrap().clone(); + match script { + Some(script) => script(seen, allow).await, + None => { + let origin = request.origin().unwrap(); + if !allow(origin.clone()).await { + return Err(FetchError::Denied); + } + Ok(Fetched { + status: 200, + headers: vec![("content-type".into(), "text/plain".into())], + body: b"fetched".to_vec(), + final_origin: origin, + }) + } + } + } +} + +impl FakeFetcher { + pub(super) fn calls(&self) -> Vec { + self.calls.lock().unwrap().clone() + } + + pub(super) fn script(&self, script: impl Fn(Seen, AllowOrigin) -> F + Send + Sync + 'static) + where + F: Future> + Send + 'static, + { + *self.script.lock().unwrap() = + Some(Arc::new(move |seen, allow| Box::pin(script(seen, allow)))); + } +} + +/// The origins the user approved, changeable between calls. +#[derive(Default)] +pub(super) struct Origins { + approved: StdMutex>, + asked_for: StdMutex>, +} + +#[async_trait] +impl OriginScopes for Origins { + async fn approved(&self, identity: &PluginIdentity, _: u64) -> Option { + self.asked_for.lock().unwrap().push(identity.clone()); + Some(ApprovedOrigins { + revision: 0, + origins: self + .approved + .lock() + .unwrap() + .iter() + .filter_map(|origin| canonical_origin(origin)) + .collect(), + }) + } +} + +impl Origins { + fn set(&self, origins: &[&str]) { + *self.approved.lock().unwrap() = origins.iter().map(|o| (*o).to_owned()).collect(); + } +} + +impl Fixture { + pub(super) fn user_approving_origins(&self, origins: &[&str]) -> Arc { + let scopes = Arc::new(Origins::default()); + scopes.set(origins); + self.network.set_scopes(scopes.clone()); + scopes + } + + pub(super) async fn fetch_with( + &self, + url: &str, + method: &str, + headers: &[(&str, &str)], + body: &[u8], + max_response_bytes: u64, + timeout_ms: u32, + ) -> Result { + self.client() + .network_fetch(NetworkFetchRequest { + context: Some(self.context()), + url: url.into(), + method: method.into(), + headers: headers + .iter() + .map(|(n, v)| ((*n).to_owned(), (*v).to_owned())) + .collect(), + body: body.to_vec(), + max_response_bytes, + timeout_ms, + }) + .await + .map(Response::into_inner) + } + + pub(super) async fn fetch_url_text(&self, url: &str) -> Result { + self.fetch_with(url, "", &[], b"", 0, 0).await + } +} + +fn denial(status: &Status) -> DenialDetail { + DenialDetail::decode(status.details()).unwrap() +} + +const API_ORIGIN: &str = "https://api.example.com"; +const CDN_ORIGIN: &str = "https://cdn.example.com:8443"; + +fn persist_origins(fixture: &Fixture, plugin: &str, publisher: &str, approved: &[&str]) { + let profile = fixture.api.profiles().current().unwrap(); + let identity = PluginIdentity { + plugin_id: plugin.into(), + publisher_fingerprint: publisher.into(), + profile_id: profile.profile_id().into(), + }; + let requests = + manifest_permission_requests(&[crate::plugin_host::package::PermissionRequest { + id: cap::NETWORK_FETCH.into(), + required: false, + scope: format!("{API_ORIGIN}, {CDN_ORIGIN}"), + reason: "Fetch fixtures".into(), + impact_if_disabled: None, + }]) + .unwrap(); + let decisions: Vec<_> = approved + .iter() + .map(|origin| PermissionDecision { + permission_id: cap::NETWORK_FETCH.into(), + scope: crate::plugin_host::grants::GrantScope::Declared { + value: (*origin).into(), + }, + granted: true, + }) + .collect(); + PluginStateLayout::new(&fixture.plugin_data) + .open_grants(&profile) + .unwrap() + .replace_grants(identity, &requests, &decisions) + .unwrap(); +} + +#[tokio::test] +async fn persisted_network_origins_require_separate_approval_for_the_authenticated_identity() { + let fixture = Fixture::new(NETWORK).await; + let publisher = "ab".repeat(32); + for (plugin, key) in [ + ("other.plugin", publisher.clone()), + ("fixture.plugin", "ef".repeat(32)), + ] { + persist_origins(&fixture, plugin, &key, &[API_ORIGIN]); + } + assert_eq!( + fixture.fetch_url_text(API_ORIGIN).await.unwrap_err().code(), + Code::PermissionDenied + ); + assert!(fixture.fetcher.calls().is_empty()); + + persist_origins(&fixture, "fixture.plugin", &publisher, &[API_ORIGIN]); + fixture.fetch_url_text(API_ORIGIN).await.unwrap(); + assert_eq!( + fixture.fetch_url_text(CDN_ORIGIN).await.unwrap_err().code(), + Code::PermissionDenied + ); + persist_origins( + &fixture, + "fixture.plugin", + &publisher, + &[API_ORIGIN, CDN_ORIGIN], + ); + fixture.fetch_url_text(CDN_ORIGIN).await.unwrap(); + assert_eq!( + fixture + .fetch_url_text("https://cdn.example.com") + .await + .unwrap_err() + .code(), + Code::PermissionDenied + ); + + let restarted = Fixture::restarted(NETWORK, fixture.plugin_data.clone()).await; + restarted.fetch_url_text(CDN_ORIGIN).await.unwrap(); + restarted.api.profiles().update(Some("new-account"), true); + assert_eq!( + restarted + .fetch_url_text(CDN_ORIGIN) + .await + .unwrap_err() + .code(), + Code::FailedPrecondition + ); +} + +#[tokio::test] +async fn persisted_network_revocation_and_profile_switch_cancel_an_in_flight_request() { + for change_profile in [false, true] { + let fixture = Fixture::new(NETWORK).await; + let publisher = "ab".repeat(32); + persist_origins(&fixture, "fixture.plugin", &publisher, &[API_ORIGIN]); + let started = Arc::new(tokio::sync::Notify::new()); + let in_flight = started.clone(); + fixture.fetcher.script(move |_, allow| { + let in_flight = in_flight.clone(); + async move { + assert!(allow(API_ORIGIN.into()).await); + in_flight.notify_one(); + std::future::pending().await + } + }); + let mut client = fixture.client(); + let context = fixture.context(); + let request = tokio::spawn(async move { + client + .network_fetch(NetworkFetchRequest { + context: Some(context), + url: API_ORIGIN.into(), + ..Default::default() + }) + .await + }); + tokio::time::timeout(Duration::from_secs(5), started.notified()) + .await + .unwrap(); + let expected = if change_profile { + fixture.api.profiles().update(Some("new-account"), true); + Code::FailedPrecondition + } else { + persist_origins(&fixture, "fixture.plugin", &publisher, &[]); + fixture.api.profiles().notify_permissions_changed(); + Code::PermissionDenied + }; + let status = tokio::time::timeout(Duration::from_secs(5), request) + .await + .unwrap() + .unwrap() + .unwrap_err(); + assert_eq!(status.code(), expected); + assert_eq!( + fixture.fetch_url_text(API_ORIGIN).await.unwrap_err().code(), + expected + ); + } +} + +#[tokio::test] +async fn persisted_network_revision_blocks_a_response_after_reapproval() { + let fixture = Fixture::new(NETWORK).await; + let publisher = "ab".repeat(32); + persist_origins(&fixture, "fixture.plugin", &publisher, &[API_ORIGIN]); + let started = Arc::new(tokio::sync::Notify::new()); + let finished = Arc::new(tokio::sync::Notify::new()); + fixture.fetcher.script({ + let (started, finished) = (started.clone(), finished.clone()); + move |_, allow| { + let (started, finished) = (started.clone(), finished.clone()); + async move { + assert!(allow(API_ORIGIN.into()).await); + started.notify_one(); + finished.notified().await; + Ok(Fetched { + status: 200, + headers: vec![], + body: b"stale".to_vec(), + final_origin: API_ORIGIN.into(), + }) + } + } + }); + let fetch = fixture.fetch_url_text(API_ORIGIN); + let change_grants = async { + started.notified().await; + persist_origins(&fixture, "fixture.plugin", &publisher, &[]); + persist_origins(&fixture, "fixture.plugin", &publisher, &[API_ORIGIN]); + finished.notify_one(); + }; + let (result, ()) = tokio::time::timeout(Duration::from_secs(5), async { + tokio::join!(fetch, change_grants) + }) + .await + .unwrap(); + assert_eq!(result.unwrap_err().code(), Code::PermissionDenied); +} + +#[tokio::test] +async fn an_approved_origin_is_fetched_and_the_answer_comes_back() { + let fixture = Fixture::new(NETWORK).await; + let scopes = fixture.user_approving_origins(&["https://api.example.com"]); + + let reply = fixture + .fetch_with( + "https://api.example.com/v1/items?limit=3#frag", + "POST", + &[("Content-Type", "application/json"), ("X-Token", "t")], + b"{\"a\":1}", + 2048, + 1500, + ) + .await + .unwrap(); + assert_eq!(reply.status_code, 200); + assert_eq!(reply.body, b"fetched"); + assert_eq!(reply.final_origin, "https://api.example.com"); + assert_eq!(reply.headers["content-type"], "text/plain"); + + // Exactly what the plugin asked for reached the fetch: nothing of GameNode's added. + let [seen] = fixture.fetcher.calls().try_into().unwrap(); + assert_eq!(seen.url, "https://api.example.com/v1/items?limit=3"); + assert_eq!(seen.method, "POST"); + let mut headers = seen.headers.clone(); + headers.sort(); + assert_eq!( + headers, + [ + ("content-type".to_owned(), "application/json".to_owned()), + ("x-token".to_owned(), "t".to_owned()) + ] + ); + assert_eq!(seen.body, b"{\"a\":1}"); + assert_eq!( + (seen.max_response_bytes, seen.timeout), + (2048, Duration::from_millis(1500)) + ); + // The origins were asked for the plugin's authenticated identity, not a name it sent. + let asked = scopes.asked_for.lock().unwrap(); + assert!( + asked + .iter() + .all(|identity| identity.plugin_id == "fixture.plugin" + && identity.publisher_fingerprint == "ab".repeat(32)) + ); + assert!(!asked.is_empty()); +} + +#[tokio::test] +async fn the_defaults_are_a_get_with_the_default_budget_and_the_longest_deadline() { + let fixture = Fixture::new(NETWORK).await; + fixture.user_approving_origins(&["https://api.example.com"]); + fixture + .fetch_url_text("https://api.example.com/") + .await + .unwrap(); + fixture + .fetch_with("https://api.example.com/", "", &[], b"", u64::MAX, u32::MAX) + .await + .unwrap(); + let calls = fixture.fetcher.calls(); + assert_eq!(calls[0].method, "GET"); + assert_eq!(calls[0].max_response_bytes, 1024 * 1024); + assert_eq!(calls[0].timeout, Duration::from_secs(30)); + assert_eq!( + calls[1].max_response_bytes, + 8 * 1024 * 1024, + "capped at 8 MiB" + ); + assert_eq!(calls[1].timeout, Duration::from_secs(30), "capped at 30 s"); +} + +#[tokio::test] +async fn nothing_is_reachable_without_the_grant_and_an_approved_origin() { + // No grant at all. + let none = Fixture::new(&[]).await; + none.user_approving_origins(&["https://api.example.com"]); + let status = none + .fetch_url_text("https://api.example.com/") + .await + .unwrap_err(); + assert_eq!(status.code(), Code::PermissionDenied); + assert_eq!(denial(&status).permission_id, cap::NETWORK_FETCH); + + // The grant, but no origin approved (nothing is connected, as in a fresh install). + let fixture = Fixture::new(NETWORK).await; + let status = fixture + .fetch_url_text("https://api.example.com/") + .await + .unwrap_err(); + assert_eq!(status.code(), Code::PermissionDenied); + assert_eq!(denial(&status).permission_id, cap::NETWORK_FETCH); + assert_eq!(denial(&status).reason, DenialReason::ScopeDenied as i32); + // The refusal is audited like any other. + assert!(fixture.api.authorization_audit().iter().any(|event| { + event.permission_id == cap::NETWORK_FETCH && event.reason == DenialReason::ScopeDenied + })); + assert!(fixture.fetcher.calls().is_empty(), "nothing was fetched"); +} + +#[tokio::test] +async fn an_origin_is_exact_scheme_host_and_port() { + let fixture = Fixture::new(NETWORK).await; + fixture.user_approving_origins(&[ + "https://api.example.com", + // Entries that are not exact origins approve nothing. + "https://other.example.com/v1", + "http://insecure.example.com", + "*.example.org", + "https://*.example.net", + "", + ]); + for url in [ + "https://example.com/", + "https://www.api.example.com/", + "https://api.example.com.evil.test/", + "https://evilapi.example.com/", + "https://api.example.com:8443/", + "https://other.example.com/v1", + "https://insecure.example.com/", + "https://sub.example.org/", + "https://sub.example.net/", + "https://api.example.com@evil.test/", + ] { + let status = fixture.fetch_url_text(url).await.unwrap_err(); + assert!( + matches!( + status.code(), + Code::PermissionDenied | Code::InvalidArgument + ), + "{url}: {status:?}" + ); + } + assert!(fixture.fetcher.calls().is_empty()); + // The approved one, in any spelling of the same origin, is fine. + for url in [ + "https://api.example.com", + "https://API.example.com/x", + "https://api.example.com:443/x", + ] { + fixture.fetch_url_text(url).await.unwrap(); + } +} + +#[tokio::test] +async fn widening_or_revoking_an_origin_takes_effect_on_the_next_call_and_at_every_redirect() { + let fixture = Fixture::new(NETWORK).await; + let scopes = fixture.user_approving_origins(&["https://api.example.com"]); + fixture + .fetch_url_text("https://api.example.com/") + .await + .unwrap(); + assert_eq!( + fixture + .fetch_url_text("https://cdn.example.com/") + .await + .unwrap_err() + .code(), + Code::PermissionDenied + ); + scopes.set(&["https://api.example.com", "https://cdn.example.com"]); + fixture + .fetch_url_text("https://cdn.example.com/") + .await + .unwrap(); + scopes.set(&[]); + assert_eq!( + fixture + .fetch_url_text("https://api.example.com/") + .await + .unwrap_err() + .code(), + Code::PermissionDenied + ); + + // A redirect to an origin that is not approved is refused where the fetch asks. + scopes.set(&["https://api.example.com"]); + let hops = Arc::new(StdMutex::new(Vec::new())); + let recorded = hops.clone(); + fixture.fetcher.script(move |_, allow| { + let recorded = recorded.clone(); + async move { + for origin in ["https://api.example.com", "https://evil.example.com"] { + let allowed = allow(origin.into()).await; + recorded.lock().unwrap().push((origin, allowed)); + if !allowed { + return Err(FetchError::Denied); + } + } + unreachable!("the unapproved origin must stop the fetch") + } + }); + let status = fixture + .fetch_url_text("https://api.example.com/") + .await + .unwrap_err(); + assert_eq!(status.code(), Code::PermissionDenied); + assert_eq!(denial(&status).reason, DenialReason::ScopeDenied as i32); + assert_eq!( + *hops.lock().unwrap(), + [ + ("https://api.example.com", true), + ("https://evil.example.com", false) + ] + ); + // The refusal says nothing about where the redirect pointed. + assert!(!format!("{status:?}").contains("evil.example.com")); +} + +#[tokio::test] +async fn a_grant_revoked_while_a_fetch_runs_stops_its_next_hop() { + let fixture = Fixture::new(NETWORK).await; + fixture.user_approving_origins(&["https://api.example.com"]); + let api = fixture.api.clone(); + fixture.fetcher.script(move |_, allow| { + let api = api.clone(); + async move { + assert!(allow("https://api.example.com".into()).await); + api.revoke_session_permission("fixture", cap::NETWORK_FETCH) + .await; + if allow("https://api.example.com".into()).await { + return Ok(Fetched { + status: 200, + headers: vec![], + body: b"leaked".to_vec(), + final_origin: "https://api.example.com".into(), + }); + } + Err(FetchError::Denied) + } + }); + let status = fixture + .fetch_url_text("https://api.example.com/") + .await + .unwrap_err(); + assert_eq!(status.code(), Code::PermissionDenied); +} + +#[tokio::test] +async fn requests_are_validated_before_anything_is_fetched() { + let fixture = Fixture::new(NETWORK).await; + fixture.user_approving_origins(&["https://api.example.com"]); + let long_url = format!("https://api.example.com/{}", "a".repeat(2100)); + let big_body = vec![0u8; 1024 * 1024 + 1]; + let long_value = "v".repeat(5000); + type Case<'a> = (String, &'a str, Vec<(&'a str, &'a str)>, Vec); + let cases: Vec = vec![ + ("not a url".into(), "GET", vec![], vec![]), + ("http://api.example.com/".into(), "GET", vec![], vec![]), + ( + "https://user:pw@api.example.com/".into(), + "GET", + vec![], + vec![], + ), + (long_url, "GET", vec![], vec![]), + ("https://api.example.com/".into(), "CONNECT", vec![], vec![]), + ("https://api.example.com/".into(), "get", vec![], vec![]), + ( + "https://api.example.com/".into(), + "GET", + vec![("Host", "evil.test")], + vec![], + ), + ( + "https://api.example.com/".into(), + "GET", + vec![("Content-Length", "1")], + vec![], + ), + ( + "https://api.example.com/".into(), + "GET", + vec![("X-A", "line\r\nInjected: 1")], + vec![], + ), + ( + "https://api.example.com/".into(), + "GET", + vec![("X-A", &long_value)], + vec![], + ), + ( + "https://api.example.com/".into(), + "GET", + vec![("bad name", "x")], + vec![], + ), + ( + "https://api.example.com/".into(), + "GET", + vec![("X-A", "1"), ("x-a", "2")], + vec![], + ), + ("https://api.example.com/".into(), "POST", vec![], big_body), + ( + "https://api.example.com/".into(), + "GET", + vec![], + b"body".to_vec(), + ), + ]; + for (url, method, headers, body) in cases { + let shown = format!("{method} {:.60}", url); + let status = fixture + .fetch_with(&url, method, &headers, &body, 0, 0) + .await + .unwrap_err(); + assert_eq!(status.code(), Code::InvalidArgument, "{shown}: {status:?}"); + } + assert!(fixture.fetcher.calls().is_empty()); +} + +#[tokio::test] +async fn failures_map_to_distinct_codes_and_never_say_where_the_destination_is() { + let fixture = Fixture::new(NETWORK).await; + fixture.user_approving_origins(&["https://api.example.com"]); + for (error, code) in [ + (FetchError::TooLarge, Code::ResourceExhausted), + (FetchError::Timeout, Code::DeadlineExceeded), + (FetchError::TooManyRedirects, Code::FailedPrecondition), + (FetchError::Unreachable, Code::Unavailable), + (FetchError::BadResponse, Code::Unavailable), + (FetchError::Denied, Code::PermissionDenied), + ] { + fixture + .fetcher + .script(move |_, _| std::future::ready(Err(error))); + let status = fixture + .fetch_url_text("https://api.example.com/") + .await + .unwrap_err(); + assert_eq!(status.code(), code, "{error:?}"); + let shown = format!("{status:?}"); + assert!( + !shown.contains("api.example.com") && !shown.contains("127.0."), + "{shown}" + ); + } +} + +#[tokio::test] +async fn a_plugin_may_have_only_a_few_fetches_running() { + let fixture = Fixture::new(NETWORK).await; + fixture.user_approving_origins(&["https://api.example.com"]); + let gate = Arc::new(tokio::sync::Semaphore::new(0)); + *fixture.fetcher.gate.lock().unwrap() = Some(gate.clone()); + + let running: Vec<_> = (0..crate::plugin_host::network::PER_PLUGIN_FETCHES) + .map(|index| { + let mut client = fixture.client(); + let request = NetworkFetchRequest { + context: Some(fixture.context()), + url: format!("https://api.example.com/{index}"), + ..Default::default() + }; + tokio::spawn(async move { client.network_fetch(request).await }) + }) + .collect(); + let deadline = tokio::time::Instant::now() + Duration::from_secs(5); + while fixture.fetcher.started.load(Ordering::SeqCst) < running.len() { + assert!( + tokio::time::Instant::now() < deadline, + "the fetches never started" + ); + tokio::time::sleep(Duration::from_millis(10)).await; + } + // One more is told to retry; it never reaches the fetch. + let status = fixture + .fetch_url_text("https://api.example.com/extra") + .await + .unwrap_err(); + assert_eq!(status.code(), Code::ResourceExhausted); + assert_eq!(fixture.fetcher.calls().len(), running.len()); + + gate.add_permits(100); + for task in running { + task.await.unwrap().unwrap(); + } + // The slots are free again. + fixture + .fetch_url_text("https://api.example.com/after") + .await + .unwrap(); +} + +#[tokio::test] +async fn the_real_client_refuses_local_and_private_destinations_before_connecting() { + let fixture = Fixture::new(NETWORK).await; + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + let accepted = Arc::new(AtomicUsize::new(0)); + let counter = accepted.clone(); + tokio::spawn(async move { + while listener.accept().await.is_ok() { + counter.fetch_add(1, Ordering::SeqCst); + } + }); + + let urls = [ + format!("https://127.0.0.1:{port}/"), + format!("https://localhost:{port}/"), + format!("https://[::1]:{port}/"), + format!("https://0x7f.1:{port}/"), + format!("https://2130706433:{port}/"), + "https://10.0.0.5/".to_owned(), + "https://192.168.1.1/".to_owned(), + "https://172.16.0.1/".to_owned(), + "https://169.254.169.254/latest/meta-data/".to_owned(), + "https://100.64.0.1/".to_owned(), + "https://[fd00::1]/".to_owned(), + "https://[::ffff:127.0.0.1]/".to_owned(), + "https://0.0.0.0/".to_owned(), + ]; + // The user approved every one of them: an approved origin is still not enough. + let origins: Vec = urls + .iter() + .map(|url| url::Url::parse(url).unwrap().origin().ascii_serialization()) + .collect(); + let service = ResourceApi::new( + fixture.api.clone(), + fixture.feed.clone(), + fixture.storage.clone(), + fixture.files.clone(), + Arc::new(NetworkAccess::default()), + fixture.notifications.clone(), + fixture.jobs.clone(), + fixture.intents.clone(), + Arc::default(), + Arc::default(), + Arc::default(), + None, + ); + let scopes = Arc::new(Origins::default()); + *scopes.approved.lock().unwrap() = origins; + service.network.set_scopes(scopes); + for url in &urls { + let status = service + .network_fetch(Request::new(NetworkFetchRequest { + context: Some(fixture.context()), + url: url.clone(), + timeout_ms: 5000, + ..Default::default() + })) + .await + .unwrap_err(); + assert_eq!(status.code(), Code::PermissionDenied, "{url}: {status:?}"); + let shown = format!("{status:?}"); + assert!( + !shown.contains("127.0.0.1") && !shown.contains("169.254"), + "{shown}" + ); + } + tokio::time::sleep(Duration::from_millis(100)).await; + assert_eq!( + accepted.load(Ordering::SeqCst), + 0, + "no connection reached a local server" + ); +} + +#[tokio::test] +async fn the_network_service_is_described_and_needs_its_own_grant() { + let fixture = Fixture::new(NETWORK).await; + let described = fixture.host.describe_api().await.unwrap(); + let method = described + .methods + .iter() + .find(|method| method.method == "NetworkFetch") + .expect("NetworkFetch is served"); + assert!( + method + .permissions + .iter() + .any(|permission| permission == cap::NETWORK_FETCH) + ); + // Another grant does not stand in for it. + let other = Fixture::new(&[cap::FILES_READ, cap::STORAGE_READ]).await; + other.user_approving_origins(&["https://api.example.com"]); + assert_eq!( + other + .fetch_url_text("https://api.example.com/") + .await + .unwrap_err() + .code(), + Code::PermissionDenied + ); +} diff --git a/crates/app/src/plugin_host/resources/tests/notifications.rs b/crates/app/src/plugin_host/resources/tests/notifications.rs new file mode 100644 index 000000000..1b9335634 --- /dev/null +++ b/crates/app/src/plugin_host/resources/tests/notifications.rs @@ -0,0 +1,432 @@ +//! `NotificationsPublish` over the real local socket (task 6.4). + +use std::sync::Mutex as StdMutex; +use std::sync::atomic::Ordering; + +use gamenode_plugin_protocol::prost::Message; + +use super::*; +use crate::plugin_host::notifications::{ + GLOBAL_PER_WINDOW, NotificationSink, PER_PLUGIN_PER_WINDOW, PluginNotice, Severity, WINDOW, +}; + +const NOTICES: &[&str] = &[cap::NOTIFICATIONS_PUBLISH]; + +/// What the application would be told to show. +#[derive(Default)] +pub(super) struct Collected(StdMutex>); + +impl NotificationSink for Collected { + fn deliver(&self, notice: PluginNotice) { + self.0.lock().unwrap().push(notice); + } +} + +impl Collected { + pub(super) fn all(&self) -> Vec { + self.0.lock().unwrap().clone() + } +} + +impl Fixture { + async fn notify( + &self, + idempotency: &str, + title: &str, + body: &str, + severity: &str, + ) -> Result { + self.notify_full(idempotency, title, body, "", severity, vec![]) + .await + } + + pub(super) async fn notify_full( + &self, + idempotency: &str, + title: &str, + body: &str, + locale: &str, + severity: &str, + translations: Vec<(&str, &str, &str)>, + ) -> Result { + self.client() + .notifications_publish(NotificationPublishRequest { + mutation: Some(self.mutation(idempotency, 0)), + title: title.into(), + body: body.into(), + locale: locale.into(), + severity: severity.into(), + translations: translations + .into_iter() + .map(|(locale, title, body)| NotificationTranslation { + locale: locale.into(), + title: title.into(), + body: body.into(), + }) + .collect(), + }) + .await + .map(Response::into_inner) + } + + pub(super) fn advance_notice_clock(&self, millis: u64) { + self.notice_clock.fetch_add(millis, Ordering::SeqCst); + } +} + +#[tokio::test] +async fn a_notification_is_delivered_attributed_to_the_authenticated_plugin() { + let fixture = Fixture::new(NOTICES).await; + let reply = fixture + .notify_full( + "n1", + " Backup finished ", + "3 files saved.\nNo errors.", + "en", + "success", + vec![ + ("pt-BR", "Backup concluído", "3 arquivos salvos."), + ("de", "Sicherung fertig", ""), + ], + ) + .await + .unwrap(); + assert_eq!(reply.outcome, MutationOutcome::Applied as i32); + + let [notice] = fixture.notices.all().try_into().unwrap(); + // The attribution is the authenticated plugin id; the request has no field for it. + assert_eq!(notice.plugin_id, "fixture.plugin"); + assert_eq!(notice.severity, Severity::Success); + let texts: Vec<_> = notice + .texts + .iter() + .map(|text| { + ( + text.locale.as_str(), + text.title.as_str(), + text.body.as_str(), + ) + }) + .collect(); + assert_eq!( + texts, + [ + ("en", "Backup finished", "3 files saved.\nNo errors."), + ("pt-BR", "Backup concluído", "3 arquivos salvos."), + ("de", "Sicherung fertig", ""), + ] + ); +} + +#[tokio::test] +async fn severity_defaults_to_info_and_unknown_words_are_refused() { + let fixture = Fixture::new(NOTICES).await; + fixture.notify("a", "hello", "", "").await.unwrap(); + for (index, word) in ["info", "success", "warning", "error"] + .into_iter() + .enumerate() + { + fixture + .notify(&format!("s{index}"), "hello", &index.to_string(), word) + .await + .unwrap(); + } + let severities: Vec<_> = fixture.notices.all().iter().map(|n| n.severity).collect(); + assert_eq!( + severities, + [ + Severity::Info, + Severity::Info, + Severity::Success, + Severity::Warning, + Severity::Error + ] + ); + for bad in ["INFO", "critical", "danger", "warn"] { + let status = fixture.notify("bad", "hello", "x", bad).await.unwrap_err(); + assert_eq!(status.code(), Code::InvalidArgument, "{bad}"); + } +} + +#[tokio::test] +async fn the_grant_is_needed_and_a_revoked_one_stops_it_without_using_the_allowance() { + let none = Fixture::new(&[]).await; + let status = none.notify("k", "hello", "", "").await.unwrap_err(); + assert_eq!(status.code(), Code::PermissionDenied); + assert_eq!( + DenialDetail::decode(status.details()) + .unwrap() + .permission_id, + cap::NOTIFICATIONS_PUBLISH + ); + assert!(none.notices.all().is_empty()); + + let fixture = Fixture::new(NOTICES).await; + fixture.notify("first", "hello", "", "").await.unwrap(); + fixture + .api + .revoke_session_permission("fixture", cap::NOTIFICATIONS_PUBLISH) + .await; + for index in 0..10 { + let status = fixture + .notify(&format!("late-{index}"), "hello", "", "") + .await + .unwrap_err(); + assert_eq!(status.code(), Code::PermissionDenied); + } + assert_eq!(fixture.notices.all().len(), 1); +} + +#[tokio::test] +async fn bad_text_is_refused_and_nothing_is_shown() { + let fixture = Fixture::new(NOTICES).await; + let long_title = "t".repeat(121); + let long_body = "b".repeat(513); + let many_lines = ["x"; 9].join("\n"); + let cases: Vec<(&str, &str, &str)> = vec![ + ("", "body", "en"), + (" ", "", "en"), + (&long_title, "", "en"), + ("two\nlines", "", "en"), + ("tab\there", "", "en"), + ("esc\u{1b}[31mred", "", "en"), + ("exe \u{202e}fdp.exe", "", "en"), + ("zero\u{200b}width", "", "en"), + ("ok", &long_body, "en"), + ("ok", &many_lines, "en"), + ("ok", "bell\u{7}", "en"), + ("ok", "rlo \u{202e}x", "en"), + ("ok", "", "en_US"), + ("ok", "", "../x"), + ]; + for (title, body, locale) in cases { + let status = fixture + .notify_full("k", title, body, locale, "", vec![]) + .await + .unwrap_err(); + assert_eq!( + status.code(), + Code::InvalidArgument, + "{title:?} {body:?} {locale:?}" + ); + } + assert!(fixture.notices.all().is_empty()); +} + +#[tokio::test] +async fn translations_are_bounded_checked_and_distinct() { + let fixture = Fixture::new(NOTICES).await; + let nine: Vec<(String, String, String)> = (0..9) + .map(|i| (format!("l{i}"), "t".into(), String::new())) + .collect(); + let nine: Vec<(&str, &str, &str)> = nine + .iter() + .map(|(l, t, b)| (l.as_str(), t.as_str(), b.as_str())) + .collect(); + let eight = nine[..8].to_vec(); + assert_eq!( + fixture + .notify_full("n", "t", "", "en", "", nine) + .await + .unwrap_err() + .code(), + Code::InvalidArgument + ); + fixture + .notify_full("ok", "t", "", "en", "", eight) + .await + .unwrap(); + + for translations in [ + vec![("", "t", "")], + vec![("fr", "", "")], + vec![("fr", "t", ""), ("FR", "t2", "")], + vec![("en", "t", "")], + vec![("EN", "t", "")], + vec![("fr", "line\nbreak", "")], + vec![("fr", "t", "x\u{202e}y")], + vec![("fr_FR", "t", "")], + ] { + let status = fixture + .notify_full("bad", "t", "", "en", "", translations.clone()) + .await + .unwrap_err(); + assert_eq!(status.code(), Code::InvalidArgument, "{translations:?}"); + } + assert_eq!( + fixture.notices.all().len(), + 1, + "only the valid one was shown" + ); +} + +#[tokio::test] +async fn markup_links_and_script_are_passed_on_untouched_as_text() { + let fixture = Fixture::new(NOTICES).await; + let title = " "; + let body = + "[click](javascript:alert(3)) pay https://evil.test/x"; + fixture.notify("k", title, body, "").await.unwrap(); + let [notice] = fixture.notices.all().try_into().unwrap(); + // The host never interprets the text; showing it as plain text is the application's side. + assert_eq!( + ( + notice.texts[0].title.as_str(), + notice.texts[0].body.as_str() + ), + (title, body) + ); +} + +#[tokio::test] +async fn a_plugin_that_notifies_too_often_is_told_when_to_retry_and_may_then() { + let fixture = Fixture::new(NOTICES).await; + for index in 0..PER_PLUGIN_PER_WINDOW { + fixture.advance_notice_clock(1000); + fixture + .notify(&format!("n{index}"), "hello", &index.to_string(), "") + .await + .unwrap(); + } + assert_eq!(fixture.notices.all().len(), PER_PLUGIN_PER_WINDOW); + + let status = fixture + .notify("over", "hello", "over", "") + .await + .unwrap_err(); + assert_eq!(status.code(), Code::ResourceExhausted); + let retry: u64 = status + .metadata() + .get("retry-after-ms") + .expect("the wait is in the metadata") + .to_str() + .unwrap() + .parse() + .unwrap(); + assert_eq!( + retry, + WINDOW.as_millis() as u64 - 4000, + "until the oldest leaves the window" + ); + assert!( + status.message().contains("retry after 56 seconds"), + "{}", + status.message() + ); + assert_eq!( + fixture.notices.all().len(), + PER_PLUGIN_PER_WINDOW, + "nothing more was shown" + ); + + // Waiting as told makes room; the refused call was not remembered, so its key is usable. + fixture.advance_notice_clock(retry); + fixture.notify("over", "hello", "over", "").await.unwrap(); + assert_eq!(fixture.notices.all().len(), PER_PLUGIN_PER_WINDOW + 1); +} + +#[tokio::test] +async fn a_retried_notification_is_shown_once_and_a_reused_key_is_refused() { + let fixture = Fixture::new(NOTICES).await; + let first = fixture + .notify("same", "hello", "body", "info") + .await + .unwrap(); + let retry = fixture + .notify("same", "hello", "body", "info") + .await + .unwrap(); + assert_eq!(first, retry); + assert_eq!(fixture.notices.all().len(), 1); + // Retries do not use the allowance either. + for _ in 0..20 { + fixture + .notify("same", "hello", "body", "info") + .await + .unwrap(); + } + fixture.notify("fresh", "another", "", "").await.unwrap(); + + let status = fixture + .notify("same", "different", "body", "info") + .await + .unwrap_err(); + assert_eq!(status.code(), Code::FailedPrecondition); + assert_eq!(fixture.notices.all().len(), 2); +} + +#[tokio::test] +async fn publishing_is_unavailable_without_a_sink_and_revisions_are_not_used() { + let fixture = Fixture::new(NOTICES).await; + let status = fixture + .client() + .notifications_publish(NotificationPublishRequest { + mutation: Some(fixture.mutation("k", 4)), + title: "hello".into(), + ..Default::default() + }) + .await + .unwrap_err(); + assert_eq!(status.code(), Code::InvalidArgument); + let status = fixture + .client() + .notifications_publish(NotificationPublishRequest { + mutation: Some(MutationContext { + idempotency_key: String::new(), + ..fixture.mutation("k", 0) + }), + title: "hello".into(), + ..Default::default() + }) + .await + .unwrap_err(); + assert_eq!( + status.code(), + Code::InvalidArgument, + "an idempotency key is required" + ); + + // A host with nothing connected cannot show anything. + let service = ResourceApi::new( + fixture.api.clone(), + fixture.feed.clone(), + fixture.storage.clone(), + fixture.files.clone(), + fixture.network.clone(), + Arc::new(Notifications::default()), + Jobs::default(), + Arc::default(), + Arc::default(), + Arc::default(), + Arc::default(), + None, + ); + let status = service + .notifications_publish(Request::new(NotificationPublishRequest { + mutation: Some(fixture.mutation("k", 0)), + title: "hello".into(), + ..Default::default() + })) + .await + .unwrap_err(); + assert_eq!(status.code(), Code::Unavailable); +} + +#[test] +fn the_limits_are_the_documented_ones() { + assert_eq!((PER_PLUGIN_PER_WINDOW, GLOBAL_PER_WINDOW), (5, 20)); + assert_eq!(WINDOW, Duration::from_secs(60)); +} + +#[tokio::test] +async fn the_service_is_described() { + let fixture = Fixture::new(NOTICES).await; + let described = fixture.host.describe_api().await.unwrap(); + assert!(described.methods.iter().any(|method| { + method.method == "NotificationsPublish" + && method + .permissions + .iter() + .any(|p| p == cap::NOTIFICATIONS_PUBLISH) + })); +} diff --git a/crates/app/src/plugin_host/resources/tests/observations.rs b/crates/app/src/plugin_host/resources/tests/observations.rs new file mode 100644 index 000000000..104da3e78 --- /dev/null +++ b/crates/app/src/plugin_host/resources/tests/observations.rs @@ -0,0 +1,691 @@ +//! Public Computer and GamePresence RPC flows over the local authenticated host services. + +use super::*; +use gamenode_plugin_protocol::prost_types::{Struct, Value, value::Kind}; +use std::collections::BTreeMap; +use tonic::Code; + +const HARDWARE_GRANTS: &[&str] = &[cap::COMPUTER_HARDWARE_PUBLISH, cap::COMPUTER_HARDWARE_READ]; +const PRESENCE_GRANTS: &[&str] = &[cap::GAME_PRESENCE_PUBLISH, cap::GAME_PRESENCE_READ]; + +fn value_string(text: &str) -> Value { + Value { + kind: Some(Kind::StringValue(text.into())), + } +} + +fn value_number(number: f64) -> Value { + Value { + kind: Some(Kind::NumberValue(number)), + } +} + +fn object(fields: impl IntoIterator) -> Value { + Value { + kind: Some(Kind::StructValue(Struct { + fields: fields.into_iter().collect(), + })), + } +} + +#[tokio::test] +async fn hardware_report_uses_host_context_preserves_unknown_states_and_rejects_unique_ids() { + let fixture = Fixture::new(HARDWARE_GRANTS).await; + let observed_at = crate::plugin_host::resources::unix_now().unwrap(); + let published = fixture + .client() + .computer_publish_hardware(HardwareReportRequest { + mutation: Some(fixture.mutation("hardware-1", 0)), + computer_id: String::new(), + schema_id: "org.example.hardware.v2".into(), + schema_version: 2, + observations: Some(Struct { + fields: BTreeMap::from([ + ( + "cpu".into(), + object([ + ("logical_cores".into(), value_number(8.0)), + ("temperature_state".into(), value_string("unknown")), + ]), + ), + ("os_version".into(), value_string("FixtureOS 1")), + ]), + }), + observed_at, + }) + .await + .unwrap() + .into_inner(); + assert!(!published.report_id.is_empty()); + + let mut computer = fixture.host.computer_client(); + let listed = computer + .list(ComputerListRequest { + page: Some(PageRequest { + context: Some(fixture.context()), + cursor: String::new(), + page_size: 10, + common_data_categories: None, + }), + computer_context_id: "active-host".into(), + projection_id: "hardware.v1".into(), + }) + .await + .unwrap() + .into_inner(); + assert_eq!(listed.reports.len(), 1); + let report = &listed.reports[0]; + assert_eq!(report.record_id, published.report_id); + assert_eq!(report.computer_context_id, "active-host"); + assert_eq!(report.owner_plugin_id, "fixture.plugin"); + assert_eq!(report.schema_id, "org.example.hardware.v2"); + assert_eq!(report.schema_version, 2); + let fields = &report.typed_observations.as_ref().unwrap().fields; + let cpu = fields["cpu"].kind.as_ref().unwrap(); + let Kind::StructValue(cpu) = cpu else { + panic!("CPU observations should preserve their typed structure"); + }; + assert_eq!( + cpu.fields["logical_cores"].kind, + Some(Kind::NumberValue(8.0)) + ); + assert_eq!( + cpu.fields["temperature_state"].kind, + Some(Kind::StringValue("unknown".into())) + ); + assert!(!fields.contains_key("serial_number")); + + let fetched = computer + .get(ComputerGetRequest { + context: Some(fixture.context()), + computer_record_id: published.report_id, + projection_id: "hardware.v1".into(), + }) + .await + .unwrap() + .into_inner(); + assert_eq!(fetched.report.unwrap().schema_version, 2); + + let mut watch = computer + .watch(ComputerWatchRequest { + context: Some(fixture.context()), + computer_context_id: "active-host".into(), + projection_id: "hardware.v1".into(), + after_revision: listed.revision, + }) + .await + .unwrap() + .into_inner(); + fixture + .client() + .computer_publish_hardware(HardwareReportRequest { + mutation: Some(fixture.mutation("hardware-2", 0)), + schema_id: "org.example.hardware.v2".into(), + schema_version: 2, + observations: Some(Struct { + fields: BTreeMap::from([("gpu_state".into(), value_string("unknown"))]), + }), + observed_at, + ..Default::default() + }) + .await + .unwrap(); + let event = tokio::time::timeout(std::time::Duration::from_secs(2), watch.message()) + .await + .unwrap() + .unwrap() + .unwrap(); + assert_eq!(event.event_type, "published"); + assert!(event.revision > listed.revision); + + let denied = fixture + .client() + .computer_publish_hardware(HardwareReportRequest { + mutation: Some(fixture.mutation("hardware-private-id", 0)), + schema_id: "org.example.hardware.v2".into(), + schema_version: 2, + observations: Some(Struct { + fields: BTreeMap::from([("serial_number".into(), value_string("secret"))]), + }), + observed_at, + ..Default::default() + }) + .await + .unwrap_err(); + assert_eq!(denied.code(), Code::InvalidArgument); +} + +#[tokio::test] +async fn hardware_context_id_is_host_assigned_and_permissions_are_separate() { + let fixture = Fixture::new(&[cap::COMPUTER_HARDWARE_PUBLISH]).await; + let denied = fixture + .client() + .computer_publish_hardware(HardwareReportRequest { + mutation: Some(fixture.mutation("hardware-id", 0)), + computer_id: "machine-serial-123".into(), + schema_id: "org.example.hardware.v1".into(), + schema_version: 1, + observations: Some(Struct { + fields: BTreeMap::from([("cpu_name".into(), value_string("Fixture CPU"))]), + }), + observed_at: crate::plugin_host::resources::unix_now().unwrap(), + }) + .await + .unwrap_err(); + assert_eq!(denied.code(), Code::InvalidArgument); + + let mut computer = fixture.host.computer_client(); + let denied = computer + .list(ComputerListRequest { + page: Some(PageRequest { + context: Some(fixture.context()), + cursor: String::new(), + page_size: 10, + common_data_categories: None, + }), + computer_context_id: String::new(), + projection_id: "hardware.v1".into(), + }) + .await + .unwrap_err(); + assert_eq!(denied.code(), Code::PermissionDenied); +} + +#[tokio::test] +async fn presence_replaces_stale_state_and_clear_reaches_authorized_watchers() { + let fixture = Fixture::new(PRESENCE_GRANTS).await; + let mut presence = fixture.host.game_presence_client(); + let list_request = || PresenceListRequest { + page: Some(PageRequest { + context: Some(fixture.context()), + cursor: String::new(), + page_size: 10, + common_data_categories: None, + }), + game_id: "42".into(), + session_id: "session-a".into(), + projection_id: "presence.v1".into(), + }; + // Merely opening a session or selecting a game must not publish online state. + assert!( + presence + .list(list_request()) + .await + .unwrap() + .into_inner() + .records + .is_empty() + ); + let publish = |key: &str, mode: &str| PresencePublishRequest { + mutation: Some(fixture.mutation(key, 0)), + game_id: "42".into(), + session_id: "session-a".into(), + details: Some(Struct { + fields: BTreeMap::from([("mode".into(), value_string(mode))]), + }), + ttl_seconds: 60, + }; + let first = fixture + .client() + .game_presence_publish(publish("presence-1", "ranked")) + .await + .unwrap() + .into_inner(); + let listed = presence.list(list_request()).await.unwrap().into_inner(); + assert_eq!(listed.records.len(), 1); + assert_eq!(listed.records[0].presence_id, first.report_id); + assert_eq!(listed.records[0].owner_plugin_id, "fixture.plugin"); + assert_eq!(listed.records[0].game_id, "42"); + assert_eq!(listed.records[0].session_id, "session-a"); + assert_eq!( + listed.records[0].approved_details.as_ref().unwrap().fields["mode"].kind, + Some(Kind::StringValue("ranked".into())) + ); + + let mut watch = presence + .watch(PresenceWatchRequest { + context: Some(fixture.context()), + game_id: "42".into(), + session_id: "session-a".into(), + projection_id: "presence.v1".into(), + after_sequence: listed.revision, + }) + .await + .unwrap() + .into_inner(); + let second = fixture + .client() + .game_presence_publish(publish("presence-2", "menu")) + .await + .unwrap() + .into_inner(); + assert_ne!(first.report_id, second.report_id); + let update = tokio::time::timeout(std::time::Duration::from_secs(2), watch.message()) + .await + .unwrap() + .unwrap() + .unwrap(); + assert_eq!(update.event_type, "published"); + assert_eq!(update.record.unwrap().presence_id, second.report_id); + + let listed = presence.list(list_request()).await.unwrap().into_inner(); + assert_eq!(listed.records.len(), 1); + assert_eq!(listed.records[0].presence_id, second.report_id); + assert_eq!( + listed.records[0].approved_details.as_ref().unwrap().fields["mode"].kind, + Some(Kind::StringValue("menu".into())) + ); + let mut watch = presence + .watch(PresenceWatchRequest { + context: Some(fixture.context()), + game_id: "42".into(), + session_id: "session-a".into(), + projection_id: "presence.v1".into(), + after_sequence: listed.revision, + }) + .await + .unwrap() + .into_inner(); + fixture + .client() + .game_presence_clear(PresenceClearRequest { + mutation: Some(fixture.mutation("presence-clear", 0)), + game_id: "42".into(), + session_id: "session-a".into(), + }) + .await + .unwrap(); + let event = tokio::time::timeout(std::time::Duration::from_secs(2), watch.message()) + .await + .unwrap() + .unwrap() + .unwrap(); + assert_eq!(event.event_type, "cleared"); + assert_eq!(event.record.unwrap().session_id, "session-a"); + + assert!( + presence + .list(list_request()) + .await + .unwrap() + .into_inner() + .records + .is_empty() + ); + let missing = presence + .get(PresenceGetRequest { + context: Some(fixture.context()), + presence_id: second.report_id, + projection_id: "presence.v1".into(), + }) + .await + .unwrap_err(); + assert_eq!(missing.code(), Code::NotFound); +} + +#[tokio::test] +async fn presence_expires_from_public_query_after_the_host_ttl() { + let fixture = Fixture::new(PRESENCE_GRANTS).await; + fixture + .client() + .game_presence_publish(PresencePublishRequest { + mutation: Some(fixture.mutation("presence-expiry", 0)), + game_id: "42".into(), + session_id: "session-expiring".into(), + details: Some(Struct { + fields: BTreeMap::from([("state".into(), value_string("playing"))]), + }), + ttl_seconds: 1, + }) + .await + .unwrap(); + + tokio::time::sleep(std::time::Duration::from_millis(1_100)).await; + let mut presence = fixture.host.game_presence_client(); + let listed = presence + .list(PresenceListRequest { + page: Some(PageRequest { + context: Some(fixture.context()), + cursor: String::new(), + page_size: 10, + common_data_categories: None, + }), + game_id: "42".into(), + session_id: "session-expiring".into(), + projection_id: "presence.v1".into(), + }) + .await + .unwrap() + .into_inner(); + assert!(listed.records.is_empty()); +} + +#[tokio::test] +async fn computer_reads_do_not_include_another_plugins_sensitive_observations_without_policy() { + use crate::plugin_host::{ + grants::PluginIdentity, shared_data::Publication, sharing_policy::SharingClass, + }; + + let fixture = Fixture::new(&[cap::COMPUTER_HARDWARE_READ]).await; + fixture + .data_broker + .publish( + Publication { + owner: PluginIdentity { + plugin_id: "source.plugin".into(), + publisher_fingerprint: "cd".repeat(32), + profile_id: "a".into(), + }, + dataset_id: "computer.hardware.observations.v1".into(), + category: None, + class: SharingClass::Sensitive, + schema_id: "org.example.hardware.v1".into(), + schema_version: 1, + fields: serde_json::Map::from_iter([( + "cpu_name".into(), + serde_json::json!("private source CPU"), + )]), + opaque_payload: Vec::new(), + resource_id: "active-host/1".into(), + observed_at: crate::plugin_host::resources::unix_now().unwrap(), + sequence: 0, + source_observation_id: String::new(), + session_id: Some("source-session".into()), + publisher: None, + expires_at: None, + }, + crate::plugin_host::resources::unix_now().unwrap(), + ) + .unwrap(); + + let mut computer = fixture.host.computer_client(); + let listed = computer + .list(ComputerListRequest { + page: Some(PageRequest { + context: Some(fixture.context()), + cursor: String::new(), + page_size: 10, + common_data_categories: None, + }), + computer_context_id: "active-host".into(), + projection_id: "hardware.v1".into(), + }) + .await + .unwrap() + .into_inner(); + assert!(listed.reports.is_empty()); +} + +#[tokio::test] +async fn presence_requires_separate_publish_and_read_permissions_and_bounds_ttl() { + let fixture = Fixture::new(&[cap::GAME_PRESENCE_PUBLISH]).await; + let invalid_ttl = fixture + .client() + .game_presence_publish(PresencePublishRequest { + mutation: Some(fixture.mutation("presence-ttl", 0)), + game_id: "42".into(), + session_id: "session-a".into(), + details: Some(Struct { + fields: BTreeMap::from([("state".into(), value_string("playing"))]), + }), + ttl_seconds: 301, + }) + .await + .unwrap_err(); + assert_eq!(invalid_ttl.code(), Code::InvalidArgument); + + let mut presence = fixture.host.game_presence_client(); + let denied = presence + .list(PresenceListRequest { + page: Some(PageRequest { + context: Some(fixture.context()), + cursor: String::new(), + page_size: 10, + common_data_categories: None, + }), + game_id: String::new(), + session_id: String::new(), + projection_id: "presence.v1".into(), + }) + .await + .unwrap_err(); + assert_eq!(denied.code(), Code::PermissionDenied); +} + +#[tokio::test] +async fn presence_reads_do_not_include_another_plugins_sensitive_records_without_policy() { + use crate::plugin_host::{ + grants::PluginIdentity, shared_data::Publication, sharing_policy::SharingClass, + }; + + let fixture = Fixture::new(PRESENCE_GRANTS).await; + let now = crate::plugin_host::resources::unix_now().unwrap(); + fixture + .data_broker + .publish( + Publication { + owner: PluginIdentity { + plugin_id: "source.plugin".into(), + publisher_fingerprint: "cd".repeat(32), + profile_id: "a".into(), + }, + dataset_id: "game.presence.v1".into(), + category: None, + class: SharingClass::Sensitive, + schema_id: "game.presence.v1".into(), + schema_version: 1, + fields: [("details.mode".into(), serde_json::json!("ranked"))] + .into_iter() + .collect(), + opaque_payload: Vec::new(), + resource_id: "42/session-a".into(), + observed_at: now, + sequence: 1, + source_observation_id: "source-presence-1".into(), + session_id: Some("source-session".into()), + publisher: None, + expires_at: Some(now + 60), + }, + now, + ) + .unwrap(); + + let mut presence = fixture.host.game_presence_client(); + let listed = presence + .list(PresenceListRequest { + page: Some(PageRequest { + context: Some(fixture.context()), + cursor: String::new(), + page_size: 10, + common_data_categories: None, + }), + game_id: "42".into(), + session_id: "session-a".into(), + projection_id: "presence.v1".into(), + }) + .await + .unwrap() + .into_inner(); + assert!(listed.records.is_empty()); +} + +#[tokio::test] +async fn presence_is_removed_when_the_publishing_session_closes() { + let fixture = Fixture::new(PRESENCE_GRANTS).await; + fixture + .client() + .game_presence_publish(PresencePublishRequest { + mutation: Some(fixture.mutation("presence-session-close", 0)), + game_id: "42".into(), + session_id: "session-a".into(), + details: Some(Struct { + fields: BTreeMap::from([("mode".into(), value_string("ranked"))]), + }), + ttl_seconds: 300, + }) + .await + .unwrap(); + + let context = fixture.context(); + let caller = fixture + .api + .authorize_resource_session(Some(&context)) + .unwrap(); + assert_eq!(fixture.data_broker.close_session(&caller.session_id), 1); + + let mut presence = fixture.host.game_presence_client(); + let listed = presence + .list(PresenceListRequest { + page: Some(PageRequest { + context: Some(context), + cursor: String::new(), + page_size: 10, + common_data_categories: None, + }), + game_id: "42".into(), + session_id: "session-a".into(), + projection_id: "presence.v1".into(), + }) + .await + .unwrap() + .into_inner(); + assert!(listed.records.is_empty()); +} + +#[tokio::test] +async fn computer_and_presence_reports_flow_between_plugins_with_separate_reviews() { + use crate::plugin_host::sharing_policy::{SharingClass, SourceRecipientPolicy}; + + let fixture = Fixture::new(&[cap::COMPUTER_HARDWARE_PUBLISH, cap::GAME_PRESENCE_PUBLISH]).await; + let consumer = super::data::consumer_session_with_grants( + &fixture, + &[cap::COMPUTER_HARDWARE_READ, cap::GAME_PRESENCE_READ], + ) + .await; + let consumer_context = consumer.host.resource_context().unwrap().clone(); + let source = super::data::authenticated_identity(&fixture, &fixture.context()); + let recipient = super::data::authenticated_identity(&fixture, &consumer_context); + for (dataset, field) in [ + ( + "computer.hardware.observations.v1", + "observations.cpu.logical_cores", + ), + ("game.presence.v1", "details.state"), + ] { + fixture + .shared_policies + .set_source_recipient_policy( + SourceRecipientPolicy::new( + source.clone(), + recipient.clone(), + SharingClass::Sensitive, + dataset.into(), + [field.into()], + true, + false, + ) + .unwrap(), + ) + .unwrap(); + } + + let observed_at = crate::plugin_host::resources::unix_now().unwrap(); + let hardware = fixture + .client() + .computer_publish_hardware(HardwareReportRequest { + mutation: Some(fixture.mutation("producer-hardware", 0)), + schema_id: "org.example.hardware.v1".into(), + schema_version: 1, + observations: Some(Struct { + fields: BTreeMap::from([( + "cpu".into(), + object([ + ("logical_cores".into(), value_number(8.0)), + ("model".into(), value_string("Fixture CPU")), + ]), + )]), + }), + observed_at, + ..Default::default() + }) + .await + .unwrap() + .into_inner(); + fixture + .client() + .game_presence_publish(PresencePublishRequest { + mutation: Some(fixture.mutation("producer-presence", 0)), + game_id: "42".into(), + session_id: "session-a".into(), + details: Some(Struct { + fields: BTreeMap::from([ + ("state".into(), value_string("playing")), + ("activity".into(), value_string("private activity")), + ]), + }), + ttl_seconds: 60, + }) + .await + .unwrap(); + + let mut computer = consumer.host.computer_client(); + let listed = computer + .list(ComputerListRequest { + page: Some(PageRequest { + context: Some(consumer_context.clone()), + page_size: 10, + ..Default::default() + }), + computer_context_id: "active-host".into(), + projection_id: "hardware.v1".into(), + }) + .await + .unwrap() + .into_inner(); + assert_eq!(listed.reports.len(), 1); + assert_eq!(listed.reports[0].record_id, hardware.report_id); + let fields = &listed.reports[0] + .typed_observations + .as_ref() + .unwrap() + .fields; + let cpu = fields["cpu"].kind.as_ref().unwrap(); + let Kind::StructValue(cpu) = cpu else { + panic!("projected CPU observations should remain structured"); + }; + assert!(cpu.fields.contains_key("logical_cores")); + assert!(!cpu.fields.contains_key("model")); + + let mut presence = consumer.host.game_presence_client(); + let listed = presence + .list(PresenceListRequest { + page: Some(PageRequest { + context: Some(consumer_context), + page_size: 10, + ..Default::default() + }), + game_id: "42".into(), + session_id: "session-a".into(), + projection_id: "presence.v1".into(), + }) + .await + .unwrap() + .into_inner(); + assert_eq!(listed.records.len(), 1); + assert!( + listed.records[0] + .approved_details + .as_ref() + .unwrap() + .fields + .contains_key("state") + ); + assert!( + !listed.records[0] + .approved_details + .as_ref() + .unwrap() + .fields + .contains_key("activity") + ); +} diff --git a/crates/app/src/plugin_host/resources/tests/performance.rs b/crates/app/src/plugin_host/resources/tests/performance.rs new file mode 100644 index 000000000..dfcbe1bb1 --- /dev/null +++ b/crates/app/src/plugin_host/resources/tests/performance.rs @@ -0,0 +1,701 @@ +//! End-to-end GamePerformance coverage over the authenticated local plugin services. + +use super::*; +use std::time::Duration; +use tonic::Code; + +const BATCH_SIZE: usize = 1000; + +const GRANTS: &[&str] = &[ + cap::GAME_LAUNCH, + cap::GAME_PERFORMANCE_PUBLISH, + cap::GAME_PERFORMANCE_READ, +]; + +pub(super) fn sample(sequence: u64, observed_at: i64, fps: f64) -> PerformanceSample { + PerformanceSample { + observed_at, + frames_per_second: fps, + cpu_percent: 42.0, + memory_bytes: 512 * 1024 * 1024, + sequence, + sampling_window_ms: 0, + fps_method: PerformanceFpsMethod::Instantaneous as i32, + fps_statistic: PerformanceFpsStatistic::Instantaneous as i32, + quality: PerformanceMeasurementQuality::Measured as i32, + ..Default::default() + } +} + +/// A valid performance batch for one authenticated session context. Shared with the combined +/// two-plugin flow so the measurement semantics stay identical across fixtures. +pub(super) fn request_for( + context: &ServiceContext, + key: &str, + expected_revision: u64, + samples: Vec, +) -> PerformanceSamplesRequest { + PerformanceSamplesRequest { + mutation: Some(MutationContext { + context: Some(context.clone()), + idempotency_key: key.into(), + expected_revision, + ..Default::default() + }), + series_id: "series-primary".into(), + game_id: "5".into(), + samples, + runtime_id: "runtime-main".into(), + runtime_recipe_revision: "rev-2".into(), + source: "overlay-frame-counter".into(), + tool_name: "Fixture collector".into(), + tool_version: "1.2".into(), + sample_interval_ms: 100, + cpu_scope: PerformanceCpuScope::Process as i32, + cpu_normalization: PerformanceCpuNormalization::WholeMachinePercent as i32, + memory_kind: PerformanceMemoryKind::WorkingSetBytes as i32, + memory_source: "linux-proc-status".into(), + fps_unit: "frames/second".into(), + cpu_unit: "percent".into(), + memory_unit: "bytes".into(), + ..Default::default() + } +} + +fn request( + fixture: &Fixture, + key: &str, + expected_revision: u64, + samples: Vec, +) -> PerformanceSamplesRequest { + request_for(&fixture.context(), key, expected_revision, samples) +} + +async fn fixture() -> Fixture { + Fixture::start_with_target( + GRANTS, + true, + None, + Some(TargetGameContext { + game_id: "5".into(), + installation_id: "steam:five".into(), + profile_id: String::new(), + revision: "library-rev-1".into(), + }), + ) + .await +} + +#[tokio::test] +async fn performance_batches_are_retained_queryable_and_aggregated_with_context() { + let fixture = fixture().await; + let now = crate::plugin_host::resources::unix_now().unwrap() * 1000; + let published = fixture + .client() + .game_performance_publish_samples(request( + &fixture, + "performance-batch-1", + 0, + vec![sample(1, now - 200, 59.0), sample(2, now - 100, 61.0)], + )) + .await + .unwrap() + .into_inner(); + assert_eq!(published.accepted_samples, 2); + assert!(published.report_id.starts_with("performance-")); + + let mut performance = fixture.host.game_performance_client(); + let listed = performance + .list(PerformanceListRequest { + page: Some(PageRequest { + context: Some(fixture.context()), + cursor: String::new(), + page_size: 20, + common_data_categories: None, + }), + game_id: "5".into(), + computer_context_id: "active-host".into(), + projection_id: "performance.v1".into(), + }) + .await + .unwrap() + .into_inner(); + assert_eq!(listed.series.len(), 1); + let series = &listed.series[0]; + assert_eq!(series.series_id, published.report_id); + assert_eq!(series.installation_id, "steam:five"); + assert_eq!(series.computer_context_id, "active-host"); + assert_eq!(series.runtime_id, "runtime-main"); + assert_eq!(series.source, "overlay-frame-counter"); + assert_eq!(series.fps_unit, "frames/second"); + assert_eq!(series.cpu_unit, "percent"); + assert_eq!(series.memory_unit, "bytes"); + assert_eq!(series.samples.len(), 2); + + let queried = performance + .query_series(PerformanceQuerySeriesRequest { + context: Some(fixture.context()), + series_id: series.series_id.clone(), + from_time: now - 300, + to_time: now, + resolution_ms: 300, + page: Some(PageRequest { + context: Some(fixture.context()), + cursor: String::new(), + page_size: 10, + common_data_categories: None, + }), + ..Default::default() + }) + .await + .unwrap() + .into_inner(); + assert_eq!(queried.samples.len(), 1); + assert_eq!(queried.coverage, "downsampled"); + assert_eq!(queried.dropped_samples, 0); + + let aggregate = performance + .aggregate(PerformanceAggregateRequest { + context: Some(fixture.context()), + series_id: series.series_id.clone(), + from_time: now - 300, + to_time: now, + metric: "fps".into(), + aggregation: "average".into(), + common_data_categories: None, + }) + .await + .unwrap() + .into_inner(); + assert_eq!(aggregate.value, 60.0); + assert_eq!(aggregate.unit, "frames/second"); + assert_eq!(aggregate.sample_count, 2); + assert_eq!(aggregate.coverage, "complete"); + let cpu = performance + .aggregate(PerformanceAggregateRequest { + context: Some(fixture.context()), + series_id: series.series_id.clone(), + from_time: now - 300, + to_time: now, + metric: "cpu_percent".into(), + aggregation: "average".into(), + common_data_categories: None, + }) + .await + .unwrap() + .into_inner(); + assert_eq!(cpu.value, 42.0); + assert_eq!(cpu.unit, "percent"); + let memory = performance + .aggregate(PerformanceAggregateRequest { + context: Some(fixture.context()), + series_id: series.series_id.clone(), + from_time: now - 300, + to_time: now, + metric: "memory_bytes".into(), + aggregation: "max".into(), + common_data_categories: None, + }) + .await + .unwrap() + .into_inner(); + assert_eq!(memory.value, (512 * 1024 * 1024) as f64); + assert_eq!(memory.unit, "bytes"); + let percentile = performance + .aggregate(PerformanceAggregateRequest { + context: Some(fixture.context()), + series_id: series.series_id.clone(), + from_time: now - 300, + to_time: now, + metric: "fps".into(), + aggregation: "p95".into(), + common_data_categories: None, + }) + .await + .unwrap() + .into_inner(); + assert_eq!(percentile.value, 61.0); + + let mut watch = performance + .watch(PerformanceWatchRequest { + context: Some(fixture.context()), + game_id: "5".into(), + computer_context_id: "active-host".into(), + projection_id: "performance.v1".into(), + after_sequence: listed.revision, + ..Default::default() + }) + .await + .unwrap() + .into_inner(); + + let ended = fixture + .client() + .game_performance_end_series(PerformanceEndSeriesRequest { + mutation: Some(fixture.mutation("performance-end", series.revision)), + series_id: "series-primary".into(), + ended_at: now, + expected_last_sequence: 2, + }) + .await + .unwrap() + .into_inner(); + assert_eq!(ended.outcome, MutationOutcome::Applied as i32); + let event = tokio::time::timeout(std::time::Duration::from_secs(2), watch.message()) + .await + .unwrap() + .unwrap() + .unwrap(); + assert_eq!(event.event_type, "ended"); + let after_end = fixture + .client() + .game_performance_publish_samples(request( + &fixture, + "performance-after-end", + ended.revision, + vec![sample(3, now + 100, 60.0)], + )) + .await + .unwrap_err(); + assert_eq!(after_end.code(), Code::FailedPrecondition); +} + +#[tokio::test] +async fn performance_rejects_out_of_order_and_reports_batch_backpressure() { + let fixture = fixture().await; + let now = crate::plugin_host::resources::unix_now().unwrap() * 1000; + let first = request( + &fixture, + "performance-first", + 0, + vec![sample(5, now - 100, 60.0)], + ); + let first_reply = fixture + .client() + .game_performance_publish_samples(first.clone()) + .await + .unwrap() + .into_inner(); + let mut repeated_request = first; + repeated_request.mutation.as_mut().unwrap().idempotency_key = "performance-first-retry".into(); + let repeated = fixture + .client() + .game_performance_publish_samples(repeated_request) + .await + .unwrap() + .into_inner(); + assert_eq!(repeated.outcome, MutationOutcome::AlreadyApplied as i32); + assert_eq!(repeated.revision, first_reply.revision); + let mut performance = fixture.host.game_performance_client(); + let listed = performance + .list(PerformanceListRequest { + page: Some(PageRequest { + context: Some(fixture.context()), + cursor: String::new(), + page_size: 10, + common_data_categories: None, + }), + projection_id: "performance.v1".into(), + ..Default::default() + }) + .await + .unwrap() + .into_inner(); + assert_eq!(listed.series[0].coverage, "gapped"); + assert_eq!(listed.series[0].dropped_samples, 4); + + let stale = request( + &fixture, + "performance-stale", + first_reply.revision, + vec![sample(4, now, 60.0)], + ); + assert_eq!( + fixture + .client() + .game_performance_publish_samples(stale) + .await + .unwrap_err() + .code(), + Code::Aborted + ); + + let pressure = request( + &fixture, + "performance-pressure", + first_reply.revision, + vec![sample(6, now, 60.0)], + ); + let pressure = fixture + .client() + .game_performance_publish_samples(pressure) + .await + .unwrap() + .into_inner(); + assert_eq!(pressure.outcome, MutationOutcome::Backpressure as i32); + assert_eq!(pressure.dropped_samples, 1); + assert!(pressure.retry_after_ms > 0); +} + +#[tokio::test] +async fn performance_reports_reject_invalid_units_normalization_and_future_samples() { + let fixture = fixture().await; + let now = crate::plugin_host::resources::unix_now().unwrap() * 1000; + let mut wrong_unit = request(&fixture, "performance-unit", 0, vec![sample(1, now, 60.0)]); + wrong_unit.memory_unit = "percent".into(); + assert_eq!( + fixture + .client() + .game_performance_publish_samples(wrong_unit) + .await + .unwrap_err() + .code(), + Code::InvalidArgument + ); + + let mut wrong_normalization = + request(&fixture, "performance-cpu", 0, vec![sample(1, now, 60.0)]); + wrong_normalization.cpu_normalization = PerformanceCpuNormalization::WholeMachinePercent as i32; + wrong_normalization.samples[0].cpu_percent = 101.0; + assert_eq!( + fixture + .client() + .game_performance_publish_samples(wrong_normalization) + .await + .unwrap_err() + .code(), + Code::InvalidArgument + ); + + let mut future = request( + &fixture, + "performance-future", + 0, + vec![sample(1, now + 400_000, 60.0)], + ); + future.samples[0].observed_at = now + 400_000; + assert_eq!( + fixture + .client() + .game_performance_publish_samples(future) + .await + .unwrap_err() + .code(), + Code::InvalidArgument + ); + + let mut excessive = request( + &fixture, + "performance-count", + 0, + vec![sample(1, now, 60.0); 1001], + ); + for (index, item) in excessive.samples.iter_mut().enumerate() { + item.sequence = index as u64 + 1; + item.observed_at = now + index as i64 * 100; + } + assert_eq!( + fixture + .client() + .game_performance_publish_samples(excessive) + .await + .unwrap_err() + .code(), + Code::InvalidArgument + ); +} + +#[tokio::test] +async fn performance_accepts_per_core_cpu_and_frame_time_percentile_semantics() { + let fixture = fixture().await; + let now = crate::plugin_host::resources::unix_now().unwrap() * 1000; + let mut report = request( + &fixture, + "performance-per-core", + 0, + vec![sample(1, now, 120.0)], + ); + report.cpu_scope = PerformanceCpuScope::Process as i32; + report.cpu_normalization = PerformanceCpuNormalization::PerCorePercent as i32; + report.samples[0].cpu_percent = 240.0; + report.samples[0].fps_method = PerformanceFpsMethod::FrameTimeDerived as i32; + report.samples[0].fps_statistic = PerformanceFpsStatistic::Percentile as i32; + report.samples[0].sampling_window_ms = 100; + report.samples[0].fps_percentile = Some(95.0); + let reply = fixture + .client() + .game_performance_publish_samples(report) + .await + .unwrap() + .into_inner(); + assert_eq!(reply.accepted_samples, 1); +} + +#[tokio::test] +async fn common_performance_history_requires_an_explicit_selector_and_current_grant() { + use crate::plugin_host::{ + grants::PluginIdentity, shared_data::Publication, sharing_policy::SharingClass, + }; + + let fixture = fixture().await; + let now = crate::plugin_host::resources::unix_now().unwrap(); + fixture + .data_broker + .publish( + Publication { + owner: PluginIdentity { + plugin_id: "source.plugin".into(), + publisher_fingerprint: "cd".repeat(32), + profile_id: "a".into(), + }, + dataset_id: "game.performance.history.v1".into(), + category: Some(CommonDataCategory::GamePerformanceHistory), + class: SharingClass::Common, + schema_id: "game.performance.history.v1".into(), + schema_version: 1, + fields: [ + ("game_id".into(), serde_json::json!("5")), + ("installation_id".into(), serde_json::json!("steam:five")), + ( + "computer_context_id".into(), + serde_json::json!("active-host"), + ), + ("session_id".into(), serde_json::json!("source-session")), + ( + "producer_plugin_id".into(), + serde_json::json!("source.plugin"), + ), + ("runtime_id".into(), serde_json::json!("runtime-main")), + ("runtime_recipe_revision".into(), serde_json::json!("")), + ("collector_source".into(), serde_json::json!("fixture")), + ("fps_unit".into(), serde_json::json!("frames/second")), + ("cpu_unit".into(), serde_json::json!("percent")), + ("memory_unit".into(), serde_json::json!("bytes")), + ("tool_name".into(), serde_json::json!("fixture")), + ("tool_version".into(), serde_json::json!("1")), + ("sample_interval_ms".into(), serde_json::json!(100)), + ( + "cpu_scope".into(), + serde_json::json!(PerformanceCpuScope::Process as i32), + ), + ( + "cpu_normalization".into(), + serde_json::json!(PerformanceCpuNormalization::WholeMachinePercent as i32), + ), + ( + "memory_kind".into(), + serde_json::json!(PerformanceMemoryKind::WorkingSetBytes as i32), + ), + ("memory_source".into(), serde_json::json!("fixture")), + ( + "samples".into(), + serde_json::Value::String( + serde_json::to_string(&serde_json::json!([{ + "observed_at": now * 1000, + "frames_per_second": 60.0, + "cpu_percent": 40.0, + "memory_bytes": 4096, + "sequence": 1, + "sampling_window_ms": 0, + "fps_method": PerformanceFpsMethod::Instantaneous as i32, + "fps_statistic": PerformanceFpsStatistic::Instantaneous as i32, + "fps_percentile": null, + "frames_per_second_min": null, + "frames_per_second_max": null, + "quality": PerformanceMeasurementQuality::Measured as i32 + }])) + .unwrap(), + ), + ), + ] + .into_iter() + .collect(), + opaque_payload: Vec::new(), + resource_id: "performance-source-series".into(), + observed_at: now, + sequence: 1, + source_observation_id: "source-observation-1".into(), + session_id: Some("source-session".into()), + publisher: None, + expires_at: None, + }, + now, + ) + .unwrap(); + + let mut performance = fixture.host.game_performance_client(); + let private = performance + .list(PerformanceListRequest { + page: Some(PageRequest { + context: Some(fixture.context()), + cursor: String::new(), + page_size: 10, + common_data_categories: None, + }), + projection_id: "performance.v1".into(), + ..Default::default() + }) + .await + .unwrap() + .into_inner(); + assert!(private.series.is_empty()); + + let selected_but_not_granted = performance + .list(PerformanceListRequest { + page: Some(PageRequest { + context: Some(fixture.context()), + cursor: String::new(), + page_size: 10, + common_data_categories: Some(CommonDataSelector { + categories: vec![CommonDataCategory::GamePerformanceHistory as i32], + selected_record_ids: Vec::new(), + }), + }), + projection_id: "performance.v1".into(), + ..Default::default() + }) + .await + .unwrap() + .into_inner(); + assert!(selected_but_not_granted.series.is_empty()); +} + +#[tokio::test] +async fn performance_history_flows_to_a_consumer_with_an_explicit_category_grant() { + use crate::plugin_host::sharing_policy::ActivationReadGrant; + + let fixture = fixture().await; + let consumer = + super::data::consumer_session_with_grants(&fixture, &[cap::GAME_PERFORMANCE_READ]).await; + let consumer_context = consumer.host.resource_context().unwrap().clone(); + let recipient = super::data::authenticated_identity(&fixture, &consumer_context); + fixture + .shared_policies + .set_activation_grants( + &recipient, + ActivationReadGrant::new( + [CommonDataCategory::GamePerformanceHistory], + std::iter::empty(), + ) + .unwrap(), + ) + .unwrap(); + + let now = crate::plugin_host::resources::unix_now().unwrap() * 1000; + let published = fixture + .client() + .game_performance_publish_samples(request( + &fixture, + "producer-performance", + 0, + vec![sample(1, now - 100, 59.0)], + )) + .await + .unwrap() + .into_inner(); + + let mut performance = consumer.host.game_performance_client(); + let list = |selector| PerformanceListRequest { + page: Some(PageRequest { + context: Some(consumer_context.clone()), + page_size: 10, + common_data_categories: selector, + ..Default::default() + }), + game_id: "5".into(), + computer_context_id: "active-host".into(), + projection_id: "performance.v1".into(), + }; + assert!( + performance + .list(list(None)) + .await + .unwrap() + .into_inner() + .series + .is_empty() + ); + let listed = performance + .list(list(Some(CommonDataSelector { + categories: vec![CommonDataCategory::GamePerformanceHistory as i32], + selected_record_ids: Vec::new(), + }))) + .await + .unwrap() + .into_inner(); + assert_eq!(listed.series.len(), 1); + assert_eq!(listed.series[0].series_id, published.report_id); + assert_eq!(listed.series[0].samples.len(), 1); + assert_eq!(listed.series[0].samples[0].frames_per_second, 59.0); +} + +#[tokio::test] +async fn performance_series_quota_backpressures_without_losing_accepted_samples() { + let fixture = fixture().await; + let now = crate::plugin_host::resources::unix_now().unwrap() * 1000; + let mut revision = 0; + let mut next_sequence = 1; + let mut accepted = 0; + let mut saw_backpressure = false; + for batch in 0..8 { + if batch > 0 { + tokio::time::sleep(Duration::from_millis(1001)).await; + } + let samples = (0..BATCH_SIZE) + .map(|offset| { + let sequence = next_sequence + offset as u64; + let observed_at = now - 600_000 + (sequence as i64 - 1) * 100; + sample(sequence, observed_at, 60.0) + }) + .collect(); + let report = request( + &fixture, + &format!("performance-quota-{batch}"), + revision, + samples, + ); + let validation = super::super::performance::validate_request(&report, now + 1); + assert!( + validation.is_ok(), + "batch {batch} validation failed: {validation:?}" + ); + let reply = fixture + .client() + .game_performance_publish_samples(report) + .await + .unwrap_or_else(|error| panic!("quota batch {batch} failed: {error:?}")) + .into_inner(); + if reply.outcome == MutationOutcome::Backpressure as i32 { + saw_backpressure = true; + assert_eq!(reply.accepted_samples, 0); + assert_eq!(reply.dropped_samples, BATCH_SIZE as u32); + break; + } + accepted += reply.accepted_samples as usize; + revision = reply.revision; + next_sequence += BATCH_SIZE as u64; + } + assert!( + saw_backpressure, + "a growing series should hit the 1 MiB retained-record quota" + ); + assert!(accepted >= 1000); + + let mut performance = fixture.host.game_performance_client(); + let listed = performance + .list(PerformanceListRequest { + page: Some(PageRequest { + context: Some(fixture.context()), + cursor: String::new(), + page_size: 1, + common_data_categories: None, + }), + projection_id: "performance.v1".into(), + ..Default::default() + }) + .await + .unwrap() + .into_inner(); + assert_eq!(listed.series.len(), 1); + assert_eq!(listed.series[0].samples.len(), accepted); +} diff --git a/crates/app/src/plugin_host/resources/tests/persistence.rs b/crates/app/src/plugin_host/resources/tests/persistence.rs new file mode 100644 index 000000000..814f3d0e5 --- /dev/null +++ b/crates/app/src/plugin_host/resources/tests/persistence.rs @@ -0,0 +1,482 @@ +//! Logical Persistence administration stays in the authenticated private namespace. + +use super::*; +use crate::plugin_host::storage::MAX_VALUE_BYTES; + +const STORAGE: &[&str] = &[ + cap::STORAGE_READ, + cap::STORAGE_WRITE, + cap::STORAGE_DELETE, + cap::STORAGE_PERSIST, +]; + +#[tokio::test] +async fn persistence_admin_is_logical_paged_and_bound_to_authenticated_owner() { + let fixture = Fixture::new(STORAGE).await; + let _first = fixture + .store("alpha", b"one", StorageDurability::Persistent, 0) + .await + .unwrap(); + let second = fixture + .store("beta", b"two", StorageDurability::Persistent, 0) + .await + .unwrap(); + let mut client = fixture.client(); + + let usage = client + .persistence_get_usage(PersistenceUsageRequest { + context: Some(fixture.context()), + }) + .await + .unwrap() + .into_inner(); + assert_eq!(usage.logical_bytes, (5 + 3 + 64) + (4 + 3 + 64)); + assert_eq!(usage.quota_bytes, crate::plugin_host::storage::QUOTA_BYTES); + assert!(usage.physical_bytes > 0); + assert!(usage.physical_bytes_namespace_wide); + assert_eq!(usage.categories.len(), 1); + assert_eq!(usage.categories[0].category, "private"); + assert_eq!(usage.categories[0].records, 2); + assert_eq!( + usage.categories[0].logical_bytes, + (5 + 3 + 64) + (4 + 3 + 64) + ); + assert_eq!(usage.categories[0].protected_records, 0); + + let first_page = client + .persistence_list_entries(PersistenceListRequest { + page: Some(PageRequest { + context: Some(fixture.context()), + page_size: 1, + ..Default::default() + }), + category: "private".into(), + }) + .await + .unwrap() + .into_inner(); + assert_eq!(first_page.entries.len(), 1); + assert_eq!(first_page.entries[0].logical_key, "alpha"); + assert_eq!(first_page.entries[0].category, "private"); + assert_eq!(first_page.entries[0].size_bytes, 3); + assert_eq!(first_page.entries[0].entry_id.len(), 64); + assert!(!first_page.entries[0].entry_id.contains('/')); + assert!(!first_page.next_cursor.is_empty()); + + let second_page = client + .persistence_list_entries(PersistenceListRequest { + page: Some(PageRequest { + context: Some(fixture.context()), + cursor: first_page.next_cursor.clone(), + page_size: 1, + ..Default::default() + }), + category: "private".into(), + }) + .await + .unwrap() + .into_inner(); + assert_eq!(second_page.entries[0].logical_key, "beta"); + assert!(second_page.next_cursor.is_empty()); + + let consumer = + super::data::consumer_session_with_grants(&fixture, &[cap::STORAGE_PERSIST]).await; + let foreign_context = consumer.host.resource_context().unwrap().clone(); + let status = client + .persistence_list_entries(PersistenceListRequest { + page: Some(PageRequest { + context: Some(foreign_context.clone()), + cursor: first_page.next_cursor, + page_size: 1, + ..Default::default() + }), + category: "private".into(), + }) + .await + .unwrap_err(); + assert_eq!(status.code(), Code::FailedPrecondition); + + let mut foreign_mutation = fixture.mutation("foreign-delete", 0); + foreign_mutation.context = Some(foreign_context); + let status = client + .persistence_delete_entries(PersistenceDeleteRequest { + mutation: Some(foreign_mutation), + entry_ids: vec![first_page.entries[0].entry_id.clone()], + }) + .await + .unwrap_err(); + assert_eq!(status.code(), Code::NotFound); + + let status = client + .persistence_list_entries(PersistenceListRequest { + page: Some(PageRequest { + context: Some(fixture.context()), + ..Default::default() + }), + category: "../private".into(), + }) + .await + .unwrap_err(); + assert_eq!(status.code(), Code::InvalidArgument); + + let deletion = client + .persistence_delete_entries(PersistenceDeleteRequest { + mutation: Some(fixture.mutation("delete-alpha", second.revision)), + entry_ids: vec![first_page.entries[0].entry_id.clone()], + }) + .await + .unwrap() + .into_inner(); + assert_eq!(deletion.outcome, MutationOutcome::Applied as i32); + + let policy = client + .persistence_set_retention_policy(RetentionPolicyRequest { + mutation: Some(fixture.mutation("retention", deletion.revision)), + category: "private".into(), + max_age_seconds: 3600, + max_bytes: 1024, + }) + .await + .unwrap() + .into_inner(); + assert_eq!(policy.outcome, MutationOutcome::Applied as i32); + + let cleared = client + .persistence_clear(PersistenceClearRequest { + mutation: Some(fixture.mutation("clear", policy.revision)), + category: "private".into(), + }) + .await + .unwrap() + .into_inner(); + assert_eq!(cleared.outcome, MutationOutcome::Applied as i32); + assert!(!fixture.load("beta").await.unwrap().found); +} + +#[tokio::test] +async fn persistence_admin_keeps_session_values_out_and_expires_by_retention_age() { + let fixture = Fixture::new(STORAGE).await; + fixture + .store("session-only", b"two", StorageDurability::SessionOnly, 0) + .await + .unwrap(); + let stored = fixture + .store("durable", b"one", StorageDurability::Persistent, 0) + .await + .unwrap(); + let mut client = fixture.client(); + + let usage = client + .persistence_get_usage(PersistenceUsageRequest { + context: Some(fixture.context()), + }) + .await + .unwrap() + .into_inner(); + assert_eq!(usage.logical_bytes, 7 + 3 + 64); + + let page = client + .persistence_list_entries(PersistenceListRequest { + page: Some(PageRequest { + context: Some(fixture.context()), + ..Default::default() + }), + category: "private".into(), + }) + .await + .unwrap() + .into_inner(); + assert_eq!( + page.entries + .iter() + .map(|entry| entry.logical_key.as_str()) + .collect::>(), + ["durable"] + ); + + fixture.clock.store(1_000_061, Ordering::SeqCst); + let policy = client + .persistence_set_retention_policy(RetentionPolicyRequest { + mutation: Some(fixture.mutation("retention-age", stored.revision)), + category: "private".into(), + max_age_seconds: 60, + max_bytes: 0, + }) + .await + .unwrap() + .into_inner(); + assert_eq!(policy.outcome, MutationOutcome::Applied as i32); + let page = client + .persistence_list_entries(PersistenceListRequest { + page: Some(PageRequest { + context: Some(fixture.context()), + ..Default::default() + }), + category: "private".into(), + }) + .await + .unwrap() + .into_inner(); + assert!(page.entries.is_empty()); +} + +#[tokio::test] +async fn persistence_admin_rejects_a_stale_revision_and_replays_the_answer() { + let fixture = Fixture::new(STORAGE).await; + let stored = fixture + .store("alpha", b"one", StorageDurability::Persistent, 0) + .await + .unwrap(); + let mut client = fixture.client(); + let entry = client + .persistence_list_entries(PersistenceListRequest { + page: Some(PageRequest { + context: Some(fixture.context()), + ..Default::default() + }), + category: "private".into(), + }) + .await + .unwrap() + .into_inner() + .entries + .remove(0); + + // The caller names a revision that is no longer current. + let request = || PersistenceDeleteRequest { + mutation: Some(fixture.mutation("stale-delete", 0)), + entry_ids: vec![entry.entry_id.clone()], + }; + let conflict = client + .persistence_delete_entries(request()) + .await + .unwrap() + .into_inner(); + assert_eq!(conflict.outcome, MutationOutcome::RevisionConflict as i32); + assert_eq!(conflict.revision, stored.revision); + assert!(fixture.load("alpha").await.unwrap().found); + + // The same idempotency key replays the stored answer instead of deleting. + let replay = client + .persistence_delete_entries(request()) + .await + .unwrap() + .into_inner(); + assert_eq!(replay, conflict); + assert!(fixture.load("alpha").await.unwrap().found); + + let deleted = client + .persistence_delete_entries(PersistenceDeleteRequest { + mutation: Some(fixture.mutation("fresh-delete", stored.revision)), + entry_ids: vec![entry.entry_id], + }) + .await + .unwrap() + .into_inner(); + assert_eq!(deleted.outcome, MutationOutcome::Applied as i32); + assert!(!fixture.load("alpha").await.unwrap().found); +} + +#[tokio::test] +async fn host_protection_is_not_reachable_from_plugin_rpcs() { + let fixture = Fixture::new(STORAGE).await; + let alpha = fixture + .store("alpha", b"one", StorageDurability::Persistent, 0) + .await + .unwrap(); + let beta = fixture + .store("beta", b"two", StorageDurability::Persistent, 0) + .await + .unwrap(); + let resolver = fixture + .api + .profiles() + .resolver("fixture.plugin", &"ab".repeat(32), None) + .unwrap(); + let epoch = fixture.api.profiles().epoch(); + assert!( + fixture + .storage + .set_persistence_protected(&resolver, epoch, "alpha", true) + .await + .unwrap() + ); + let mut client = fixture.client(); + + let usage = client + .persistence_get_usage(PersistenceUsageRequest { + context: Some(fixture.context()), + }) + .await + .unwrap() + .into_inner(); + assert_eq!(usage.categories[0].protected_records, 1); + assert_eq!(usage.categories[0].records, 2); + + let page = client + .persistence_list_entries(PersistenceListRequest { + page: Some(PageRequest { + context: Some(fixture.context()), + ..Default::default() + }), + category: "private".into(), + }) + .await + .unwrap() + .into_inner(); + let protected = page + .entries + .iter() + .find(|entry| entry.logical_key == "alpha") + .unwrap(); + assert!(protected.user_protected); + + // A plugin cannot overwrite, delete, or bulk-delete the protected record. + let status = fixture + .store( + "alpha", + b"changed", + StorageDurability::Persistent, + alpha.revision, + ) + .await + .unwrap_err(); + assert_eq!(status.code(), Code::FailedPrecondition); + let status = fixture + .remove("alpha", alpha.revision, "protected") + .await + .unwrap_err(); + assert_eq!(status.code(), Code::FailedPrecondition); + let status = client + .persistence_delete_entries(PersistenceDeleteRequest { + mutation: Some(fixture.mutation("protected", beta.revision)), + entry_ids: vec![protected.entry_id.clone()], + }) + .await + .unwrap_err(); + assert_eq!(status.code(), Code::FailedPrecondition); + + // A clear removes the unprotected entries and reports the protected one as retained. + let cleared = client + .persistence_clear(PersistenceClearRequest { + mutation: Some(fixture.mutation("clear-unprotected", beta.revision)), + category: "private".into(), + }) + .await + .unwrap() + .into_inner(); + assert_eq!(cleared.outcome, MutationOutcome::Applied as i32); + assert!(fixture.load("alpha").await.unwrap().found); + assert!(!fixture.load("beta").await.unwrap().found); + + // Only the host can release protection; then the plugin delete succeeds. + assert!( + fixture + .storage + .set_persistence_protected(&resolver, epoch, "alpha", false) + .await + .unwrap() + ); + let removed = fixture + .remove("alpha", alpha.revision, "protected-again") + .await + .unwrap(); + assert_eq!(removed.outcome, MutationOutcome::Applied as i32); + assert!(!fixture.load("alpha").await.unwrap().found); +} + +#[tokio::test] +async fn quota_exhaustion_preserves_previously_persisted_entries() { + let fixture = Fixture::new(STORAGE).await; + let big = vec![7u8; MAX_VALUE_BYTES]; + let mut stored = 0_u64; + loop { + let key = format!("big-{stored}"); + match fixture + .store(&key, &big, StorageDurability::Persistent, 0) + .await + { + Ok(_) => stored += 1, + Err(status) => { + assert_eq!(status.code(), Code::ResourceExhausted); + break; + } + } + } + assert!( + (14..=15).contains(&stored), + "{stored} values of 1 MiB fit in the quota" + ); + + let expected: u64 = (0..stored) + .map(|index| { + let key = format!("big-{index}"); + key.len() as u64 + MAX_VALUE_BYTES as u64 + 64 + }) + .sum(); + let mut client = fixture.client(); + let before = client + .persistence_get_usage(PersistenceUsageRequest { + context: Some(fixture.context()), + }) + .await + .unwrap() + .into_inner(); + assert_eq!(before.logical_bytes, expected); + assert_eq!(before.categories[0].records, stored); + assert_eq!(before.categories[0].logical_bytes, expected); + + // The refused write changes neither accounting nor any earlier entry. + let status = fixture + .store("one-more", &big, StorageDurability::Persistent, 0) + .await + .unwrap_err(); + assert_eq!(status.code(), Code::ResourceExhausted); + let after = client + .persistence_get_usage(PersistenceUsageRequest { + context: Some(fixture.context()), + }) + .await + .unwrap() + .into_inner(); + assert_eq!(after, before); + + let page = client + .persistence_list_entries(PersistenceListRequest { + page: Some(PageRequest { + context: Some(fixture.context()), + page_size: 200, + ..Default::default() + }), + category: "private".into(), + }) + .await + .unwrap() + .into_inner(); + assert_eq!(page.entries.len() as u64, stored); + for index in 0..stored { + assert!( + page.entries + .iter() + .any(|entry| entry.logical_key == format!("big-{index}")) + ); + } + assert_eq!( + fixture.load("big-0").await.unwrap().value, + big, + "the prior value is byte-for-byte intact" + ); +} + +#[tokio::test] +async fn persistence_admin_requires_persist_permission() { + let fixture = Fixture::new(&[cap::STORAGE_READ]).await; + let mut client = fixture.client(); + let status = client + .persistence_get_usage(PersistenceUsageRequest { + context: Some(fixture.context()), + }) + .await + .unwrap_err(); + assert_eq!(status.code(), Code::PermissionDenied); +} diff --git a/crates/app/src/plugin_host/resources/tests/ports.rs b/crates/app/src/plugin_host/resources/tests/ports.rs new file mode 100644 index 000000000..4ccd91667 --- /dev/null +++ b/crates/app/src/plugin_host/resources/tests/ports.rs @@ -0,0 +1,280 @@ +//! Ports over the real transport, with a controlled guided-setup adapter. +use super::*; +use crate::plugin_host::jobs::JobOwner; +const GRANTS: &[&str] = &[cap::PORTS_READ, cap::PORTS_INSTALL]; +fn catalog() -> Vec { + ["alpha", "beta"] + .into_iter() + .map(|s| PortRecord { + port_id: format!("qcat_{s}"), + name: s.into(), + platform: "windows".into(), + availability: "available".into(), + }) + .collect() +} +async fn setup() -> (Fixture, Arc) { + let f = Fixture::new(GRANTS).await; + let host = f.with_host(); + host.port_support.store(true, Ordering::SeqCst); + *host.port_records.lock().unwrap() = catalog(); + (f, host) +} +async fn install( + f: &Fixture, + key: &str, + port: &str, + handles: Vec, + revision: u64, + game: &str, +) -> Result { + f.client() + .ports_request_install(PortInstallRequest { + mutation: Some(f.mutation(key, revision)), + port_id: port.into(), + game_id: game.into(), + supplied_file_handles: handles, + user_intent_id: String::new(), + }) + .await + .map(Response::into_inner) +} +async fn reviewed(host: &FakeHost) { + tokio::time::timeout(Duration::from_secs(5), async { + while host.port_reviews.lock().unwrap().is_empty() { + tokio::task::yield_now().await; + } + }) + .await + .unwrap(); +} +async fn ended(f: &Fixture, id: &str) -> JobReply { + let caller = f + .api + .authorize_resource_session(Some(&f.context())) + .unwrap(); + let owner = JobOwner::of(&caller).unwrap(); + tokio::time::timeout(Duration::from_secs(5), async { + loop { + let job = f.jobs.get(&owner, id).unwrap(); + if !matches!(job.state(), JobState::Queued | JobState::Running) { + return job; + } + tokio::time::sleep(Duration::from_millis(5)).await; + } + }) + .await + .unwrap() +} +#[tokio::test] +async fn catalog_and_details_are_bounded_read_only_and_reject_stale_cursors_and_urls() { + let (f, host) = setup().await; + let list = |cursor: String| PortsListRequest { + page: Some(PageRequest { + context: Some(f.context()), + cursor, + page_size: 1, + ..Default::default() + }), + platform: "windows".into(), + query: String::new(), + }; + let first = f + .client() + .ports_list(list(String::new())) + .await + .unwrap() + .into_inner(); + assert_eq!(first.ports[0].port_id, "qcat_alpha"); + assert!(!first.next_cursor.is_empty()); + let next = f + .client() + .ports_list(list(first.next_cursor.clone())) + .await + .unwrap() + .into_inner(); + assert_eq!(next.ports[0].port_id, "qcat_beta"); + let detail = f + .client() + .ports_detail(PortDetailRequest { + context: Some(f.context()), + port_id: "qcat_alpha".into(), + }) + .await + .unwrap() + .into_inner(); + assert_eq!(detail.port.unwrap(), first.ports[0]); + for id in ["https://bad.invalid/install.exe", "../file"] { + assert_eq!( + f.client() + .ports_detail(PortDetailRequest { + context: Some(f.context()), + port_id: id.into() + }) + .await + .unwrap_err() + .code(), + Code::InvalidArgument + ); + } + host.port_records.lock().unwrap()[0].availability = "blocked".into(); + assert_eq!( + f.client() + .ports_list(list(first.next_cursor)) + .await + .unwrap_err() + .code(), + Code::FailedPrecondition + ); + let mut linux = list(String::new()); + linux.platform = "linux".into(); + assert!( + f.client() + .ports_list(linux) + .await + .unwrap() + .into_inner() + .ports + .is_empty() + ); + f.api + .revoke_session_permission("fixture", cap::PORTS_READ) + .await; + assert_eq!( + f.client() + .ports_list(list(String::new())) + .await + .unwrap_err() + .code(), + Code::PermissionDenied + ); +} +#[tokio::test] +async fn installation_waits_for_core_and_retries_reuse_the_job() { + let (f, host) = setup().await; + let job = install(&f, "one", "qcat_alpha", vec![], 0, "") + .await + .unwrap(); + reviewed(&host).await; + assert_eq!(host.port_effects.load(Ordering::SeqCst), 0); + assert_eq!( + install(&f, "one", "qcat_alpha", vec![], 0, "") + .await + .unwrap() + .job_id, + job.job_id + ); + assert_eq!(host.port_reviews.lock().unwrap().len(), 1); + host.port_gate.notify_one(); + assert_eq!(ended(&f, &job.job_id).await.state(), JobState::Succeeded); + assert_eq!(host.port_effects.load(Ordering::SeqCst), 1); +} +#[tokio::test] +async fn linux_arbitrary_installers_and_unapproved_handles_never_open_setup() { + let (f, host) = setup().await; + host.port_support.store(false, Ordering::SeqCst); + assert_eq!( + install(&f, "linux", "qcat_alpha", vec![], 0, "") + .await + .unwrap_err() + .code(), + Code::Unavailable + ); + host.port_support.store(true, Ordering::SeqCst); + assert_eq!( + install(&f, "url", "https://bad.invalid/file.exe", vec![], 0, "") + .await + .unwrap_err() + .code(), + Code::InvalidArgument + ); + assert_eq!( + install( + &f, + "files", + "qcat_alpha", + vec!["path/or/handle".into()], + 0, + "" + ) + .await + .unwrap_err() + .code(), + Code::PermissionDenied + ); + assert!(host.port_reviews.lock().unwrap().is_empty()); +} +#[tokio::test] +async fn declined_revoked_and_cancelled_requests_have_no_installation_effects() { + for mode in ["decline", "revoke", "cancel"] { + let (f, host) = setup().await; + let job = install(&f, mode, "qcat_alpha", vec![], 0, "") + .await + .unwrap(); + reviewed(&host).await; + match mode { + "decline" => host.port_declined.store(true, Ordering::SeqCst), + "revoke" => { + f.api + .revoke_session_permission("fixture", cap::PORTS_INSTALL) + .await + } + "cancel" => { + let caller = f + .api + .authorize_resource_session(Some(&f.context())) + .unwrap(); + let owner = JobOwner::of(&caller).unwrap(); + let jobs = f.jobs.clone(); + let id = job.job_id.clone(); + let cancellation = tokio::spawn(async move { jobs.cancel(&owner, &id).await }); + tokio::time::sleep(Duration::from_millis(20)).await; + host.port_gate.notify_one(); + cancellation.await.unwrap().unwrap(); + } + _ => unreachable!(), + } + if mode != "cancel" { + host.port_gate.notify_one(); + } + assert_ne!(ended(&f, &job.job_id).await.state(), JobState::Succeeded); + assert_eq!(host.port_effects.load(Ordering::SeqCst), 0); + } +} +#[tokio::test] +async fn supplied_handles_stay_scoped_and_replaced_source_folders_are_rejected_after_review() { + let grants = [cap::PORTS_INSTALL, cap::FILES_READ]; + let (f, folder) = Fixture::emulator(&grants).await; + let host = f.with_host(); + host.port_support.store(true, Ordering::SeqCst); + *host.port_records.lock().unwrap() = catalog(); + let handle = f.approve("id-fixture:1", "save", &folder).await; + let revision = f.feed.revision_of("fixture:1").unwrap(); + assert_eq!( + install( + &f, + "tamper", + "qcat_alpha", + vec!["edited".into()], + revision, + "3" + ) + .await + .unwrap_err() + .code(), + Code::NotFound + ); + let job = install(&f, "source", "qcat_alpha", vec![handle], revision, "3") + .await + .unwrap(); + reviewed(&host).await; + let review = host.port_reviews.lock().unwrap()[0].clone(); + assert_eq!(review.sources.len(), 1); + assert_eq!(review.sources[0].path, folder.to_string_lossy()); + assert!(review.sources[0].directory); + std::fs::rename(&folder, folder.with_extension("old")).unwrap(); + std::fs::create_dir(&folder).unwrap(); + host.port_gate.notify_one(); + assert_eq!(ended(&f, &job.job_id).await.state(), JobState::Failed); + assert_eq!(host.port_effects.load(Ordering::SeqCst), 0); +} diff --git a/crates/app/src/plugin_host/resources/tests/runtimes.rs b/crates/app/src/plugin_host/resources/tests/runtimes.rs new file mode 100644 index 000000000..fd3e25bb9 --- /dev/null +++ b/crates/app/src/plugin_host/resources/tests/runtimes.rs @@ -0,0 +1,938 @@ +use super::*; +use gamenode_core::library::LibraryStore as _; +use gamenode_plugin_sdk::proto::{ + ExtensionNamespacePatch, ExtensionPatch, ExtensionPayload, extension_namespace_patch::Operation, +}; +use gamenode_plugin_sdk::resources::{ + RuntimeArgumentTemplate as SdkArgument, RuntimeExecutableHints, RuntimeSpec, +}; +use prost_types::{Struct, Value, value::Kind}; +use sha2::{Digest, Sha256}; +use std::sync::Mutex as StdMutex; +use std::sync::atomic::{AtomicBool, Ordering}; +use tonic::Code; + +use super::super::mutations::mutation_owner; +use crate::plugin_host::runtime_access::{InstalledProgram, RuntimeAccessRequest, RuntimeApprover}; + +#[derive(Default)] +pub(super) struct FakeRuntimeApprover { + chosen: StdMutex>, + requests: StdMutex>, + decline: AtomicBool, + /// Revokes a grant or changes the profile while the picker is open. + race: StdMutex)>>, +} + +#[tonic::async_trait] +impl RuntimeApprover for FakeRuntimeApprover { + async fn choose_executable( + &self, + request: RuntimeAccessRequest, + ) -> Result, Status> { + self.requests.lock().unwrap().push(request); + let race = self.race.lock().unwrap().clone(); + if let Some((api, permission)) = race { + if let Some(permission) = permission { + api.revoke_session_permission("fixture", permission).await; + } else { + api.profiles().update(Some("changed"), true); + } + } + if self.decline.load(Ordering::SeqCst) { + return Ok(None); + } + Ok(self.chosen.lock().unwrap().clone()) + } +} + +struct PersistentRuntimeHost { + database: std::sync::Arc, +} + +#[tonic::async_trait] +impl LibraryHost for PersistentRuntimeHost { + fn favorites(&self, _: &str) -> Vec<(u64, bool)> { + Vec::new() + } + + fn set_favorite( + &self, + _: &str, + _: u64, + _: bool, + _: &dyn Fn() -> Result<(), Status>, + ) -> Result { + Err(Status::unimplemented("fixture")) + } + + async fn search_catalog(&self, _: String, _: usize) -> Result, Status> { + Ok(Vec::new()) + } + + fn assign_match( + &self, + _: &str, + _: u64, + _: u64, + _: &dyn Fn() -> Result<(), Status>, + ) -> Result { + Err(Status::unimplemented("fixture")) + } + + async fn read_artwork(&self, _: String, _: u64) -> Result { + Err(Status::not_found("fixture")) + } + + async fn set_artwork( + &self, + _: String, + _: u64, + _: Option, + _: CommitGuard, + ) -> Result { + Err(Status::unimplemented("fixture")) + } + + async fn set_display_name( + &self, + _: String, + _: u64, + _: Option, + _: CommitGuard, + ) -> Result { + Err(Status::unimplemented("fixture")) + } + + async fn runtime_resources( + &self, + owner_key: String, + ) -> Result, Status> { + let database = self.database.clone(); + tokio::task::spawn_blocking(move || database.library_store().runtime_resources(&owner_key)) + .await + .map_err(|error| Status::internal(error.to_string()))? + .map_err(|error| Status::internal(error.to_string())) + } + + async fn runtime_resource( + &self, + owner_key: String, + runtime_id: String, + ) -> Result, Status> { + let database = self.database.clone(); + tokio::task::spawn_blocking(move || { + database + .library_store() + .runtime_resource(&owner_key, &runtime_id) + }) + .await + .map_err(|error| Status::internal(error.to_string()))? + .map_err(|error| Status::internal(error.to_string())) + } + + async fn save_runtime_resource( + &self, + owner_key: String, + runtime: gamenode_core::library::RuntimeResource, + ) -> Result { + let database = self.database.clone(); + tokio::task::spawn_blocking(move || { + database + .library_store() + .save_runtime_resource(&owner_key, &runtime) + }) + .await + .map_err(|error| Status::internal(error.to_string()))? + .map_err(|error| Status::internal(error.to_string())) + } + + async fn runtime_catalog_revision(&self, owner_key: String) -> Result { + let database = self.database.clone(); + tokio::task::spawn_blocking(move || { + database + .library_store() + .runtime_catalog_revision(&owner_key) + }) + .await + .map_err(|error| Status::internal(error.to_string()))? + .map_err(|error| Status::internal(error.to_string())) + } +} + +fn extension(note: &str) -> ExtensionPayload { + let schema = br#"{"type":"object","properties":{"note":{"type":"string","x-gamenode-classification":"public"}},"required":["note"],"additionalProperties":false}"#; + ExtensionPayload { + schema_id: "fixture.plugin.runtime.v1".into(), + schema_version: 1, + schema_digest: Sha256::digest(schema).to_vec(), + data: Some(Struct { + fields: BTreeMap::from([( + "note".into(), + Value { + kind: Some(Kind::StringValue(note.into())), + }, + )]), + }), + } +} + +fn runtime_schema() -> ExtensionSchemaDescriptor { + let schema = br#"{"type":"object","properties":{"note":{"type":"string","x-gamenode-classification":"public"}},"required":["note"],"additionalProperties":false}"#; + ExtensionSchemaDescriptor { + namespace: "fixture.plugin.runtime".into(), + schema_id: "fixture.plugin.runtime.v1".into(), + schema_version: 1, + schema_digest: Sha256::digest(schema).to_vec(), + schema_json: schema.to_vec(), + fields: vec![ExtensionSchemaField { + path: "note".into(), + classification: ExtensionFieldClassification::Public as i32, + }], + optional: true, + } +} + +fn extension_for(schema_id: &str, note: &str) -> ExtensionPayload { + ExtensionPayload { + schema_id: schema_id.into(), + schema_version: 1, + schema_digest: vec![9; 32], + data: Some(Struct { + fields: BTreeMap::from([( + "note".into(), + Value { + kind: Some(Kind::StringValue(note.into())), + }, + )]), + }), + } +} + +fn runtime(handle: String) -> RuntimeSpec { + RuntimeSpec { + name: "Runtime A".into(), + version: "1.0".into(), + executable_handle: handle, + supported_formats: vec!["snes-rom".into()], + platform: "linux".into(), + argument_template: vec![SdkArgument::Literal("--safe".into())], + extensions: HashMap::from([ + ("fixture.plugin.runtime".into(), extension("known-v1")), + ( + "fixture.plugin.future".into(), + extension_for("fixture.plugin.future.v1", "unknown-to-old-client"), + ), + ]), + } +} + +impl Fixture { + /// Connects a runtime picker that approves `path`. + pub(super) fn runtime_approving(&self, path: &std::path::Path) -> Arc { + let approver = Arc::new(FakeRuntimeApprover::default()); + *approver.chosen.lock().unwrap() = Some(path.to_path_buf()); + self.files.set_runtime_approver(approver.clone()); + approver + } + + pub(super) fn runtime_request( + &self, + name: &str, + hints: &[&str], + key: &str, + expected_revision: u64, + ) -> RuntimeRequestAccessRequest { + RuntimeRequestAccessRequest { + mutation: Some(self.mutation(key, expected_revision)), + runtime: Some(RuntimeRecord { + name: name.into(), + version: "1.0".into(), + platform: "linux".into(), + supported_formats: vec!["rom".into()], + argument_template: vec![RuntimeArgumentTemplate { + value: Some(runtime_argument_template::Value::Literal("--safe".into())), + }], + ..Default::default() + }), + hints: Some(RuntimeAccessHints { + executable_names: hints.iter().map(|hint| (*hint).into()).collect(), + desktop_ids: Vec::new(), + }), + } + } + + /// A fixture with one approved installation folder holding `emulator`, registered as the + /// caller's runtime. The returned path is the installation folder. + pub(super) async fn approved_runtime( + grants: &[&'static str], + ) -> (Self, RuntimeRecord, std::path::PathBuf) { + let fixture = Self::new(grants).await; + let dir = fixture.game_dir( + "runtime", + &[("emulator", b"binary"), ("content.rom", b"rom")], + ); + fixture.library_in(&[("fixture:1", Some(3), "Emulated", &dir)]); + let root = fixture.approve("id-fixture:1", "installation", &dir).await; + let executable = fixture.child(&root, "emulator").await; + fixture.with_host(); + let runtime = fixture.runtime_record(executable).await; + (fixture, runtime, dir) + } + + /// Registers an already approved executable handle as this plugin's runtime. + async fn runtime_record(&self, executable_handle: String) -> RuntimeRecord { + self.host + .resources() + .unwrap() + .runtime_register( + RuntimeSpec { + name: "Runtime".into(), + version: "1.0".into(), + executable_handle, + supported_formats: vec!["rom".into()], + platform: "linux".into(), + argument_template: vec![SdkArgument::Literal("--safe".into())], + extensions: HashMap::new(), + }, + 0, + "register-runtime", + ) + .await + .unwrap() + .runtime + .unwrap() + } + + /// Points a runtime at another approved executable and returns the revised record. + pub(super) async fn update_runtime_executable( + &self, + runtime: &RuntimeRecord, + executable_handle: String, + ) -> RuntimeRecord { + self.host + .resources() + .unwrap() + .runtime_update( + &runtime.id, + RuntimeSpec { + name: runtime.name.clone(), + version: runtime.version.clone(), + executable_handle, + supported_formats: runtime.supported_formats.clone(), + platform: runtime.platform.clone(), + argument_template: vec![SdkArgument::Literal("--safe".into())], + extensions: HashMap::new(), + }, + ["executable_handle"], + runtime.revision, + "update-runtime", + ) + .await + .unwrap() + .runtime + .unwrap() + } +} + +#[tokio::test] +async fn runtime_namespace_patches_are_owner_checked_revisioned_and_preserve_old_client_data() { + let fixture = Fixture::new(&[ + cap::FILES_READ, + cap::GAME_RUNTIME_CREATE, + cap::GAME_RUNTIME_READ, + cap::GAME_RUNTIME_UPDATE, + ]) + .await; + fixture + .api + .set_extension_schemas( + "fixture", + "fixture.plugin", + &"ab".repeat(32), + vec![runtime_schema()], + ) + .unwrap(); + let database_path = fixture._temp.path().join("runtime.sqlite3"); + let database = std::sync::Arc::new( + gamenode_platform::db::SqliteSettingsStore::open(&database_path).unwrap(), + ); + fixture + .feed + .set_host(std::sync::Arc::new(PersistentRuntimeHost { database })); + let dir = fixture.game_dir("runtime", &[("emulator", b"binary")]); + fixture.library_in(&[("fixture:1", None, "Game", &dir)]); + fixture.user_approving(&dir); + let root = fixture.root_handle("id-fixture:1", &["read"]).await; + let executable = fixture.child(&root, "emulator").await; + let resources = fixture.host.resources().unwrap(); + let mut watch = resources.runtimes_watch(0, None).await.unwrap(); + let registered = resources + .runtime_register(runtime(executable), 0, "register-runtime") + .await + .unwrap(); + assert_eq!(registered.outcome, MutationOutcome::Applied as i32); + let first = registered.runtime.unwrap(); + assert_eq!(first.revision, 1); + let mut invalid_known = extension("wrong shape"); + invalid_known.data.as_mut().unwrap().fields.insert( + "note".into(), + Value { + kind: Some(Kind::NumberValue(7.0)), + }, + ); + assert!( + resources + .runtime_update_patch( + &first.id, + runtime(String::new()), + ExtensionPatch { + expected_revision: 1, + typed_field_mask: vec!["name".into()], + namespaces: vec![ExtensionNamespacePatch { + namespace: "fixture.plugin.runtime".into(), + operation: Some(Operation::Set(invalid_known)), + }], + }, + std::iter::empty::(), + 1, + "reject-invalid-signed-schema-payload", + ) + .await + .is_err() + ); + assert_eq!( + resources + .runtime_get(&first.id, None) + .await + .unwrap() + .revision, + 1 + ); + assert_eq!( + first.extensions["fixture.plugin.future"], + extension_for("fixture.plugin.future.v1", "unknown-to-old-client") + ); + let page = resources.runtimes_page(20, "", None).await.unwrap(); + assert_eq!(page.runtimes.len(), 1); + assert_eq!(page.runtimes[0].id, first.id); + assert_eq!( + page.runtimes[0].extensions["fixture.plugin.future"], + extension_for("fixture.plugin.future.v1", "unknown-to-old-client"), + "the owner can list a usable typed runtime with its opaque optional namespace" + ); + let event = watch + .message() + .await + .unwrap() + .expect("runtime registration should publish a watch event"); + assert_eq!( + event.runtime.unwrap().extensions["fixture.plugin.future"], + extension_for("fixture.plugin.future.v1", "unknown-to-old-client") + ); + + // An update from a client unaware of extensions changes a typed field only. + let mut old = runtime(String::new()); + old.extensions.clear(); + let edited = resources + .runtime_update(&first.id, old.clone(), ["name"], 1, "old-client-update") + .await + .unwrap(); + assert_eq!(edited.outcome, MutationOutcome::Applied as i32); + let second = edited.runtime.unwrap(); + assert_eq!( + second.extensions["fixture.plugin.future"], + extension_for("fixture.plugin.future.v1", "unknown-to-old-client") + ); + + old.name = "Runtime patched".into(); + let patched = resources + .runtime_update_patch( + &first.id, + old, + ExtensionPatch { + expected_revision: 2, + typed_field_mask: vec!["name".into()], + namespaces: vec![ExtensionNamespacePatch { + namespace: "fixture.plugin.runtime".into(), + operation: Some(Operation::Set(extension("known-v2"))), + }], + }, + std::iter::empty::(), + 2, + "patch-known-namespace", + ) + .await + .unwrap(); + assert_eq!(patched.outcome, MutationOutcome::Applied as i32); + let third = patched.runtime.unwrap(); + assert_eq!(third.revision, 3); + assert_eq!(third.name, "Runtime patched"); + assert_eq!( + third.extensions["fixture.plugin.runtime"], + extension("known-v2") + ); + assert_eq!( + third.extensions["fixture.plugin.future"], + extension_for("fixture.plugin.future.v1", "unknown-to-old-client") + ); + + // A stale writer cannot change either the typed fields or namespace payloads. + let stale = resources + .runtime_update_patch( + &first.id, + runtime(String::new()), + ExtensionPatch { + expected_revision: 2, + typed_field_mask: vec!["name".into()], + namespaces: vec![ExtensionNamespacePatch { + namespace: "fixture.plugin.runtime".into(), + operation: Some(Operation::Set(extension("stale"))), + }], + }, + std::iter::empty::(), + 2, + "stale-patch", + ) + .await + .unwrap(); + assert_eq!(stale.outcome, MutationOutcome::RevisionConflict as i32); + let current = resources.runtime_get(&first.id, None).await.unwrap(); + assert_eq!(current.revision, 3); + assert_eq!( + current.extensions["fixture.plugin.runtime"], + extension("known-v2") + ); + assert_eq!( + current.extensions["fixture.plugin.future"], + extension_for("fixture.plugin.future.v1", "unknown-to-old-client") + ); + + // Reopening SQLite between RPCs models a host restart while the client keeps its record ID. + let database = std::sync::Arc::new( + gamenode_platform::db::SqliteSettingsStore::open(&database_path).unwrap(), + ); + fixture + .feed + .set_host(std::sync::Arc::new(PersistentRuntimeHost { database })); + let reopened = resources.runtime_get(&first.id, None).await.unwrap(); + assert_eq!(reopened.revision, 3); + assert_eq!( + reopened.extensions["fixture.plugin.runtime"], + extension("known-v2") + ); + assert_eq!( + reopened.extensions["fixture.plugin.future"], + extension_for("fixture.plugin.future.v1", "unknown-to-old-client") + ); + + let foreign_namespace = resources + .runtime_update_patch( + &first.id, + runtime(String::new()), + ExtensionPatch { + expected_revision: 3, + namespaces: vec![ExtensionNamespacePatch { + namespace: "other.plugin.runtime".into(), + operation: Some(Operation::Set(extension("foreign"))), + }], + ..Default::default() + }, + std::iter::empty::(), + 3, + "foreign-namespace-patch", + ) + .await + .unwrap_err(); + assert_eq!(foreign_namespace.code(), Code::PermissionDenied); + let current = resources.runtime_get(&first.id, None).await.unwrap(); + assert_eq!(current.revision, 3); + assert_eq!( + current.extensions["fixture.plugin.runtime"], + extension("known-v2") + ); + + // A writer without the update grant is rejected before touching the store. + let readonly = Fixture::new(&[cap::FILES_READ, cap::GAME_RUNTIME_READ]).await; + let denied = readonly + .host + .resources() + .unwrap() + .runtime_update_patch( + &first.id, + runtime(String::new()), + ExtensionPatch::default(), + std::iter::empty::(), + 3, + "read-only-patch", + ) + .await + .unwrap_err(); + assert_eq!(denied.code(), Code::PermissionDenied); + assert_eq!( + resources + .runtime_get(&first.id, None) + .await + .unwrap() + .revision, + 3 + ); +} + +fn executable_in(dir: &std::path::Path, name: &str) -> std::path::PathBuf { + use std::os::unix::fs::PermissionsExt; + let path = dir.join(name); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap(); + path +} + +#[tokio::test] +async fn a_runtime_request_prompts_once_creates_the_owned_runtime_and_returns_no_path() { + let fixture = Fixture::new(&[ + cap::GAME_RUNTIME_CREATE, + cap::GAME_RUNTIME_READ, + cap::FILES_READ, + ]) + .await; + let dir = fixture.game_dir("runtime", &[("dolphin-emu", b"binary")]); + let executable = executable_in(&dir, "dolphin-emu"); + let host = fixture.with_host(); + host.installed_programs + .lock() + .unwrap() + .push(InstalledProgram { + display_name: "Dolphin Emulator".into(), + executable: executable.to_string_lossy().into_owned(), + desktop_file: "/usr/share/applications/dolphin-emu.desktop".into(), + package_id: "dolphin-emu;2503-1;x86_64;extra".into(), + package_manager: "pacman".into(), + }); + let approver = fixture.runtime_approving(&executable); + + let reply = fixture + .client() + .runtimes_request_access(fixture.runtime_request( + "Dolphin", + &["dolphin-emu"], + "request-runtime-1", + 0, + )) + .await + .unwrap() + .into_inner(); + let runtime = reply.runtime.expect("created runtime"); + assert_eq!(reply.outcome, MutationOutcome::Applied as i32); + assert!(!runtime.id.is_empty()); + assert!(runtime.executable_handle.is_empty()); + assert_eq!(runtime.name, "Dolphin"); + assert!(!format!("{runtime:?}").contains(&dir.to_string_lossy().to_string())); + + let requests = approver.requests.lock().unwrap().clone(); + assert_eq!(requests.len(), 1); + assert_eq!(requests[0].plugin_id, "fixture.plugin"); + assert_eq!(requests[0].candidates[0].path, executable.to_string_lossy()); + assert_eq!(requests[0].candidates[0].display_name, "Dolphin Emulator"); + assert_eq!(requests[0].candidates[0].version, "2503-1"); + + // The ordinary read projection still gives no executable handle. + let read = fixture + .host + .resources() + .unwrap() + .runtime_get(&runtime.id, None) + .await + .unwrap(); + assert!(read.executable_handle.is_empty()); + + // The host can resolve the approved program for a launch, and the plugin does not get the + // path through the runtime record. + let caller = fixture.caller(); + assert_eq!( + fixture + .resource_api + .resolve_runtime_executable(&caller, &runtime.id) + .await + .unwrap(), + executable.canonicalize().unwrap().to_str().unwrap() + ); + let approvals = fixture + .resource_api + .in_namespace(&caller, |namespace| namespace.runtime_approvals()) + .await + .unwrap(); + assert_eq!(approvals.len(), 1); + assert_eq!(approvals[0].runtime_id, runtime.id); + assert!(approvals[0].revoked_at.is_none()); + + // The same key is answered from the recorded outcome without a second prompt. + let replay = fixture + .client() + .runtimes_request_access(fixture.runtime_request( + "Dolphin", + &["dolphin-emu"], + "request-runtime-1", + 0, + )) + .await + .unwrap() + .into_inner(); + assert_eq!(replay.outcome, MutationOutcome::Applied as i32); + assert_eq!(replay.runtime.unwrap().id, runtime.id); + assert_eq!(approver.requests.lock().unwrap().len(), 1); + + // A different key returns the valid owned runtime without prompting as well. + let reused = fixture + .client() + .runtimes_request_access(fixture.runtime_request( + "Dolphin", + &["dolphin-emu"], + "request-runtime-2", + 0, + )) + .await + .unwrap() + .into_inner(); + assert_eq!(reused.outcome, MutationOutcome::AlreadyApplied as i32); + assert_eq!(reused.runtime.unwrap().id, runtime.id); + assert_eq!(approver.requests.lock().unwrap().len(), 1); +} + +#[tokio::test] +async fn the_sdk_runtime_request_access_helper_sends_the_picker_request_without_a_handle() { + let fixture = Fixture::new(&[cap::GAME_RUNTIME_CREATE, cap::FILES_READ]).await; + let dir = fixture.game_dir("runtime", &[("dolphin-emu", b"binary")]); + let executable = executable_in(&dir, "dolphin-emu"); + fixture.with_host(); + let approver = fixture.runtime_approving(&executable); + let sdk = fixture.host.resources().unwrap(); + let spec = RuntimeSpec { + name: "Dolphin via SDK".into(), + version: "1.0".into(), + executable_handle: String::new(), + supported_formats: vec!["rom".into()], + platform: "linux".into(), + argument_template: vec![SdkArgument::Literal("--safe".into())], + extensions: Default::default(), + }; + let reply = sdk + .runtime_request_access( + spec, + RuntimeExecutableHints { + executable_names: vec!["dolphin-emu".into()], + desktop_ids: Vec::new(), + }, + 0, + "sdk-runtime-request", + ) + .await + .unwrap(); + assert_eq!(reply.outcome, MutationOutcome::Applied as i32); + assert!(reply.runtime.unwrap().executable_handle.is_empty()); + assert_eq!(approver.requests.lock().unwrap().len(), 1); + + let refused = sdk + .runtime_request_access( + RuntimeSpec { + name: "Bad".into(), + version: "1.0".into(), + executable_handle: "plugin-supplied-handle".into(), + supported_formats: vec!["rom".into()], + platform: "linux".into(), + argument_template: Vec::new(), + extensions: Default::default(), + }, + RuntimeExecutableHints::default(), + 0, + "sdk-runtime-handle", + ) + .await + .unwrap_err(); + assert_eq!(refused.code(), Code::InvalidArgument); + assert_eq!(approver.requests.lock().unwrap().len(), 1); +} + +#[tokio::test] +async fn an_unavailable_packagekit_inventory_still_offers_manual_browse() { + let fixture = Fixture::new(&[cap::GAME_RUNTIME_CREATE, cap::FILES_READ]).await; + let dir = fixture.game_dir("runtime", &[("dolphin-emu", b"binary")]); + let executable = executable_in(&dir, "dolphin-emu"); + let host = fixture.with_host(); + host.inventory_down.store(true, Ordering::SeqCst); + let approver = fixture.runtime_approving(&executable); + let reply = fixture + .client() + .runtimes_request_access(fixture.runtime_request( + "Dolphin", + &["dolphin-emu"], + "inventory-down", + 0, + )) + .await + .unwrap() + .into_inner(); + assert_eq!(reply.outcome, MutationOutcome::Applied as i32); + let requests = approver.requests.lock().unwrap().clone(); + assert_eq!(requests.len(), 1); + assert!(requests[0].candidates.is_empty()); +} + +#[tokio::test] +async fn a_declined_runtime_request_creates_no_runtime_or_approval() { + let fixture = Fixture::new(&[cap::GAME_RUNTIME_CREATE, cap::FILES_READ]).await; + let dir = fixture.game_dir("runtime", &[("dolphin-emu", b"binary")]); + let executable = executable_in(&dir, "dolphin-emu"); + fixture.with_host(); + let approver = fixture.runtime_approving(&executable); + approver.decline.store(true, Ordering::SeqCst); + let caller = fixture.caller(); + let owner = mutation_owner(&caller); + + let status = fixture + .client() + .runtimes_request_access(fixture.runtime_request( + "Dolphin", + &["dolphin-emu"], + "declined-runtime", + 0, + )) + .await + .unwrap_err(); + assert_eq!(status.code(), Code::PermissionDenied); + assert!( + fixture + .resource_api + .library + .host() + .unwrap() + .runtime_resources(owner) + .await + .unwrap() + .is_empty() + ); + assert!( + fixture + .resource_api + .in_namespace(&caller, |namespace| namespace.runtime_approvals()) + .await + .unwrap() + .is_empty() + ); +} + +#[tokio::test] +async fn a_changed_executable_refuses_launch_and_requires_fresh_approval() { + let fixture = Fixture::new(&[ + cap::GAME_RUNTIME_CREATE, + cap::GAME_RUNTIME_READ, + cap::FILES_READ, + ]) + .await; + let dir = fixture.game_dir("runtime", &[("dolphin-emu", b"binary")]); + let executable = executable_in(&dir, "dolphin-emu"); + fixture.with_host(); + let approver = fixture.runtime_approving(&executable); + let caller = fixture.caller(); + let runtime = fixture + .client() + .runtimes_request_access(fixture.runtime_request( + "Dolphin", + &["dolphin-emu"], + "first-approval", + 0, + )) + .await + .unwrap() + .into_inner() + .runtime + .unwrap(); + assert_eq!( + fixture + .resource_api + .resolve_runtime_executable(&caller, &runtime.id) + .await + .unwrap(), + executable.canonicalize().unwrap().to_str().unwrap() + ); + + std::fs::write(&executable, b"replaced binary").unwrap(); + let refused = fixture + .resource_api + .resolve_runtime_executable(&caller, &runtime.id) + .await + .unwrap_err(); + assert_eq!(refused.code(), Code::FailedPrecondition); + assert!(!refused.message().contains(dir.to_string_lossy().as_ref())); + + // The next request reapproves the same runtime; the user sees the picker again. + let reapproved = fixture + .client() + .runtimes_request_access(fixture.runtime_request( + "Dolphin", + &["dolphin-emu"], + "second-approval", + 1, + )) + .await + .unwrap() + .into_inner(); + assert_eq!(reapproved.outcome, MutationOutcome::Applied as i32); + let reapproved = reapproved.runtime.unwrap(); + assert_eq!(reapproved.id, runtime.id); + assert_eq!(reapproved.revision, runtime.revision + 1); + assert_eq!(approver.requests.lock().unwrap().len(), 2); + assert_eq!( + fixture + .resource_api + .resolve_runtime_executable(&caller, &reapproved.id) + .await + .unwrap(), + executable.canonicalize().unwrap().to_str().unwrap() + ); +} + +#[tokio::test] +async fn a_grant_revoked_or_profile_changed_while_the_picker_is_open_creates_nothing() { + for (permission, profile_change) in [(Some(cap::GAME_RUNTIME_CREATE), false), (None, true)] { + let fixture = Fixture::new(&[cap::GAME_RUNTIME_CREATE, cap::FILES_READ]).await; + let dir = fixture.game_dir("runtime", &[("dolphin-emu", b"binary")]); + let executable = executable_in(&dir, "dolphin-emu"); + fixture.with_host(); + let approver = fixture.runtime_approving(&executable); + *approver.race.lock().unwrap() = Some((fixture.api.clone(), permission)); + let caller = fixture.caller(); + let owner = mutation_owner(&caller); + let status = fixture + .client() + .runtimes_request_access(fixture.runtime_request( + "Dolphin", + &["dolphin-emu"], + if profile_change { + "changed-profile" + } else { + "revoked-grant" + }, + 0, + )) + .await + .unwrap_err(); + assert!( + matches!( + status.code(), + Code::PermissionDenied | Code::FailedPrecondition + ), + "{status:?}" + ); + assert!( + fixture + .resource_api + .library + .host() + .unwrap() + .runtime_resources(owner) + .await + .unwrap() + .is_empty() + ); + assert_eq!(approver.requests.lock().unwrap().len(), 1); + } +} diff --git a/crates/app/src/plugin_host/resources/tests/saves.rs b/crates/app/src/plugin_host/resources/tests/saves.rs new file mode 100644 index 000000000..5c0a2fb7a --- /dev/null +++ b/crates/app/src/plugin_host/resources/tests/saves.rs @@ -0,0 +1,1463 @@ +//! The `Saves` service over the real local socket (task 13.1): profiles that say where one +//! runtime keeps a game's saves, resting on folders the user already approved. + +use std::path::{Path, PathBuf}; + +use gamenode_platform::plugin_storage::SaveProfileRow; +use gamenode_plugin_protocol::prost_types::{Struct, Value, value::Kind}; + +use super::*; +use crate::plugin_host::saves::{ForeignGrant, ProfileGrants, access}; + +const GRANTS: &[&str] = &[ + cap::GAME_SAVES_READ, + cap::GAME_SAVES_CREATE, + cap::GAME_SAVES_UPDATE, + cap::GAME_SAVES_DELETE, + cap::FILES_READ, +]; +pub(super) const INSTALLATION: &str = "id-fixture:1"; + +impl Fixture { + pub(super) fn saves( + &self, + ) -> gamenode_plugin_protocol::proto::saves_client::SavesClient { + self.host.saves_client() + } + + /// A plugin with an emulator folder (`GC/USA/card.gci`, `states/s1.sav`) for one game entry + /// and another entry, and a user who approves whatever folder is set next. + pub(super) async fn emulator(grants: &[&'static str]) -> (Self, PathBuf) { + let fixture = Self::new(grants).await; + let saves = fixture.game_dir( + "dolphin-saves", + &[("GC/USA/card.gci", b"card"), ("states/s1.sav", b"state")], + ); + let rom = fixture.game_dir("rom", &[]); + let other = fixture.game_dir("other", &[]); + fixture.library_in(&[ + ("fixture:1", Some(3), "ROM", &rom), + ("fixture:2", Some(4), "Other", &other), + ("steam:1", Some(5), "Foreign", &other), + ]); + (fixture, saves) + } + + /// The root handle of a folder the user approves for `installation` as `kind`. + pub(super) async fn approve(&self, installation: &str, kind: &str, folder: &Path) -> String { + self.user_approving(folder); + self.request_access(installation, &["read"], &[kind]) + .await + .unwrap() + .handles + .remove(0) + .handle + } + + pub(super) async fn make( + &self, + key: &str, + profile: SaveProfile, + ) -> Result { + self.saves() + .create_profile(SaveProfileCreateRequest { + mutation: Some(self.mutation(key, 0)), + profile: Some(profile), + }) + .await + .map(Response::into_inner) + } + + pub(super) async fn profile(&self, id: &str) -> Result { + self.saves() + .get_profile(SaveProfileGetRequest { + context: Some(self.context()), + game_id: String::new(), + profile_id: id.into(), + shared_records: None, + }) + .await + .map(Response::into_inner) + } + + pub(super) async fn profiles( + &self, + installation: &str, + page_size: u32, + cursor: &str, + shared: Option, + ) -> Result { + self.saves() + .list_profiles(SaveProfileListRequest { + context: Some(self.context()), + game_id: String::new(), + installation_id: installation.into(), + cursor: cursor.into(), + page_size, + shared_records: shared, + }) + .await + .map(Response::into_inner) + } + + pub(super) async fn patch( + &self, + key: &str, + id: &str, + expected: u64, + mask: &[&str], + new: SaveProfile, + ) -> Result { + self.saves() + .update_profile(SaveProfileUpdateRequest { + mutation: Some(self.mutation(key, expected)), + profile_id: id.into(), + patch: Some(SaveProfilePatch { + field_mask: mask.iter().map(|path| (*path).into()).collect(), + profile: Some(new), + }), + }) + .await + .map(Response::into_inner) + } + + pub(super) async fn drop_profile( + &self, + key: &str, + id: &str, + expected: u64, + ) -> Result { + self.saves() + .remove_profile(SaveProfileRemoveRequest { + mutation: Some(self.mutation(key, expected)), + game_id: String::new(), + profile_id: id.into(), + }) + .await + .map(Response::into_inner) + } +} + +pub(super) fn directory(handle: &str, name: &str, patterns: &[&str]) -> SaveDirectory { + SaveDirectory { + approved_resource_handle: handle.into(), + display_name: name.into(), + naming_patterns: patterns.iter().map(|p| (*p).into()).collect(), + } +} + +pub(super) fn profile(name: &str, runtime: &str, directories: Vec) -> SaveProfile { + SaveProfile { + installation_id: INSTALLATION.into(), + name: name.into(), + runtime_id: runtime.into(), + directories, + ..SaveProfile::default() + } +} + +fn text(value: &str) -> Value { + Value { + kind: Some(Kind::StringValue(value.into())), + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_plugin_creates_and_reads_back_a_profile_that_rests_on_an_approved_folder() { + let (fixture, saves) = Fixture::emulator(GRANTS).await; + let root = fixture.approve(INSTALLATION, "save", &saves).await; + let mut new = profile( + " Dolphin card A ", + "org.dolphin-emu", + vec![directory( + &root, + "Memory card", + &["GC/**/*.gci", "!cache/**"], + )], + ); + new.format_id = "gci".into(); + new.format_version = 2; + new.descriptive_metadata = Some(Struct { + fields: [("region".to_owned(), text("USA"))].into(), + }); + let created = fixture.make("one", new).await.unwrap(); + assert_eq!(created.outcome, MutationOutcome::Applied as i32); + assert!(created.profile_id.starts_with("profile-")); + assert!(created.revision > 0); + + let read = fixture + .profile(&created.profile_id) + .await + .unwrap() + .profile + .unwrap(); + assert_eq!( + ( + read.name.as_str(), + read.game_id.as_str(), + read.installation_id.as_str(), + read.runtime_id.as_str(), + read.format_id.as_str(), + read.format_version, + read.creator_plugin_id.as_str(), + read.revision, + ), + ( + "Dolphin card A", + "3", + INSTALLATION, + "org.dolphin-emu", + "gci", + 2, + "fixture.plugin", + created.revision + ) + ); + assert_eq!( + read.descriptive_metadata.unwrap().fields["region"], + text("USA") + ); + let [folder] = read.directories.try_into().unwrap(); + assert_eq!(folder.display_name, "Memory card"); + assert_eq!(folder.naming_patterns, ["GC/**/*.gci", "!cache/**"]); + // The folder comes back as a handle of this session, which works like the one it came from. + let listed = fixture.ls(&folder.approved_resource_handle).await.unwrap(); + assert_eq!(names(&listed), ["GC", "states"]); + + let all = fixture.profiles("", 0, "", None).await.unwrap(); + assert_eq!(all.profiles.len(), 1); + assert_eq!(all.revision, created.revision); +} + +fn names(reply: &FilesListReply) -> Vec<&str> { + reply + .entries + .iter() + .map(|entry| entry.name.as_str()) + .collect() +} + +#[tokio::test(flavor = "multi_thread")] +async fn one_rom_can_have_distinct_save_folders_for_distinct_runtimes() { + let (fixture, dolphin) = Fixture::emulator(GRANTS).await; + let other_emulator = fixture.game_dir("other-emulator", &[("slot1.sav", b"s")]); + let first = fixture.approve(INSTALLATION, "save", &dolphin).await; + let second = fixture + .approve(INSTALLATION, "prefix", &other_emulator) + .await; + + let a = fixture + .make( + "a", + profile("Dolphin", "dolphin", vec![directory(&first, "", &[])]), + ) + .await + .unwrap(); + let b = fixture + .make( + "b", + profile("Other emulator", "other", vec![directory(&second, "", &[])]), + ) + .await + .unwrap(); + assert_ne!(a.profile_id, b.profile_id); + assert!(b.revision > a.revision, "one counter, never repeated"); + + let both = fixture.profiles(INSTALLATION, 0, "", None).await.unwrap(); + let runtimes: Vec<_> = both + .profiles + .iter() + .map(|p| p.runtime_id.as_str()) + .collect(); + assert_eq!(runtimes.len(), 2); + assert!(runtimes.contains(&"dolphin") && runtimes.contains(&"other")); + // Another game entry has none. + assert!( + fixture + .profiles("id-fixture:2", 0, "", None) + .await + .unwrap() + .profiles + .is_empty() + ); + + // The name is unique per game entry, without regard to case; another entry may reuse it. + let again = fixture + .make( + "c", + profile("DOLPHIN", "dolphin", vec![directory(&first, "", &[])]), + ) + .await + .unwrap_err(); + assert_eq!(again.code(), Code::AlreadyExists); +} + +#[tokio::test(flavor = "multi_thread")] +async fn lists_are_paged_in_a_stable_order() { + let (fixture, saves) = Fixture::emulator(GRANTS).await; + let root = fixture.approve(INSTALLATION, "save", &saves).await; + let mut ids = Vec::new(); + for n in 0..5 { + let created = fixture + .make( + &format!("k{n}"), + profile( + &format!("Profile {n}"), + "rt", + vec![directory(&root, "", &[])], + ), + ) + .await + .unwrap(); + ids.push(created.profile_id); + } + let mut seen = Vec::new(); + let mut cursor = String::new(); + loop { + let page = fixture.profiles("", 2, &cursor, None).await.unwrap(); + assert!(page.profiles.len() <= 2); + seen.extend(page.profiles.iter().map(|p| p.profile_id.clone())); + if page.next_cursor.is_empty() { + break; + } + cursor = page.next_cursor; + } + let mut sorted = ids.clone(); + sorted.sort(); + seen.sort(); + assert_eq!(seen, sorted, "every profile once"); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_profile_reaches_only_folders_approved_for_its_own_game_entry() { + let (fixture, saves) = Fixture::emulator(GRANTS).await; + let mine = fixture.approve(INSTALLATION, "save", &saves).await; + let elsewhere = fixture.game_dir("elsewhere", &[]); + let theirs = fixture.approve("id-fixture:2", "save", &elsewhere).await; + + // A folder approved for another game entry is not this one's. + let refused = fixture + .make("a", profile("P", "rt", vec![directory(&theirs, "", &[])])) + .await + .unwrap_err(); + assert_eq!(refused.code(), Code::PermissionDenied); + // A forged, edited or path-like handle is just not found. + for handle in ["forged", "", "/etc", &format!("{mine}x")] { + let refused = fixture + .make("b", profile("P", "rt", vec![directory(handle, "", &[])])) + .await + .unwrap_err(); + assert_eq!(refused.code(), Code::NotFound, "{handle:?}"); + } + // The same folder twice, and no folder at all. + assert_eq!( + fixture + .make( + "c", + profile( + "P", + "rt", + vec![directory(&mine, "", &[]), directory(&mine, "", &[])] + ) + ) + .await + .unwrap_err() + .code(), + Code::InvalidArgument + ); + assert_eq!( + fixture + .make("d", profile("P", "rt", vec![])) + .await + .unwrap_err() + .code(), + Code::InvalidArgument + ); + // A folder below the approved one is fine, and so is the same folder with other rules. + let below = fixture.ls(&mine).await.unwrap(); + let states = below + .entries + .iter() + .find(|entry| entry.name == "states") + .unwrap(); + let created = fixture + .make( + "e", + profile( + "States", + "rt", + vec![ + directory(&states.handle, "States", &["*.sav"]), + directory(&mine, "All", &[]), + ], + ), + ) + .await + .unwrap(); + assert_eq!(created.outcome, MutationOutcome::Applied as i32); + assert!( + fixture + .profiles("", 0, "", None) + .await + .unwrap() + .profiles + .len() + == 1 + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_revoked_approval_leaves_the_profile_with_no_reachable_folder() { + let (fixture, saves) = Fixture::emulator(GRANTS).await; + let root = fixture.approve(INSTALLATION, "save", &saves).await; + let created = fixture + .make( + "a", + profile("P", "rt", vec![directory(&root, "Card", &["*.gci"])]), + ) + .await + .unwrap(); + + // The user takes the folder approval back. + let caller = fixture.caller(); + let approval = fixture + .storage + .run_for_host( + caller.namespace.as_ref().unwrap(), + caller.profile_epoch, + |namespace| { + let id = namespace + .approval_for(INSTALLATION, "save")? + .expect("the folder was approved") + .id; + namespace.revoke_approval(&id) + }, + ) + .await + .unwrap(); + assert!(approval); + + let read = fixture + .profile(&created.profile_id) + .await + .unwrap() + .profile + .unwrap(); + let [folder] = read.directories.try_into().unwrap(); + // The profile and its rules remain; the folder is simply not reachable any more. + assert_eq!(folder.approved_resource_handle, ""); + assert_eq!( + (folder.display_name.as_str(), folder.naming_patterns.len()), + ("Card", 1) + ); + // A new profile cannot rest on it either. + assert_eq!( + fixture + .make("b", profile("Q", "rt", vec![directory(&root, "", &[])])) + .await + .unwrap_err() + .code(), + Code::NotFound + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn configuring_a_profile_authorizes_no_file_access() { + let (fixture, saves) = Fixture::emulator(GRANTS).await; + let root = fixture.approve(INSTALLATION, "save", &saves).await; + let created = fixture + .make("a", profile("P", "rt", vec![directory(&root, "", &[])])) + .await + .unwrap(); + let read = fixture.profile(&created.profile_id).await.unwrap(); + // The reply carries no path of the user's computer. + let shown = format!("{read:?}"); + assert!(!shown.contains(saves.to_str().unwrap()) && !shown.contains("dolphin-saves")); + + // The handle in it is worth only what files.read is: lose that and it opens nothing, though the + // profile is still readable. + let handle = read.profile.unwrap().directories[0] + .approved_resource_handle + .clone(); + fixture + .api + .revoke_session_permission("fixture", cap::FILES_READ) + .await; + assert_eq!( + fixture.ls(&handle).await.unwrap_err().code(), + Code::PermissionDenied + ); + assert!(fixture.profile(&created.profile_id).await.is_ok()); +} + +#[tokio::test(flavor = "multi_thread")] +async fn what_a_plugin_may_not_set_or_send_is_refused() { + let (fixture, saves) = Fixture::emulator(GRANTS).await; + let root = fixture.approve(INSTALLATION, "save", &saves).await; + let dirs = || vec![directory(&root, "", &[])]; + let good = || profile("P", "rt", dirs()); + let code = |result: Result| result.unwrap_err().code(); + + // The host's fields are the host's. + let mut with_id = good(); + with_id.profile_id = "mine".into(); + assert_eq!( + code(fixture.make("a", with_id).await), + Code::InvalidArgument + ); + let mut with_creator = good(); + with_creator.creator_plugin_id = "someone.else".into(); + assert_eq!( + code(fixture.make("b", with_creator).await), + Code::InvalidArgument + ); + let mut with_revision = good(); + with_revision.revision = 4; + assert_eq!( + code(fixture.make("c", with_revision).await), + Code::InvalidArgument + ); + // A create is revision 0. + let stale = fixture + .saves() + .create_profile(SaveProfileCreateRequest { + mutation: Some(fixture.mutation("d", 5)), + profile: Some(good()), + }) + .await + .unwrap_err(); + assert_eq!(stale.code(), Code::InvalidArgument); + + // Names, ids, rules and metadata. + for bad in [ + profile("", "rt", dirs()), + profile(&"x".repeat(121), "rt", dirs()), + profile("line\nbreak", "rt", dirs()), + profile("P", "has space", dirs()), + profile("P", &"x".repeat(129), dirs()), + profile("P", "rt", vec![directory(&root, "", &["/etc/passwd"])]), + profile("P", "rt", vec![directory(&root, "", &["../up"])]), + profile("P", "rt", vec![directory(&root, "", &["a", "a"])]), + profile("P", "rt", vec![directory(&root, "bad\nname", &[])]), + ] { + assert_eq!(code(fixture.make("x", bad).await), Code::InvalidArgument); + } + let mut huge = good(); + huge.descriptive_metadata = Some(Struct { + fields: [("k".to_owned(), text(&"y".repeat(9000)))].into(), + }); + assert_eq!(code(fixture.make("y", huge).await), Code::InvalidArgument); + // Too many folders. + let many: Vec<_> = (0..9).map(|_| directory(&root, "", &[])).collect(); + assert_eq!( + code(fixture.make("z", profile("P", "rt", many)).await), + Code::InvalidArgument + ); + + // The entry must be this plugin's own: another provider's is not found, nor is an unknown one. + for installation in ["id-steam:1", "id-nothing"] { + let mut foreign = good(); + foreign.installation_id = installation.into(); + assert_eq!(code(fixture.make("w", foreign).await), Code::NotFound); + } + let mut wrong_game = good(); + wrong_game.game_id = "999".into(); + assert_eq!(code(fixture.make("v", wrong_game).await), Code::NotFound); + // Nothing of that was kept. + assert!( + fixture + .profiles("", 0, "", None) + .await + .unwrap() + .profiles + .is_empty() + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_profile_is_updated_by_revision_and_field_mask() { + let (fixture, saves) = Fixture::emulator(GRANTS).await; + let root = fixture.approve(INSTALLATION, "save", &saves).await; + let created = fixture + .make( + "a", + profile("Card", "rt", vec![directory(&root, "Root", &["*.gci"])]), + ) + .await + .unwrap(); + + let renamed = fixture + .patch( + "u1", + &created.profile_id, + created.revision, + &["name", "format_id", "format_version"], + SaveProfile { + name: "Card B".into(), + format_id: "gci".into(), + format_version: 3, + // Not in the mask, so ignored. + runtime_id: "ignored".into(), + ..SaveProfile::default() + }, + ) + .await + .unwrap(); + assert_eq!(renamed.outcome, MutationOutcome::Applied as i32); + assert!(renamed.revision > created.revision); + let read = fixture + .profile(&created.profile_id) + .await + .unwrap() + .profile + .unwrap(); + assert_eq!( + ( + read.name.as_str(), + read.runtime_id.as_str(), + read.format_id.as_str(), + read.format_version + ), + ("Card B", "rt", "gci", 3) + ); + // The folders were not in the mask: they are as they were. + assert_eq!(read.directories[0].naming_patterns, ["*.gci"]); + + // A stale revision changes nothing and says where the profile is. + let stale = fixture + .patch( + "u2", + &created.profile_id, + created.revision, + &["name"], + SaveProfile { + name: "Lost".into(), + ..SaveProfile::default() + }, + ) + .await + .unwrap(); + assert_eq!( + (stale.outcome, stale.revision), + (MutationOutcome::RevisionConflict as i32, renamed.revision) + ); + assert_eq!( + fixture + .profile(&created.profile_id) + .await + .unwrap() + .profile + .unwrap() + .name, + "Card B" + ); + + // New folders and rules replace the old ones, through handles of this session. + let moved = fixture + .patch( + "u3", + &created.profile_id, + renamed.revision, + &["directories", "descriptive_metadata"], + SaveProfile { + directories: vec![directory(&root, "Everything", &["**", "!*.tmp"])], + descriptive_metadata: Some(Struct { + fields: [("core".to_owned(), text("gc"))].into(), + }), + ..SaveProfile::default() + }, + ) + .await + .unwrap(); + let read = fixture + .profile(&created.profile_id) + .await + .unwrap() + .profile + .unwrap(); + assert_eq!(read.directories[0].naming_patterns, ["**", "!*.tmp"]); + assert_eq!(read.revision, moved.revision); + + // What may not be changed, and what is malformed. + for (mask, expected) in [ + (&["profile_id"][..], moved.revision), + (&["installation_id"], moved.revision), + (&["game_id"], moved.revision), + (&["creator_plugin_id"], moved.revision), + (&["revision"], moved.revision), + (&[], moved.revision), + (&["name"], 0), + ] { + let refused = fixture + .patch( + "bad", + &created.profile_id, + expected, + mask, + SaveProfile::default(), + ) + .await + .unwrap_err(); + assert_eq!( + refused.code(), + Code::InvalidArgument, + "{mask:?} at {expected}" + ); + } + // A profile that is not there, and a name another profile of the entry already has. + assert_eq!( + fixture + .patch( + "n", + "profile-nothing", + 1, + &["name"], + SaveProfile { + name: "x".into(), + ..SaveProfile::default() + } + ) + .await + .unwrap_err() + .code(), + Code::NotFound + ); + let other = fixture + .make( + "o", + profile("Second", "rt", vec![directory(&root, "", &[])]), + ) + .await + .unwrap(); + let taken = fixture + .patch( + "t", + &other.profile_id, + other.revision, + &["name"], + SaveProfile { + name: "card b".into(), + ..SaveProfile::default() + }, + ) + .await + .unwrap_err(); + assert_eq!(taken.code(), Code::AlreadyExists); +} + +#[tokio::test(flavor = "multi_thread")] +async fn removing_a_profile_touches_no_file_and_never_repeats_a_revision() { + let (fixture, saves) = Fixture::emulator(GRANTS).await; + let root = fixture.approve(INSTALLATION, "save", &saves).await; + let created = fixture + .make("a", profile("Card", "rt", vec![directory(&root, "", &[])])) + .await + .unwrap(); + + // A stale revision removes nothing. + let stale = fixture + .drop_profile("r0", &created.profile_id, created.revision + 9) + .await + .unwrap(); + assert_eq!( + (stale.outcome, stale.revision), + (MutationOutcome::RevisionConflict as i32, created.revision) + ); + assert!(fixture.profile(&created.profile_id).await.is_ok()); + // Revision 0 is not a revision to remove at. + assert_eq!( + fixture + .drop_profile("r1", &created.profile_id, 0) + .await + .unwrap_err() + .code(), + Code::InvalidArgument + ); + + let removed = fixture + .drop_profile("r2", &created.profile_id, created.revision) + .await + .unwrap(); + assert_eq!(removed.outcome, MutationOutcome::Applied as i32); + assert_eq!( + fixture + .profile(&created.profile_id) + .await + .unwrap_err() + .code(), + Code::NotFound + ); + // The folder and what is in it are exactly where the user keeps them. + assert_eq!( + std::fs::read(saves.join("GC/USA/card.gci")).unwrap(), + b"card" + ); + assert_eq!( + std::fs::read(saves.join("states/s1.sav")).unwrap(), + b"state" + ); + // Removing again is not found; a profile made afterwards gets a higher revision than the removal. + assert_eq!( + fixture + .drop_profile("r3", &created.profile_id, removed.revision) + .await + .unwrap_err() + .code(), + Code::NotFound + ); + let again = fixture + .make("b", profile("Card", "rt", vec![directory(&root, "", &[])])) + .await + .unwrap(); + assert!(again.revision > removed.revision); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_retry_returns_the_original_outcome_and_a_reused_key_is_refused() { + let (fixture, saves) = Fixture::emulator(GRANTS).await; + let root = fixture.approve(INSTALLATION, "save", &saves).await; + let same = || profile("Card", "rt", vec![directory(&root, "", &[])]); + let first = fixture.make("key", same()).await.unwrap(); + let retry = fixture.make("key", same()).await.unwrap(); + assert_eq!( + (&retry.profile_id, retry.revision, retry.outcome), + (&first.profile_id, first.revision, first.outcome) + ); + assert_eq!( + fixture + .profiles("", 0, "", None) + .await + .unwrap() + .profiles + .len(), + 1 + ); + // The same key for another request is refused. + let other = fixture + .make( + "key", + profile("Different", "rt", vec![directory(&root, "", &[])]), + ) + .await + .unwrap_err(); + assert_eq!(other.code(), Code::FailedPrecondition); + + // Updates and removals are retried the same way. + let patch = || { + fixture.patch( + "u", + &first.profile_id, + first.revision, + &["name"], + SaveProfile { + name: "Renamed".into(), + ..SaveProfile::default() + }, + ) + }; + let one = patch().await.unwrap(); + let two = patch().await.unwrap(); + assert_eq!((one.revision, one.outcome), (two.revision, two.outcome)); + let gone = fixture + .drop_profile("d", &first.profile_id, one.revision) + .await + .unwrap(); + let again = fixture + .drop_profile("d", &first.profile_id, one.revision) + .await + .unwrap(); + assert_eq!(gone.revision, again.revision); +} + +#[tokio::test(flavor = "multi_thread")] +async fn the_four_permissions_are_independent_and_checked_at_the_commit() { + // Read only: nothing can be changed. + let (reader, saves) = Fixture::emulator(&[cap::GAME_SAVES_READ, cap::FILES_READ]).await; + let root = reader.approve(INSTALLATION, "save", &saves).await; + let denied = reader + .make("a", profile("P", "rt", vec![directory(&root, "", &[])])) + .await + .unwrap_err(); + assert_eq!(denied.code(), Code::PermissionDenied); + assert!( + reader + .profiles("", 0, "", None) + .await + .unwrap() + .profiles + .is_empty() + ); + + // Create without read: it can be made but not looked at. + let (maker, saves) = Fixture::emulator(&[cap::GAME_SAVES_CREATE, cap::FILES_READ]).await; + let root = maker.approve(INSTALLATION, "save", &saves).await; + let created = maker + .make("a", profile("P", "rt", vec![directory(&root, "", &[])])) + .await + .unwrap(); + assert_eq!( + maker.profile(&created.profile_id).await.unwrap_err().code(), + Code::PermissionDenied + ); + assert_eq!( + maker.profiles("", 0, "", None).await.unwrap_err().code(), + Code::PermissionDenied + ); + assert_eq!( + maker + .patch( + "u", + &created.profile_id, + created.revision, + &["name"], + SaveProfile::default() + ) + .await + .unwrap_err() + .code(), + Code::PermissionDenied + ); + assert_eq!( + maker + .drop_profile("d", &created.profile_id, created.revision) + .await + .unwrap_err() + .code(), + Code::PermissionDenied + ); + + // Losing the permission ends it for good, and a retry of a committed write is still answered. + maker + .api + .revoke_session_permission("fixture", cap::GAME_SAVES_CREATE) + .await; + let after = maker + .make("b", profile("Q", "rt", vec![directory(&root, "", &[])])) + .await + .unwrap_err(); + assert_eq!(after.code(), Code::PermissionDenied); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_forged_context_and_a_missing_request_part_are_refused() { + let (fixture, saves) = Fixture::emulator(GRANTS).await; + let root = fixture.approve(INSTALLATION, "save", &saves).await; + let mut forged = fixture.context(); + forged.session_credential = vec![0; forged.session_credential.len()]; + let denied = fixture + .saves() + .list_profiles(SaveProfileListRequest { + context: Some(forged), + ..SaveProfileListRequest::default() + }) + .await + .unwrap_err(); + assert_eq!(denied.code(), Code::PermissionDenied); + let none = fixture + .saves() + .list_profiles(SaveProfileListRequest::default()) + .await + .unwrap_err(); + assert_eq!(none.code(), Code::Unauthenticated); + assert_eq!( + fixture + .saves() + .create_profile(SaveProfileCreateRequest { + mutation: None, + profile: Some(profile("P", "rt", vec![directory(&root, "", &[])])), + }) + .await + .unwrap_err() + .code(), + Code::InvalidArgument + ); + // Common-data categories are not served for profiles. + let categories = fixture + .profiles( + "", + 0, + "", + Some(CommonDataSelector { + categories: vec![CommonDataCategory::GamePerformanceHistory as i32], + selected_record_ids: vec![], + }), + ) + .await + .unwrap_err(); + assert_eq!(categories.code(), Code::Unimplemented); +} + +#[tokio::test(flavor = "multi_thread")] +async fn profiles_belong_to_the_account_profile_and_survive_a_restart() { + let (mut fixture, saves) = Fixture::emulator(GRANTS).await; + let root = fixture.approve(INSTALLATION, "save", &saves).await; + let created = fixture + .make("a", profile("Card", "rt", vec![directory(&root, "", &[])])) + .await + .unwrap(); + + // The plugin restarts in the same account: its profile is there, and its folder is reachable + // again through a handle of the new session. + fixture.reconnect().await; + let read = fixture + .profile(&created.profile_id) + .await + .unwrap() + .profile + .unwrap(); + let handle = &read.directories[0].approved_resource_handle; + assert!(!handle.is_empty()); + assert!(fixture.ls(handle).await.is_ok()); + + // Another account signs in and sees none of it. + fixture.api.profiles().update(Some("b"), true); + fixture.api.fence_third_party_sessions().await; + fixture.reconnect().await; + assert!( + fixture + .profiles("", 0, "", None) + .await + .unwrap() + .profiles + .is_empty() + ); + assert_eq!( + fixture + .profile(&created.profile_id) + .await + .unwrap_err() + .code(), + Code::NotFound + ); + + // Back in the first account the profile is where it was, with its revision. + fixture.api.profiles().update(Some("a"), true); + fixture.api.fence_third_party_sessions().await; + fixture.reconnect().await; + let back = fixture + .profile(&created.profile_id) + .await + .unwrap() + .profile + .unwrap(); + assert_eq!(back.revision, created.revision); +} + +#[tokio::test(flavor = "multi_thread")] +async fn shared_resource_declarations_are_resolved_and_require_current_consent() { + let fixture = Fixture::new(GRANTS).await; + let shared = fixture.game_dir("shared", &[("one/rom", b"one"), ("two/rom", b"two")]); + fixture.library_in(&[ + ("fixture:card-a", Some(3), "Card A", &shared.join("one")), + ("fixture:card-b", Some(4), "Card B", &shared.join("two")), + ]); + let installation = "id-fixture:card-a"; + let root = fixture.approve(installation, "save", &shared).await; + let mut new = profile("Shared card", "rt", vec![directory(&root, "", &["*.sav"])]); + new.installation_id = installation.into(); + new.shared_resources = vec![SharedResourceDeclaration { + resource_id: "memory-card".into(), + approved_resource_handle: root.clone(), + display_name: "Memory card".into(), + consent: 0, + }]; + let created = fixture.make("shared", new).await.unwrap(); + let read = fixture + .profile(&created.profile_id) + .await + .unwrap() + .profile + .unwrap(); + assert_eq!(read.shared_resources.len(), 1); + assert_eq!(read.shared_resources[0].resource_id, "memory-card"); + assert!(!read.shared_resources[0].approved_resource_handle.is_empty()); + assert_eq!( + read.shared_resources[0].consent, + SharedResourceConsent::Pending as i32 + ); + + let publisher = "ab".repeat(32); + let reviews = crate::plugin_host::shared_resources::PluginSharedResources::new( + fixture.storage.clone(), + fixture.api.profiles(), + fixture.files.clone(), + fixture.feed.clone(), + ); + let pending = reviews.list("fixture.plugin", &publisher).await.unwrap(); + assert_eq!(pending.len(), 1); + assert_eq!(pending[0].consent, "pending"); + assert_eq!(pending[0].affected_games.len(), 2); + assert!( + reviews + .prepared("fixture.plugin", &publisher, &created.profile_id) + .await + .is_err() + ); + + reviews + .accept( + "fixture.plugin", + &publisher, + &created.profile_id, + "memory-card", + ) + .await + .unwrap(); + let prepared = reviews + .prepared("fixture.plugin", &publisher, &created.profile_id) + .await + .unwrap(); + assert_eq!(prepared.len(), 1); + assert_eq!(prepared[0].scope.len(), 2); + assert_eq!( + reviews.list("fixture.plugin", &publisher).await.unwrap()[0].consent, + "current" + ); + + // A display-name edit takes a profile revision but does not invalidate the reviewed scope. + fixture + .patch( + "rename", + &created.profile_id, + created.revision, + &["name"], + SaveProfile { + name: "Renamed card".into(), + ..Default::default() + }, + ) + .await + .unwrap(); + assert_eq!( + reviews + .prepared("fixture.plugin", &publisher, &created.profile_id) + .await + .unwrap() + .len(), + 1 + ); + + // A changed runtime binding needs an explicit re-declaration. + let runtime_changed = fixture + .patch( + "runtime", + &created.profile_id, + created.revision + 1, + &["runtime_id"], + SaveProfile { + runtime_id: "other-runtime".into(), + ..Default::default() + }, + ) + .await + .unwrap_err(); + assert_eq!(runtime_changed.code(), Code::FailedPrecondition); + + // A newly affected game makes the old consent stale and blocks use until it is reviewed. + let three = fixture.game_dir("shared", &[("three/rom", b"three")]); + fixture.library_in(&[ + ("fixture:card-a", Some(3), "Card A", &shared.join("one")), + ("fixture:card-b", Some(4), "Card B", &shared.join("two")), + ("fixture:card-c", Some(5), "Card C", &three.join("three")), + ]); + let stale = reviews.list("fixture.plugin", &publisher).await.unwrap(); + assert_eq!(stale[0].consent, "stale"); + assert!(stale[0].unavailable); + let refused = reviews + .prepared("fixture.plugin", &publisher, &created.profile_id) + .await + .unwrap_err(); + assert!(refused.contains("changed") || refused.contains("review")); +} + +#[tokio::test(flavor = "multi_thread")] +async fn duplicate_shared_resource_aliases_are_refused() { + let fixture = Fixture::new(GRANTS).await; + let shared = fixture.game_dir("shared", &[("one/rom", b"one")]); + fixture.library_in(&[("fixture:card-a", Some(3), "Card A", &shared.join("one"))]); + let installation = "id-fixture:card-a"; + let root = fixture.approve(installation, "save", &shared).await; + let mut new = profile("Card", "rt", vec![directory(&root, "", &["*.sav"])]); + new.installation_id = installation.into(); + new.shared_resources = vec![ + SharedResourceDeclaration { + resource_id: "memory-card".into(), + approved_resource_handle: root.clone(), + display_name: "Memory card".into(), + consent: 0, + }, + SharedResourceDeclaration { + resource_id: "memory-card".into(), + approved_resource_handle: root, + display_name: "Same alias".into(), + consent: 0, + }, + ]; + assert_eq!( + fixture.make("duplicate", new).await.unwrap_err().code(), + Code::InvalidArgument + ); +} + +struct Granted(Vec); + +impl ProfileGrants for Granted { + fn grants(&self, plugin_id: &str, publisher: &str) -> Vec { + assert_eq!(plugin_id, "fixture.plugin"); + assert_eq!(publisher, "ab".repeat(32)); + self.0.clone() + } +} + +impl Fixture { + /// A profile another plugin ("org.maker") contributed, written into its own store. + async fn makers_profile(&self) -> SaveProfileRow { + let profiles = self.api.profiles(); + let resolver = profiles.resolver("org.maker", "cd", None).unwrap(); + let row = SaveProfileRow { + id: "profile-maker".into(), + installation_id: "maker-installation".into(), + game_id: "9".into(), + name: "Maker card".into(), + runtime_id: "maker-runtime".into(), + format_id: String::new(), + format_version: 0, + metadata: "{}".into(), + directories: crate::plugin_host::saves::directories_json(&[ + crate::plugin_host::saves::Directory { + approval_id: "makers-approval".into(), + path: vec![], + display_name: "Maker folder".into(), + naming_patterns: vec!["*.sav".into()], + }, + ]), + shared_resources: "[]".into(), + revision: 0, + created_at: 0, + }; + let stored = row.clone(); + self.storage + .run_for_host(&resolver, profiles.epoch(), move |namespace| { + let guard: crate::plugin_host::library::CommitGuard = Box::new(|| Ok(())); + namespace.put_save_profile(stored, 0, &guard) + }) + .await + .unwrap(); + row + } + + async fn makers_row(&self) -> Option { + let profiles = self.api.profiles(); + let resolver = profiles.resolver("org.maker", "cd", None).unwrap(); + self.storage + .run_for_host(&resolver, profiles.epoch(), |namespace| { + namespace.save_profile("profile-maker") + }) + .await + .unwrap() + } + + fn grant_makers_profile(&self, operations: u8) { + self.saves.set_grants(Arc::new(Granted(vec![ForeignGrant { + creator_plugin_id: "org.maker".into(), + creator_publisher: "cd".into(), + profile_id: "profile-maker".into(), + operations, + }]))); + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn another_plugins_profile_is_reached_only_through_an_explicit_grant_and_keeps_its_provenance() + { + let (fixture, _) = Fixture::emulator(GRANTS).await; + let row = fixture.makers_profile().await; + + // No grant: it is not there for this plugin, in any operation. + assert_eq!( + fixture.profile(&row.id).await.unwrap_err().code(), + Code::NotFound + ); + assert_eq!( + fixture + .patch( + "u", + &row.id, + 1, + &["name"], + SaveProfile { + name: "x".into(), + ..SaveProfile::default() + } + ) + .await + .unwrap_err() + .code(), + Code::NotFound + ); + assert_eq!( + fixture + .drop_profile("d", &row.id, 1) + .await + .unwrap_err() + .code(), + Code::NotFound + ); + + // Read granted: it can be read, with the creator named and no handle to its folders. + fixture.grant_makers_profile(access::READ); + let read = fixture.profile(&row.id).await.unwrap().profile.unwrap(); + assert_eq!( + ( + read.creator_plugin_id.as_str(), + read.name.as_str(), + read.game_id.as_str() + ), + ("org.maker", "Maker card", "9") + ); + assert_eq!(read.directories[0].approved_resource_handle, ""); + assert_eq!(read.directories[0].display_name, "Maker folder"); + // It is listed only when named; another profile of the maker is not reachable by this grant. + assert!( + fixture + .profiles("", 0, "", None) + .await + .unwrap() + .profiles + .is_empty() + ); + let named = fixture + .profiles( + "", + 0, + "", + Some(CommonDataSelector { + categories: vec![], + selected_record_ids: vec![row.id.clone(), "profile-other".into()], + }), + ) + .await + .unwrap(); + assert_eq!(named.profiles.len(), 1); + // Read does not mean update or remove. + assert_eq!( + fixture + .patch( + "u", + &row.id, + 1, + &["name"], + SaveProfile { + name: "x".into(), + ..SaveProfile::default() + } + ) + .await + .unwrap_err() + .code(), + Code::NotFound + ); + assert_eq!( + fixture + .drop_profile("d", &row.id, 1) + .await + .unwrap_err() + .code(), + Code::NotFound + ); + + // Update granted: the name may change, the creator's folders may not. + fixture.grant_makers_profile(access::READ | access::UPDATE); + let revision = read.revision; + let denied = fixture + .patch( + "dirs", + &row.id, + revision, + &["directories"], + SaveProfile { + directories: vec![directory("anything", "", &[])], + ..SaveProfile::default() + }, + ) + .await + .unwrap_err(); + assert_eq!(denied.code(), Code::PermissionDenied); + let renamed = fixture + .patch( + "name", + &row.id, + revision, + &["name"], + SaveProfile { + name: "Edited by reader".into(), + ..SaveProfile::default() + }, + ) + .await + .unwrap(); + assert_eq!(renamed.outcome, MutationOutcome::Applied as i32); + let stored = fixture.makers_row().await.unwrap(); + assert_eq!( + (stored.name.as_str(), stored.revision), + ("Edited by reader", renamed.revision) + ); + // The provenance and the folders are the creator's, unchanged. + assert_eq!(stored.directories, row.directories); + let again = fixture.profile(&row.id).await.unwrap().profile.unwrap(); + assert_eq!(again.creator_plugin_id, "org.maker"); + + // Delete granted: it can be removed, and then it is gone for the creator too. + fixture.grant_makers_profile(access::DELETE); + let removed = fixture + .drop_profile("rm", &row.id, renamed.revision) + .await + .unwrap(); + assert_eq!(removed.outcome, MutationOutcome::Applied as i32); + assert!(fixture.makers_row().await.is_none()); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_grant_the_user_takes_back_ends_the_access() { + let (fixture, _) = Fixture::emulator(GRANTS).await; + let row = fixture.makers_profile().await; + fixture.grant_makers_profile(access::READ); + assert!(fixture.profile(&row.id).await.is_ok()); + fixture.saves.set_grants(Arc::new(Granted(vec![]))); + assert_eq!( + fixture.profile(&row.id).await.unwrap_err().code(), + Code::NotFound + ); + // And the profile's own permission still matters: without game.saves.read the grant is idle. + fixture.grant_makers_profile(access::READ); + fixture + .api + .revoke_session_permission("fixture", cap::GAME_SAVES_READ) + .await; + assert_eq!( + fixture.profile(&row.id).await.unwrap_err().code(), + Code::PermissionDenied + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn describe_api_lists_the_saves_methods_with_their_own_permissions() { + let (fixture, _) = Fixture::emulator(GRANTS).await; + let described = fixture.host.describe_api().await.unwrap(); + let saves: Vec<_> = described + .methods + .iter() + .filter(|method| method.service == "Saves") + .map(|method| (method.method.as_str(), method.permissions.clone())) + .collect(); + assert_eq!( + saves, + [ + ("ListProfiles", vec![cap::GAME_SAVES_READ.to_owned()]), + ("GetProfile", vec![cap::GAME_SAVES_READ.to_owned()]), + ("CreateProfile", vec![cap::GAME_SAVES_CREATE.to_owned()]), + ("UpdateProfile", vec![cap::GAME_SAVES_UPDATE.to_owned()]), + ("RemoveProfile", vec![cap::GAME_SAVES_DELETE.to_owned()]), + ] + ); +} diff --git a/crates/app/src/plugin_host/resources/tests/sdk.rs b/crates/app/src/plugin_host/resources/tests/sdk.rs new file mode 100644 index 000000000..a72302902 --- /dev/null +++ b/crates/app/src/plugin_host/resources/tests/sdk.rs @@ -0,0 +1,1070 @@ +//! The SDK's resource helpers against the same fixture host as the raw gRPC tests: every call +//! is made through the SDK and again by hand, and the answers must be the same. A write is +//! compared by replaying it raw under the SDK's idempotency key: the host only returns the +//! original outcome for a request that is identical, so a match proves the SDK sent exactly what +//! the hand-written call sends. + +use super::*; +use gamenode_platform::plugin_shared_data::SharedDataStore; +use gamenode_plugin_sdk::{Outcome, Resources, Written, idempotency_key, prost_types}; + +const OWN_AND_MORE: &[&str] = &[ + cap::LIBRARY_READ, + cap::LIBRARY_METADATA_WRITE, + cap::FAVORITES_READ, + cap::FAVORITES_WRITE, + cap::MATCHING_READ, + cap::MATCHING_WRITE, + cap::ARTWORK_READ, + cap::ARTWORK_WRITE, +]; + +async fn ready() -> (Fixture, Resources, Arc) { + let fixture = Fixture::new(OWN_AND_MORE).await; + fixture.library(SHARED); + let host = fixture.with_host(); + let sdk = fixture.host.resources().expect("an API 1.6 session"); + (fixture, sdk, host) +} + +fn raw_written(reply: MutationReply) -> Written { + Written::try_from(reply).unwrap() +} + +#[tokio::test] +async fn a_session_before_api_1_6_has_no_resource_helpers() { + let fixture = Fixture::build(&[], false).await; + assert!(fixture.host.resources().is_none()); + assert!(fixture.host.resource_context().is_none()); +} + +#[test] +fn idempotency_keys_are_unique_and_acceptable_to_the_host() { + let keys: std::collections::HashSet = (0..1000).map(|_| idempotency_key()).collect(); + assert_eq!(keys.len(), 1000); + assert!( + keys.iter() + .all(|key| (1..=128).contains(&key.len()) && !key.chars().any(char::is_control)) + ); +} + +#[tokio::test] +async fn library_reads_equal_the_raw_reads_across_pages() { + let fixture = Fixture::new(&[cap::LIBRARY_READ]).await; + let rows: Vec<(String, u64)> = (0..450).map(|n| (format!("fixture:{n}"), n + 1)).collect(); + let borrowed: Vec<(&str, Option, &str)> = rows + .iter() + .map(|(key, game)| (key.as_str(), Some(*game), "Game")) + .collect(); + fixture.library(&borrowed); + let sdk = fixture.host.resources().unwrap(); + + // The helper walks three pages; walking by hand gives the same entries in the same order. + let all = sdk.library_entries("").await.unwrap(); + assert_eq!(all.len(), 450); + let mut by_hand = Vec::new(); + let mut cursor = String::new(); + loop { + let page = fixture + .client() + .library_list(fixture.list_request(200, &cursor, "")) + .await + .unwrap() + .into_inner(); + by_hand.extend(page.entries); + if page.next_cursor.is_empty() { + break; + } + cursor = page.next_cursor; + } + assert_eq!(all, by_hand); + + // One page, with a search and another provider's filter, matches the raw call. + let page = sdk.library_page("", "Game", 5, "").await.unwrap(); + let raw = fixture + .client() + .library_list(LibraryListRequest { + search: "Game".into(), + ..fixture.list_request(5, "", "") + }) + .await + .unwrap() + .into_inner(); + assert_eq!((&page.entries, page.revision), (&raw.entries, raw.revision)); + assert!(!page.next_cursor.is_empty()); + assert_eq!( + sdk.library_get("id-fixture:7").await.unwrap(), + fixture.get("id-fixture:7", "").await.unwrap() + ); + + // A cursor the library has moved past is the host's own stale-cursor refusal. + let first = sdk.library_page("", "", 2, "").await.unwrap(); + fixture.library(&[("fixture:1", Some(1), "Renamed")]); + let stale = sdk + .library_page("", "", 2, &first.next_cursor) + .await + .unwrap_err(); + let raw_stale = fixture + .client() + .library_list(fixture.list_request(2, &first.next_cursor, "")) + .await + .unwrap_err(); + assert_eq!(stale.code(), Code::FailedPrecondition); + assert_eq!( + (stale.code(), stale.message()), + (raw_stale.code(), raw_stale.message()) + ); +} + +#[tokio::test] +async fn library_errors_are_the_hosts_own() { + let (fixture, sdk, _host) = ready().await; + // A foreign installation, even by id, and an unknown one. + for id in ["id-steam:620", "id-nope"] { + let via_sdk = sdk.library_get(id).await.unwrap_err(); + let raw = fixture.get(id, "").await.unwrap_err(); + assert_eq!(via_sdk.code(), Code::NotFound, "{id}"); + assert_eq!( + (via_sdk.code(), via_sdk.message()), + (raw.code(), raw.message()) + ); + } + // Another provider's entries are not disclosed without library.read.all: the list is empty, + // exactly as the raw call answers. + let other = sdk.library_page("steam", "", 10, "").await.unwrap(); + let raw = fixture.list("steam").await.unwrap(); + assert!(other.entries.is_empty()); + assert_eq!(other.entries, raw.entries); +} + +#[tokio::test] +async fn watch_through_the_sdk_delivers_the_same_events_as_the_raw_stream() { + let (fixture, sdk, _host) = ready().await; + let revision = fixture.feed.revision(); + let mut by_sdk = sdk.library_watch("", revision).await.unwrap(); + let mut by_hand = fixture.watch(revision).await.unwrap(); + fixture.library(&[ + ("fixture:1", Some(7), "Portal Two"), + ("fixture:2", None, "Homebrew"), + ]); + let (a, b) = ( + next(&mut by_sdk).await.unwrap(), + next(&mut by_hand).await.unwrap(), + ); + assert_eq!(a, b); + assert_eq!(a.event_type, "upserted"); + // A position the host no longer retains is its refusal, unchanged. + let status = sdk.library_watch("", 10_000).await.unwrap_err(); + assert_eq!(status.code(), Code::OutOfRange); +} + +#[tokio::test] +async fn display_names_set_through_the_sdk_are_what_a_raw_call_would_set() { + let (fixture, sdk, host) = ready().await; + let key = idempotency_key(); + let set = sdk + .set_display_name("id-fixture:1", 0, &key, Some("Portal Two")) + .await + .unwrap(); + assert_eq!( + set, + Written { + resource_id: "id-fixture:1".into(), + revision: 1, + outcome: Outcome::Applied + } + ); + // The same key with the hand-written request replays the SDK's outcome, so it was identical. + let replay = fixture + .set_name( + &key, + 0, + "id-fixture:1", + "", + &[("display_name", "Portal Two")], + ) + .await + .unwrap(); + assert_eq!(raw_written(replay), set); + assert_eq!(host.writes.load(Ordering::SeqCst), 1); + + // A stale revision is an answer, not an error, in both. + let stale = sdk + .set_display_name("id-fixture:1", 0, &idempotency_key(), Some("Other")) + .await + .unwrap(); + let raw = fixture + .rename(&idempotency_key(), 0, "Other") + .await + .unwrap(); + assert_eq!( + (stale.outcome, stale.revision), + (Outcome::RevisionConflict, 1) + ); + assert_eq!( + raw_written(raw), + Written { + resource_id: "id-fixture:1".into(), + ..stale + } + ); + + // None restores the detected name; the raw call for it is an empty display_name. + let clear_key = idempotency_key(); + let cleared = sdk + .set_display_name("id-fixture:1", 1, &clear_key, None) + .await + .unwrap(); + assert_eq!((cleared.revision, cleared.outcome), (2, Outcome::Applied)); + let replay = fixture + .set_name(&clear_key, 1, "id-fixture:1", "", &[("display_name", "")]) + .await + .unwrap(); + assert_eq!(raw_written(replay), cleared); + + // A foreign entry and a bad value fail with the host's own codes. + let foreign = sdk + .set_display_name("id-steam:620", 0, &idempotency_key(), Some("X")) + .await + .unwrap_err(); + assert_eq!(foreign.code(), Code::NotFound); + let control = sdk + .set_display_name("id-fixture:1", 2, &idempotency_key(), Some("a\u{7}b")) + .await + .unwrap_err(); + assert_eq!(control.code(), Code::InvalidArgument); +} + +#[tokio::test] +async fn favorites_through_the_sdk_equal_the_raw_calls() { + let (fixture, sdk, host) = ready().await; + host.games + .lock() + .unwrap() + .insert(("fixture".into(), 7), false); + + let key = idempotency_key(); + let set = sdk.set_favorite("7", true, &key).await.unwrap(); + assert_eq!( + (set.resource_id.as_str(), set.revision, set.outcome), + ("7", 0, Outcome::Applied) + ); + let replay = fixture.favorite(&key, 0, "", "7", true).await.unwrap(); + assert_eq!(raw_written(replay), set); + assert_eq!(host.writes.load(Ordering::SeqCst), 1); + + let raw_list = fixture.favorites(0, "", "").await.unwrap(); + let listed = sdk.favorite_games().await.unwrap(); + assert_eq!(listed, [("7".to_owned(), true)]); + assert_eq!( + listed, + raw_list + .entries + .iter() + .map(|e| (e.game_id.clone(), e.favorite)) + .collect::>() + ); + // The same state again is already applied; a game no own entry is matched to is not found. + let again = sdk + .set_favorite("7", true, &idempotency_key()) + .await + .unwrap(); + assert_eq!(again.outcome, Outcome::AlreadyApplied); + let nobody = sdk + .set_favorite("8", true, &idempotency_key()) + .await + .unwrap_err(); + assert_eq!(nobody.code(), Code::NotFound); +} + +#[tokio::test] +async fn matching_through_the_sdk_equals_the_raw_calls() { + let (fixture, sdk, host) = ready().await; + *host.catalog.lock().unwrap() = vec![ + catalog_game(7, "Portal 2", Some(2011)), + catalog_game(8, "Portal", Some(2007)), + ]; + let found = sdk.search_catalog("portal", 0).await.unwrap(); + let raw = fixture.search("portal", 0).await.unwrap(); + assert_eq!(found, raw.candidates); + assert_eq!( + found + .iter() + .map(|c| (c.game_id.as_str(), c.release_year)) + .collect::>(), + [("7", 2011), ("8", 2007)] + ); + + let key = idempotency_key(); + let assigned = sdk + .assign_match("id-fixture:2", "7", 1, &key) + .await + .unwrap(); + assert_eq!( + ( + assigned.resource_id.as_str(), + assigned.revision, + assigned.outcome + ), + ("id-fixture:2", 2, Outcome::Applied) + ); + let replay = fixture.assign(&key, 1, "7").await.unwrap(); + assert_eq!(raw_written(replay), assigned); + assert_eq!(host.writes.load(Ordering::SeqCst), 1); + + // A stale revision conflicts; a game nobody offered is not found; the user's choice stands. + let conflict = sdk + .assign_match("id-fixture:2", "8", 1, &idempotency_key()) + .await + .unwrap(); + assert_eq!(conflict.outcome, Outcome::RevisionConflict); + let unknown = sdk + .assign_match("id-fixture:2", "999", 2, &idempotency_key()) + .await + .unwrap_err(); + assert_eq!(unknown.code(), Code::NotFound); + host.matches + .lock() + .unwrap() + .insert("fixture:1".into(), (Some(7), true, 1)); + let user = sdk + .assign_match("id-fixture:1", "8", 1, &idempotency_key()) + .await + .unwrap_err(); + let raw_user = fixture + .assign_request(&idempotency_key(), 1, "id-fixture:1", "8") + .await + .unwrap_err(); + assert_eq!(user.code(), Code::FailedPrecondition); + assert_eq!( + (user.code(), user.message()), + (raw_user.code(), raw_user.message()) + ); +} + +#[tokio::test] +async fn covers_through_the_sdk_equal_the_raw_calls() { + let (fixture, sdk, host) = ready().await; + host.game_covers + .lock() + .unwrap() + .insert("fixture:1".into(), b"game cover".to_vec()); + let before = sdk.read_cover("id-fixture:1", 0).await.unwrap(); + assert_eq!( + (before.bytes.as_slice(), before.revision), + (b"game cover".as_slice(), 0) + ); + + let key = idempotency_key(); + let set = sdk + .set_cover("id-fixture:1", 0, &key, png(900, 1200), "image/png") + .await + .unwrap(); + assert_eq!((set.revision, set.outcome), (1, Outcome::Applied)); + let replay = fixture + .set_cover(&key, 0, "id-fixture:1", png(900, 1200), "image/png") + .await + .unwrap(); + assert_eq!(raw_written(replay), set); + assert_eq!(host.writes.load(Ordering::SeqCst), 1); + + let cover = sdk.read_cover("id-fixture:1", 0).await.unwrap(); + let raw = fixture.read_cover("id-fixture:1", 0).await.unwrap(); + assert_eq!( + ( + cover.bytes.as_slice(), + cover.media_type.as_str(), + cover.revision + ), + ( + raw.encoded_image.as_slice(), + raw.media_type.as_str(), + raw.revision + ) + ); + assert_eq!(cover.revision, 1); + + // Clearing restores the game's cover, with the raw call for it being an empty image. + let clear_key = idempotency_key(); + let cleared = sdk + .clear_cover("id-fixture:1", 1, &clear_key) + .await + .unwrap(); + assert_eq!((cleared.revision, cleared.outcome), (2, Outcome::Applied)); + let replay = fixture + .set_cover(&clear_key, 1, "id-fixture:1", Vec::new(), "") + .await + .unwrap(); + assert_eq!(raw_written(replay), cleared); + assert_eq!( + sdk.read_cover("id-fixture:1", 0).await.unwrap().bytes, + b"game cover" + ); + + // A refused image, a missing cover and an over-budget read are the host's own errors. + let refused = sdk + .set_cover( + "id-fixture:1", + 2, + &idempotency_key(), + b"".to_vec(), + "image/png", + ) + .await + .unwrap_err(); + let raw_refused = fixture + .set_cover( + &idempotency_key(), + 2, + "id-fixture:1", + b"".to_vec(), + "image/png", + ) + .await + .unwrap_err(); + assert_eq!(refused.code(), Code::InvalidArgument); + assert_eq!( + (refused.code(), refused.message()), + (raw_refused.code(), raw_refused.message()) + ); + assert_eq!( + sdk.read_cover("id-fixture:2", 0).await.unwrap_err().code(), + Code::NotFound + ); + assert_eq!( + sdk.read_cover("id-fixture:1", 3).await.unwrap_err().code(), + Code::ResourceExhausted + ); +} + +#[tokio::test] +async fn without_a_grant_or_the_engine_the_sdk_gets_the_raw_refusals() { + // No write grants: every write is denied exactly as the raw call is. + let fixture = Fixture::new(&[cap::LIBRARY_READ]).await; + fixture.library(SHARED); + fixture.with_host(); + let sdk = fixture.host.resources().unwrap(); + let denied = sdk + .set_display_name("id-fixture:1", 0, &idempotency_key(), Some("X")) + .await + .unwrap_err(); + let raw = fixture + .rename(&idempotency_key(), 0, "X") + .await + .unwrap_err(); + assert_eq!(denied.code(), Code::PermissionDenied); + assert_eq!( + (denied.code(), denied.message()), + (raw.code(), raw.message()) + ); + assert_eq!( + sdk.set_favorite("7", true, &idempotency_key()) + .await + .unwrap_err() + .code(), + Code::PermissionDenied + ); + assert_eq!( + sdk.search_catalog("portal", 0).await.unwrap_err().code(), + Code::PermissionDenied + ); + assert_eq!( + sdk.read_cover("id-fixture:1", 0).await.unwrap_err().code(), + Code::PermissionDenied + ); + + // Granted but with no engine side connected: unavailable, as raw. + let fixture = Fixture::new(OWN_AND_MORE).await; + fixture.library(SHARED); + let sdk = fixture.host.resources().unwrap(); + let down = sdk + .set_display_name("id-fixture:1", 0, &idempotency_key(), Some("X")) + .await + .unwrap_err(); + assert_eq!(down.code(), Code::Unavailable); +} + +// ---- Shared data: SDK helpers against the same fixture host ---- + +const DATA_GRANTS: &[&str] = &[cap::DATA_PUBLISH, cap::STORAGE_PERSIST]; +const DATASET: &str = "org.example.metrics.v1"; + +fn data_struct(fps: f64) -> prost_types::Struct { + prost_types::Struct { + fields: [( + "fps".to_owned(), + prost_types::Value { + kind: Some(prost_types::value::Kind::NumberValue(fps)), + }, + )] + .into(), + } +} + +/// A publication the caller would write itself: every field but `mutation`. +fn publication(key: &str, fps: f64, durability: StorageDurability) -> DataPublishRequest { + DataPublishRequest { + dataset_id: DATASET.into(), + schema_id: DATASET.into(), + schema_version: 1, + value: Some(data_struct(fps)), + durability: durability as i32, + ttl_seconds: 300, + resource_id: "runtime-primary".into(), + observed_at: 1_700_000_000, + sequence: 1, + source_observation_id: key.into(), + ..Default::default() + } +} + +async fn next_data(stream: &mut tonic::Streaming) -> DataEvent { + tokio::time::timeout(std::time::Duration::from_secs(5), stream.message()) + .await + .expect("an event in time") + .expect("the stream is open") + .expect("an event, not the end of the stream") +} + +#[tokio::test] +async fn durable_publication_through_the_sdk_replays_identically_when_sent_raw() { + let fixture = Fixture::new(DATA_GRANTS).await; + let sdk = fixture.host.resources().unwrap(); + let key = idempotency_key(); + + let published = sdk + .data_publish( + &key, + 0, + publication(&key, 60.0, StorageDurability::Persistent), + ) + .await + .unwrap(); + assert_eq!( + published.durability, + StorageDurability::Persistent as i32, + "the host stored the requested durable mode" + ); + assert_eq!(published.outcome, MutationOutcome::Applied as i32); + assert!(!published.record_id.is_empty()); + assert!(published.expires_at > 0); + + // The same key replayed raw returns the original record and revision only if the SDK sent the + // identical request, including the session's mutation context. + let replay = fixture + .client() + .data_publish(DataPublishRequest { + mutation: Some(fixture.mutation(&key, 0)), + ..publication(&key, 60.0, StorageDurability::Persistent) + }) + .await + .unwrap() + .into_inner(); + assert_eq!(replay.record_id, published.record_id); + assert_eq!(replay.revision, published.revision); + assert_eq!(replay, published); +} + +#[tokio::test] +async fn data_reads_through_the_sdk_equal_the_raw_calls() { + let fixture = Fixture::new(DATA_GRANTS).await; + let sdk = fixture.host.resources().unwrap(); + let key = idempotency_key(); + let published = sdk + .data_publish( + &key, + 0, + publication(&key, 60.0, StorageDurability::Persistent), + ) + .await + .unwrap(); + + let record = sdk + .data_get(DATASET, &published.record_id, None) + .await + .unwrap(); + let raw = fixture + .client() + .data_get(DataGetRequest { + context: Some(fixture.context()), + dataset_id: DATASET.into(), + record_id: published.record_id.clone(), + common_data_categories: None, + }) + .await + .unwrap() + .into_inner() + .record + .unwrap(); + assert_eq!(record, raw); + assert_eq!(record.revision, published.revision); + assert_eq!(record.durability, StorageDurability::Persistent as i32); + + let page = sdk.data_list(DATASET, "", None, 10).await.unwrap(); + let raw_page = fixture + .client() + .data_list(DataListRequest { + page: Some(PageRequest { + context: Some(fixture.context()), + cursor: String::new(), + page_size: 10, + common_data_categories: None, + }), + dataset_id: DATASET.into(), + filter: String::new(), + common_data_categories: None, + }) + .await + .unwrap() + .into_inner(); + assert_eq!(page.records, raw_page.records); + assert_eq!(page.revision, raw_page.revision); + assert!(page.next_cursor.is_empty()); + assert_eq!(page.records.len(), 1); + assert_eq!(page.records[0].record_id, published.record_id); + + // An explicit selector is sent only on the request, exactly as a raw caller would. + let selector = CommonDataSelector::default(); + let with_selector = sdk + .data_list(DATASET, "", Some(selector.clone()), 10) + .await + .unwrap(); + let raw_selector = fixture + .client() + .data_list(DataListRequest { + page: Some(PageRequest { + context: Some(fixture.context()), + cursor: String::new(), + page_size: 10, + common_data_categories: None, + }), + dataset_id: DATASET.into(), + filter: String::new(), + common_data_categories: Some(selector), + }) + .await + .unwrap() + .into_inner(); + assert_eq!(with_selector.records, raw_selector.records); + assert_eq!(with_selector.revision, raw_selector.revision); + + let missing = sdk + .data_get(DATASET, "no-such-record", None) + .await + .unwrap_err(); + let raw_missing = fixture + .client() + .data_get(DataGetRequest { + context: Some(fixture.context()), + dataset_id: DATASET.into(), + record_id: "no-such-record".into(), + common_data_categories: None, + }) + .await + .unwrap_err(); + assert_eq!(missing.code(), Code::NotFound); + assert_eq!( + (missing.code(), missing.message()), + (raw_missing.code(), raw_missing.message()) + ); +} + +#[tokio::test] +async fn data_watch_through_the_sdk_delivers_the_same_event_as_the_raw_stream() { + let fixture = Fixture::new(DATA_GRANTS).await; + let sdk = fixture.host.resources().unwrap(); + let first_key = idempotency_key(); + sdk.data_publish( + &first_key, + 0, + publication(&first_key, 60.0, StorageDurability::Persistent), + ) + .await + .unwrap(); + let listed = sdk.data_list(DATASET, "", None, 10).await.unwrap(); + + let mut by_sdk = sdk + .data_watch(DATASET, listed.revision, None) + .await + .unwrap(); + let mut by_hand = fixture + .client() + .data_watch(DataWatchRequest { + context: Some(fixture.context()), + dataset_id: DATASET.into(), + after_revision: listed.revision, + common_data_categories: None, + }) + .await + .unwrap() + .into_inner(); + + let second_key = idempotency_key(); + let mut second_request = publication(&second_key, 75.0, StorageDurability::Persistent); + second_request.sequence = 2; + let second = sdk + .data_publish(&second_key, 0, second_request) + .await + .unwrap(); + + let (via_sdk, raw) = (next_data(&mut by_sdk).await, next_data(&mut by_hand).await); + assert_eq!(via_sdk, raw); + assert_eq!(via_sdk.event_type, "published"); + assert_eq!(via_sdk.revision, second.revision); + assert_eq!(via_sdk.record.unwrap().record_id, second.record_id); +} + +#[tokio::test] +async fn durable_publish_without_storage_persist_fails_through_the_sdk_and_keeps_no_row() { + let fixture = Fixture::new(&[cap::DATA_PUBLISH]).await; + let sdk = fixture.host.resources().unwrap(); + let key = idempotency_key(); + + let denied = sdk + .data_publish( + &key, + 0, + publication(&key, 60.0, StorageDurability::Persistent), + ) + .await + .unwrap_err(); + assert_eq!(denied.code(), Code::PermissionDenied); + assert!( + denied.message().contains("storage.persist"), + "unexpected message: {}", + denied.message() + ); + + // The identical raw call is refused with the same status. + let raw = fixture + .client() + .data_publish(DataPublishRequest { + mutation: Some(fixture.mutation(&key, 0)), + ..publication(&key, 60.0, StorageDurability::Persistent) + }) + .await + .unwrap_err(); + assert_eq!( + (denied.code(), denied.message()), + (raw.code(), raw.message()) + ); + + // No session fallback and no durable row or pool file. + let listed = sdk.data_list(DATASET, "", None, 10).await.unwrap(); + assert!(listed.records.is_empty()); + let raw_listed = fixture + .client() + .data_list(DataListRequest { + page: Some(PageRequest { + context: Some(fixture.context()), + cursor: String::new(), + page_size: 10, + common_data_categories: None, + }), + dataset_id: DATASET.into(), + filter: String::new(), + common_data_categories: None, + }) + .await + .unwrap() + .into_inner(); + assert!(raw_listed.records.is_empty()); + assert!( + SharedDataStore::open_existing(&fixture.data_dir) + .unwrap() + .is_none(), + "a refused durable publish must not create the pool" + ); +} + +#[tokio::test] +async fn a_revision_conflict_is_surfaced_unchanged_through_the_sdk() { + let fixture = Fixture::new(&[cap::DATA_PUBLISH]).await; + let sdk = fixture.host.resources().unwrap(); + + let first_key = idempotency_key(); + let first = sdk + .data_publish( + &first_key, + 0, + publication(&first_key, 60.0, StorageDurability::SessionOnly), + ) + .await + .unwrap(); + assert_eq!(first.outcome, MutationOutcome::Applied as i32); + + // A different observation for the same resource and sequence is the host's own conflict + // answer, not an SDK error. + let conflicting_key = idempotency_key(); + let mut conflicting = publication(&conflicting_key, 75.0, StorageDurability::SessionOnly); + conflicting.source_observation_id = "different-observation".into(); + let conflict = sdk + .data_publish(&conflicting_key, 0, conflicting.clone()) + .await + .unwrap(); + assert_eq!(conflict.outcome, MutationOutcome::RevisionConflict as i32); + assert_eq!(conflict.revision, first.revision); + + let raw_conflict = fixture + .client() + .data_publish(DataPublishRequest { + mutation: Some(fixture.mutation(&idempotency_key(), 0)), + ..conflicting + }) + .await + .unwrap() + .into_inner(); + assert_eq!( + (raw_conflict.outcome, raw_conflict.revision), + (conflict.outcome, conflict.revision) + ); + + // A non-zero expected_revision stays the host's append-only refusal in both calls. + let refused_key = idempotency_key(); + let refused = sdk + .data_publish( + &refused_key, + 1, + publication(&refused_key, 60.0, StorageDurability::SessionOnly), + ) + .await + .unwrap_err(); + let raw_refused = fixture + .client() + .data_publish(DataPublishRequest { + mutation: Some(fixture.mutation(&refused_key, 1)), + ..publication(&refused_key, 60.0, StorageDurability::SessionOnly) + }) + .await + .unwrap_err(); + assert_eq!(refused.code(), Code::InvalidArgument); + assert_eq!( + (refused.code(), refused.message()), + (raw_refused.code(), raw_refused.message()) + ); +} + +#[tokio::test] +async fn the_sdk_publishes_with_the_session_context_from_resources() { + let fixture = Fixture::new(DATA_GRANTS).await; + let sdk = fixture.host.resources().unwrap(); + let key = idempotency_key(); + let published = sdk + .data_publish( + &key, + 0, + publication(&key, 60.0, StorageDurability::Persistent), + ) + .await + .unwrap(); + + // The idempotency key is scoped to the authenticated session: the same key from another + // session applies separately instead of replaying, which shows which context the SDK used. + let other = super::data::consumer_session_with_grants(&fixture, DATA_GRANTS).await; + let other_context = other.host.resource_context().unwrap().clone(); + let separate = other + .host + .resource_client() + .data_publish(DataPublishRequest { + mutation: Some(MutationContext { + context: Some(other_context), + idempotency_key: key.clone(), + ..Default::default() + }), + ..publication(&key, 60.0, StorageDurability::Persistent) + }) + .await + .unwrap() + .into_inner(); + assert_eq!(separate.outcome, MutationOutcome::Applied as i32); + assert_ne!(separate.record_id, published.record_id); + + // Under the session's own resource context, the raw replay is the SDK's original answer. + let replay = fixture + .client() + .data_publish(DataPublishRequest { + mutation: Some(fixture.mutation(&key, 0)), + ..publication(&key, 60.0, StorageDurability::Persistent) + }) + .await + .unwrap() + .into_inner(); + assert_eq!(replay, published); +} + +// ---- The published recipes, run against the same fixture host ---- + +#[path = "../../../../../plugin-sdk/examples/library_recipes.rs"] +mod recipes; + +#[tokio::test(start_paused = true)] +async fn a_change_is_resent_with_its_key_only_after_a_lost_connection() { + let calls = std::sync::atomic::AtomicUsize::new(0); + let sent = recipes::send(|| async { + match calls.fetch_add(1, Ordering::SeqCst) { + 0 | 1 => Err(Status::unavailable("connection lost")), + _ => Ok("done"), + } + }) + .await; + assert_eq!((sent.unwrap(), calls.load(Ordering::SeqCst)), ("done", 3)); + + // Three failures give up with the last one; a real answer or refusal is never resent. + calls.store(0, Ordering::SeqCst); + let sent: Result<(), Status> = recipes::send(|| async { + calls.fetch_add(1, Ordering::SeqCst); + Err(Status::deadline_exceeded("slow")) + }) + .await; + assert_eq!(sent.unwrap_err().code(), Code::DeadlineExceeded); + assert_eq!(calls.load(Ordering::SeqCst), 3); + calls.store(0, Ordering::SeqCst); + let sent: Result<(), Status> = recipes::send(|| async { + calls.fetch_add(1, Ordering::SeqCst); + Err(Status::not_found("no")) + }) + .await; + assert_eq!(sent.unwrap_err().code(), Code::NotFound); + assert_eq!(calls.load(Ordering::SeqCst), 1); +} + +#[tokio::test] +async fn the_rename_recipe_writes_with_the_revision_it_read_and_gives_up_on_a_moving_entry() { + let (_fixture, sdk, host) = ready().await; + let named = recipes::rename(&sdk, "id-fixture:1", Some("Portal Two")) + .await + .unwrap(); + assert_eq!((named.revision, named.outcome), (1, Outcome::Applied)); + assert_eq!( + host.name_of("fixture:1"), + Some((Some("Portal Two".into()), 1)) + ); + // The fixture library still reports revision 0 (it is not fed back), so the host sees a stale + // revision on every attempt: the recipe reads again, then reports that the entry kept moving. + let moving = recipes::rename(&sdk, "id-fixture:1", Some("Again")) + .await + .unwrap_err(); + assert_eq!(moving.code(), Code::Aborted); + assert_eq!( + host.name_of("fixture:1"), + Some((Some("Portal Two".into()), 1)) + ); + // Other errors are not retried. + let foreign = recipes::rename(&sdk, "id-steam:620", Some("X")) + .await + .unwrap_err(); + assert_eq!(foreign.code(), Code::NotFound); +} + +#[tokio::test] +async fn the_match_recipe_finds_the_title_and_leaves_the_users_choice_alone() { + let (_fixture, sdk, host) = ready().await; + *host.catalog.lock().unwrap() = vec![ + catalog_game(8, "Portal", Some(2007)), + catalog_game(7, "Portal 2", Some(2011)), + ]; + // The exact title, not the first search result. + let written = recipes::match_by_title(&sdk, "id-fixture:2", "portal 2") + .await + .unwrap() + .unwrap(); + assert_eq!(written.outcome, Outcome::Applied); + assert_eq!(host.matches.lock().unwrap()["fixture:2"].0, Some(7)); + // Nothing in the catalog is that title. + assert!( + recipes::match_by_title(&sdk, "id-fixture:2", "Half-Life") + .await + .unwrap() + .is_none() + ); + // The user chose this entry's game: the recipe reports nothing to do. + host.matches + .lock() + .unwrap() + .insert("fixture:1".into(), (Some(8), true, 1)); + assert!( + recipes::match_by_title(&sdk, "id-fixture:1", "Portal 2") + .await + .unwrap() + .is_none() + ); +} + +#[tokio::test] +async fn the_cover_recipes_set_clear_and_read_without_downloading() { + let (_fixture, sdk, host) = ready().await; + assert!( + recipes::current_cover(&sdk, "id-fixture:1") + .await + .unwrap() + .is_none() + ); + let set = recipes::use_cover(&sdk, "id-fixture:1", Some((png(300, 450), "image/png"))) + .await + .unwrap(); + assert_eq!((set.revision, set.outcome), (1, Outcome::Applied)); + let cover = recipes::current_cover(&sdk, "id-fixture:1") + .await + .unwrap() + .unwrap(); + assert_eq!( + (cover.media_type.as_str(), cover.revision), + ("image/jpeg", 1) + ); + // A refused image is the host's refusal, not retried. + let refused = recipes::use_cover(&sdk, "id-fixture:1", Some((b"nope".to_vec(), "image/png"))) + .await + .unwrap_err(); + assert_eq!(refused.code(), Code::InvalidArgument); + assert_eq!(host.writes.load(Ordering::SeqCst), 1); +} + +#[tokio::test] +async fn the_favorites_recipe_stars_each_matched_game_once() { + let (_fixture, sdk, host) = ready().await; + { + let mut games = host.games.lock().unwrap(); + games.insert(("fixture".into(), 7), false); + games.insert(("fixture".into(), 9), true); + games.insert(("fixture".into(), 11), false); + } + assert_eq!(recipes::star_matched_games(&sdk).await.unwrap(), 2); + assert!( + host.games + .lock() + .unwrap() + .values() + .all(|favorite| *favorite) + ); + assert_eq!(recipes::star_matched_games(&sdk).await.unwrap(), 0); +} + +#[tokio::test] +async fn the_follow_recipe_lists_then_receives_the_changes_after_the_list() { + let (fixture, sdk, _host) = ready().await; + let listed = std::sync::atomic::AtomicUsize::new(usize::MAX); + let mut seen = Vec::new(); + let follow = recipes::follow_library( + &sdk, + |entries| listed.store(entries.len(), Ordering::SeqCst), + |event| { + seen.push((event.event_type, event.entry.unwrap().name)); + false + }, + ); + let change = async { + while listed.load(Ordering::SeqCst) == usize::MAX { + tokio::task::yield_now().await; + } + // The change lands after the snapshot; the watch resumes from the snapshot's revision, + // so it is delivered even if the stream opens later. + fixture.library(&[ + ("fixture:1", Some(7), "Portal Two"), + ("fixture:2", None, "Homebrew"), + ]); + }; + let (followed, ()) = tokio::join!(follow, change); + followed.unwrap(); + assert_eq!(listed.load(Ordering::SeqCst), 2); + assert_eq!(seen, [("upserted".to_owned(), "Portal Two".to_owned())]); +} diff --git a/crates/app/src/plugin_host/resources/tests/sdk_actions.rs b/crates/app/src/plugin_host/resources/tests/sdk_actions.rs new file mode 100644 index 000000000..af5e75e83 --- /dev/null +++ b/crates/app/src/plugin_host/resources/tests/sdk_actions.rs @@ -0,0 +1,266 @@ +//! The SDK's action helpers and recipes against the fixture host: the same requests a raw call +//! sends, jobs followed to completion, and a permission revoked while a confirmation is open. +use std::sync::Mutex as StdMutex; + +use super::*; +use crate::plugin_host::intents::{Answer, ConfirmationRequest, Prompter}; +use gamenode_plugin_sdk::{Actions, Code, idempotency_key, proto::JobState}; +use tokio::sync::Notify; + +use super::action_recipes; + +const GRANTS: &[&str] = &[ + cap::LIBRARY_READ, + cap::GAME_LAUNCH, + cap::TOOLS_READ, + cap::TOOLS_APPLY, + cap::TOOLS_REMOVE, + cap::PORTS_READ, + cap::PORTS_INSTALL, +]; + +/// The user's side of Core's confirmation dialog: answers when the test lets it go. +#[derive(Default)] +struct Dialog { + shown: StdMutex>, + gate: Option>, + approve: bool, +} + +#[tonic::async_trait] +impl Prompter for Dialog { + async fn confirm(&self, request: ConfirmationRequest) -> Result { + self.shown.lock().unwrap().push(request); + if let Some(gate) = &self.gate { + gate.notified().await; + } + Ok(Answer { + approved: self.approve, + remember: false, + }) + } +} + +async fn shown(dialog: &Dialog) { + tokio::time::timeout(Duration::from_secs(5), async { + while dialog.shown.lock().unwrap().is_empty() { + tokio::time::sleep(Duration::from_millis(5)).await; + } + }) + .await + .unwrap(); +} + +fn catalog() -> Vec { + ["alpha", "beta"] + .into_iter() + .map(|name| PortRecord { + port_id: format!("qcat_{name}"), + name: name.into(), + platform: "windows".into(), + availability: "available".into(), + }) + .collect() +} + +async fn setup() -> (Fixture, Arc, Actions) { + let f = Fixture::new(GRANTS).await; + f.library(&[("fixture:1", Some(3), "Game")]); + let host = f.with_host(); + host.tool_support.store(true, Ordering::SeqCst); + host.port_support.store(true, Ordering::SeqCst); + *host.port_records.lock().unwrap() = catalog(); + let actions = f.host.actions().expect("an API 1.6 session"); + (f, host, actions) +} + +#[tokio::test(flavor = "multi_thread")] +async fn tool_calls_through_the_sdk_match_raw_calls_and_the_job_runs_to_the_end() { + let (f, host, actions) = setup().await; + let revision = f.feed.revision_of("fixture:1").unwrap(); + let raw = f + .client() + .tools_list(ToolsListRequest { + page: Some(PageRequest { + context: Some(f.context()), + page_size: 200, + ..Default::default() + }), + game_id: "3".into(), + platform: "windows".into(), + }) + .await + .unwrap() + .into_inner(); + assert_eq!(actions.tools("3", "windows").await.unwrap(), raw.tools); + + let job = actions + .apply_tool("optiscaler", "3", revision, &idempotency_key()) + .await + .unwrap(); + tokio::time::timeout(Duration::from_secs(5), async { + while host.tool_reviews.lock().unwrap().is_empty() { + tokio::task::yield_now().await; + } + }) + .await + .unwrap(); + let waiting = tokio::spawn({ + let actions = actions.clone(); + let id = job.job_id.clone(); + async move { action_recipes::wait_for_job(&actions, &id).await } + }); + tokio::time::sleep(Duration::from_millis(50)).await; + assert!(!waiting.is_finished(), "the review is still open"); + host.tool_gate.notify_one(); + let done = waiting.await.unwrap().unwrap(); + assert_eq!(done.state, JobState::Succeeded); + assert_eq!(host.tool_effects.load(Ordering::SeqCst), 1); + + let removed = actions + .remove_tool("optiscaler", "3", revision, &idempotency_key()) + .await + .unwrap(); + tokio::time::timeout(Duration::from_secs(5), async { + while host.tool_reviews.lock().unwrap().len() < 2 { + tokio::task::yield_now().await; + } + }) + .await + .unwrap(); + host.tool_gate.notify_one(); + let removed = action_recipes::wait_for_job(&actions, &removed.job_id) + .await + .unwrap(); + assert_eq!(removed.state, JobState::Succeeded); + assert_eq!(host.tool_effects.load(Ordering::SeqCst), 2); +} + +#[tokio::test(flavor = "multi_thread")] +async fn revoking_the_permission_while_a_confirmation_is_open_prevents_the_effect() { + let (f, host, actions) = setup().await; + let revision = f.feed.revision_of("fixture:1").unwrap(); + let job = actions + .apply_tool("optiscaler", "3", revision, &idempotency_key()) + .await + .unwrap(); + tokio::time::timeout(Duration::from_secs(5), async { + while host.tool_reviews.lock().unwrap().is_empty() { + tokio::task::yield_now().await; + } + }) + .await + .unwrap(); + + // The user is still looking at the dialog when the grant goes away. + f.api + .revoke_session_permission("fixture", cap::TOOLS_APPLY) + .await; + host.tool_gate.notify_one(); + let result = action_recipes::wait_for_job(&actions, &job.job_id).await; + match result { + Ok(done) => assert_eq!(done.state, JobState::Failed), + Err(status) => assert_eq!(status.code(), Code::PermissionDenied), + } + assert_eq!(host.tool_effects.load(Ordering::SeqCst), 0); +} + +#[tokio::test(flavor = "multi_thread")] +async fn port_calls_through_the_sdk_match_raw_calls_and_install_waits_for_core() { + let (f, host, actions) = setup().await; + let raw = f + .client() + .ports_list(PortsListRequest { + page: Some(PageRequest { + context: Some(f.context()), + page_size: 200, + ..Default::default() + }), + platform: "windows".into(), + query: String::new(), + }) + .await + .unwrap() + .into_inner(); + assert_eq!(actions.ports("windows", "").await.unwrap(), raw.ports); + assert_eq!( + actions.port("qcat_alpha").await.unwrap(), + raw.ports[0].clone() + ); + + let job = actions + .install_port("qcat_alpha", "", vec![], 0, &idempotency_key()) + .await + .unwrap(); + tokio::time::timeout(Duration::from_secs(5), async { + while host.port_reviews.lock().unwrap().is_empty() { + tokio::task::yield_now().await; + } + }) + .await + .unwrap(); + let waiting = tokio::spawn({ + let actions = actions.clone(); + let id = job.job_id.clone(); + async move { action_recipes::wait_for_job(&actions, &id).await } + }); + tokio::time::sleep(Duration::from_millis(50)).await; + assert!(!waiting.is_finished()); + host.port_gate.notify_one(); + assert_eq!(waiting.await.unwrap().unwrap().state, JobState::Succeeded); + assert_eq!(host.port_effects.load(Ordering::SeqCst), 1); +} + +#[tokio::test(flavor = "multi_thread")] +async fn launching_through_the_sdk_waits_for_the_user_and_a_revoked_launch_starts_nothing() { + let f = Fixture::new(&[cap::LIBRARY_READ, cap::GAME_LAUNCH]).await; + f.library(&[("fixture:1", Some(3), "Game")]); + let host = f.with_host(); + let dialog = Arc::new(Dialog { + approve: true, + ..Dialog::default() + }); + f.intents.set_prompter(dialog.clone()); + let actions = f.host.actions().unwrap(); + let revision = f.feed.revision_of("fixture:1").unwrap(); + let waiting = tokio::spawn({ + let actions = actions.clone(); + async move { action_recipes::launch(&actions, "id-fixture:1", revision).await } + }); + shown(&dialog).await; + let done = waiting.await.unwrap().unwrap(); + assert_eq!( + (done.state, done.result_code.as_str()), + (JobState::Succeeded, "opened") + ); + assert_eq!( + *host.opened.lock().unwrap(), + [("fixture:1".to_owned(), false)] + ); + + let gate = Arc::new(Notify::new()); + let dialog = Arc::new(Dialog { + gate: Some(gate.clone()), + approve: true, + ..Dialog::default() + }); + f.intents.set_prompter(dialog.clone()); + let waiting = tokio::spawn({ + let actions = actions.clone(); + async move { action_recipes::launch(&actions, "id-fixture:1", revision).await } + }); + shown(&dialog).await; + f.api + .revoke_session_permission("fixture", cap::GAME_LAUNCH) + .await; + gate.notify_one(); + let result = waiting.await.unwrap(); + match result { + Ok(done) => assert_eq!(done.state, JobState::Failed), + Err(status) => assert_eq!(status.code(), Code::PermissionDenied), + } + assert_eq!( + *host.opened.lock().unwrap(), + [("fixture:1".to_owned(), false)] + ); +} diff --git a/crates/app/src/plugin_host/resources/tests/sdk_data_exchange.rs b/crates/app/src/plugin_host/resources/tests/sdk_data_exchange.rs new file mode 100644 index 000000000..c0d2087e6 --- /dev/null +++ b/crates/app/src/plugin_host/resources/tests/sdk_data_exchange.rs @@ -0,0 +1,551 @@ +//! The shared-data exchange recipes run against the same fixture host as the raw RPC tests. +//! +//! Each scenario also reads the checked-in contract fixture +//! `crates/plugin-protocol/contracts/data_exchange_fixtures.json`. +//! The fixture is the source for identities, units and expected outcomes; the host still +//! decides every authorization answer. + +use gamenode_plugin_sdk::proto::{ + CommonDataCategory, ContentRegistrationRequest, ExtensionPayload, MutationOutcome, + RuntimeArgumentTemplate as RuntimeArgumentProto, RuntimeRecord, RuntimeRegisterRequest, + runtime_argument_template::Value as RuntimeArgumentValue, +}; +use serde_json::Value; + +use super::data::consumer_session_with_grants; +use super::saves::{INSTALLATION, directory, profile}; +use super::*; + +#[path = "../../../../../plugin-sdk/examples/data_exchange_recipes.rs"] +mod recipes; + +const CONTRACT: &str = + include_str!("../../../../../plugin-protocol/contracts/data_exchange_fixtures.json"); + +const PERFORMANCE: &[&str] = &[ + cap::GAME_LAUNCH, + cap::GAME_PERFORMANCE_PUBLISH, + cap::GAME_PERFORMANCE_READ, +]; +const SAVE_AND_LOCATION: &[&str] = &[ + cap::GAME_SAVES_READ, + cap::GAME_SAVES_CREATE, + cap::GAME_SAVES_UPDATE, + cap::GAME_SAVES_INSPECT, + cap::GAME_STORAGE_INSPECT, + cap::FILES_READ, +]; +const RUNTIME: &[&str] = &[ + cap::DISCOVERY, + cap::GAME_CUSTOM_LAUNCH, + cap::FILES_READ, + cap::GAME_RUNTIME_CREATE, + cap::GAME_RUNTIME_READ, +]; + +fn contract() -> Value { + serde_json::from_str(CONTRACT).unwrap() +} + +macro_rules! text { + ($value:expr) => { + $value.as_str().unwrap() + }; +} + +#[tokio::test(flavor = "multi_thread")] +async fn performance_fixture_exchanges_history_and_ends_the_series_explicitly() { + use crate::plugin_host::sharing_policy::ActivationReadGrant; + + let contract = contract(); + let performance = &contract["performance"]; + let game_id = text!(performance["game_id"]); + let series_id = text!(performance["series_id"]); + let fixture = Fixture::start_with_target( + PERFORMANCE, + true, + None, + Some(TargetGameContext { + game_id: game_id.into(), + installation_id: text!(performance["installation_id"]).into(), + profile_id: String::new(), + revision: "library-rev-1".into(), + }), + ) + .await; + let context = fixture.context(); + + // The example builds the batch from the shared contract fixture. Units, semantics and + // the host-selected game are explicit; nothing here launches a collector. + let samples = performance["samples"] + .as_array() + .unwrap() + .iter() + .map(|sample| { + recipes::sample( + sample["sequence"].as_u64().unwrap(), + sample["observed_at"].as_i64().unwrap(), + sample["fps"].as_f64().unwrap(), + ) + }) + .collect::>(); + let batch = recipes::performance_batch( + &context, + "performance-batch", + 0, + series_id, + game_id, + samples.clone(), + ); + assert_eq!(batch.samples.len(), 2); + assert_eq!( + batch.sample_interval_ms, + performance["sample_interval_ms"].as_u64().unwrap() as u32 + ); + assert_eq!(batch.fps_unit, text!(performance["units"]["fps"])); + assert_eq!(batch.cpu_unit, text!(performance["units"]["cpu"])); + assert_eq!(batch.memory_unit, text!(performance["units"]["memory"])); + assert_eq!( + batch.samples[0].cpu_percent, + performance["samples"][0]["cpu_percent"].as_f64().unwrap() + ); + + let published = recipes::publish_performance( + &fixture.host, + "performance-batch", + 0, + series_id, + game_id, + samples, + ) + .await + .unwrap(); + assert_eq!(published.accepted_samples, 2); + assert!(published.report_id.starts_with("performance-")); + + let consumer = consumer_session_with_grants(&fixture, &[cap::GAME_PERFORMANCE_READ]).await; + let consumer_context = consumer.host.resource_context().unwrap().clone(); + let identity = super::data::authenticated_identity(&fixture, &consumer_context); + + // Private-only default: the same query without a selector sees the consumer's own empty scope. + let private = recipes::list_performance(&consumer.host, game_id, None, "", 10) + .await + .unwrap(); + assert!(private.series.is_empty()); + // A selector without the current grant still answers empty: common history is not an error, + // it is simply unauthorized and absent. (The runtime catalog reports the denial explicitly.) + let selected_but_not_granted = recipes::list_performance( + &consumer.host, + game_id, + Some(recipes::performance_selector()), + "", + 10, + ) + .await + .unwrap(); + assert!(selected_but_not_granted.series.is_empty()); + + fixture + .shared_policies + .set_activation_grants( + &identity, + ActivationReadGrant::new( + [CommonDataCategory::GamePerformanceHistory], + std::iter::empty(), + ) + .unwrap(), + ) + .unwrap(); + let listed = recipes::list_performance( + &consumer.host, + game_id, + Some(recipes::performance_selector()), + "", + 10, + ) + .await + .unwrap(); + assert_eq!(listed.series.len(), 1); + let series = &listed.series[0]; + assert_eq!(series.series_id, published.report_id); + assert_eq!(series.game_id, game_id); + assert_eq!( + series.installation_id, + text!(performance["installation_id"]) + ); + // The host supplied the local computer context; the producer never named one. + assert_eq!(series.computer_context_id, recipes::LOCAL_COMPUTER); + assert_eq!(series.source, "overlay-frame-counter"); + assert_eq!(series.tool_name, "Example overlay"); + assert_eq!(series.samples.len(), 2); + // Another game stays empty even with the same grant and selector. + assert!( + recipes::list_performance( + &consumer.host, + "6", + Some(recipes::performance_selector()), + "", + 10, + ) + .await + .unwrap() + .series + .is_empty() + ); + + let aggregate = recipes::aggregate_performance( + &consumer.host, + &series.series_id, + "fps", + "average", + Some(recipes::performance_selector()), + ) + .await + .unwrap(); + assert_eq!( + aggregate.value, + performance["average_fps"].as_f64().unwrap() + ); + assert_eq!(aggregate.unit, text!(performance["metric_units"]["fps"])); + assert_eq!(aggregate.sample_count, 2); + + // Revocation fences the next explicit query and returns no records again. + fixture + .shared_policies + .clear_activation_grants(&identity) + .unwrap(); + assert!( + recipes::list_performance( + &consumer.host, + game_id, + Some(recipes::performance_selector()), + "", + 10, + ) + .await + .unwrap() + .series + .is_empty() + ); + + // Cleanup is explicit: ending the series removes the retained history and refuses a later + // batch, so a stopped collector cannot reopen it. + let ended_at = performance["samples"][1]["observed_at"].as_i64().unwrap(); + let ended = recipes::end_performance(&fixture.host, series_id, published.revision, 2, ended_at) + .await + .unwrap(); + assert_eq!(ended.outcome, MutationOutcome::Applied as i32); + assert_eq!( + recipes::publish_performance( + &fixture.host, + "performance-after-end", + ended.revision, + series_id, + game_id, + vec![recipes::sample(3, ended_at + 100, 60.0)], + ) + .await + .unwrap_err() + .code(), + Code::FailedPrecondition + ); + // Cleanup finishes the job: the retained series is gone, so a stopped collector's history + // cannot be read back or extended. + assert_eq!( + recipes::query_performance( + &fixture.host, + series_id, + ended_at - 1000, + ended_at + 1000, + 0, + None, + ) + .await + .unwrap_err() + .code(), + Code::NotFound + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn approved_save_folder_is_inspected_without_a_path_and_profiles_stay_owner_only() { + let contract = contract(); + let saves_contract = &contract["save_profiles"]; + let locations = &contract["locations"]; + let (fixture, saves) = Fixture::emulator(SAVE_AND_LOCATION).await; + let root = fixture.approve(INSTALLATION, "save", &saves).await; + + let mut new = profile( + text!(saves_contract["name"]), + text!(saves_contract["runtime_id"]), + vec![directory( + &root, + text!(saves_contract["directories"][0]["display_name"]), + &saves_contract["directories"][0]["naming_patterns"] + .as_array() + .unwrap() + .iter() + .map(|pattern| text!(pattern)) + .collect::>(), + )], + ); + new.format_id = text!(saves_contract["format_id"]).into(); + new.format_version = saves_contract["format_version"].as_u64().unwrap() as u32; + let created = fixture.make("example-save-profile", new).await.unwrap(); + assert_eq!(created.outcome, MutationOutcome::Applied as i32); + + // The owner reads the profile and its folder as a session-bound handle. + let read = recipes::read_save_profile(&fixture.host, "", &created.profile_id) + .await + .unwrap() + .profile + .unwrap(); + assert_eq!(read.name, text!(saves_contract["name"])); + assert_eq!( + read.installation_id, + text!(saves_contract["installation_id"]) + ); + assert_eq!(read.runtime_id, text!(saves_contract["runtime_id"])); + assert_eq!(read.format_id, text!(saves_contract["format_id"])); + assert_eq!(read.creator_plugin_id, "fixture.plugin"); + assert!(!read.directories[0].approved_resource_handle.is_empty()); + + // Inspection returns an opaque volume token and no filesystem path. + let inspected = recipes::inspect_location(&fixture.host, &root) + .await + .unwrap(); + let location = inspected.location.clone().unwrap(); + assert_eq!( + location.availability, + InspectionAvailability::Available as i32 + ); + assert!(!location.volume_identity_token.is_empty()); + assert!(!location.interface_type.is_empty()); + // The answer may describe the volume mount, but never the approved folder path. + assert!(!location.mount_point.contains(saves.to_str().unwrap())); + assert!(!format!("{inspected:?}").contains(saves.to_str().unwrap())); + + let measured = recipes::measure_location(&fixture.host, &root) + .await + .unwrap(); + assert_eq!( + ( + measured.logical_bytes, + measured.file_count, + measured.directory_count, + measured.complete, + ), + ( + locations["size"]["logical_bytes"].as_u64().unwrap(), + locations["size"]["file_count"].as_u64().unwrap(), + locations["size"]["directory_count"].as_u64().unwrap(), + true, + ) + ); + + // Save profiles stay owner-only: a common-category selector is an explicit unsupported answer + // rather than a projection of another plugin's folders. + assert_eq!( + recipes::list_save_profiles( + &fixture.host, + INSTALLATION, + Some(recipes::category_selector(CommonDataCategory::SaveProfiles)), + ) + .await + .unwrap_err() + .code(), + Code::Unimplemented + ); + let owned = recipes::list_save_profiles(&fixture.host, INSTALLATION, None) + .await + .unwrap(); + assert_eq!(owned.profiles.len(), 1); + assert_eq!(owned.profiles[0].profile_id, created.profile_id); +} + +#[tokio::test(flavor = "multi_thread")] +async fn one_shared_runtime_lists_several_content_identities_without_paths_or_handles() { + use crate::plugin_host::sharing_policy::ActivationReadGrant; + + let contract = contract(); + let catalog = &contract["runtime_catalog"]; + let target = TargetGameContext { + game_id: text!(catalog["game_id"]).into(), + installation_id: text!(catalog["installation_id"]).into(), + profile_id: "account-a".into(), + revision: "1".into(), + }; + let (fixture, _) = Fixture::approved_extension_game(RUNTIME, target).await; + let content_root = fixture.game_dir( + "example-shared-runtime", + &[("zelda.sfc", b"rom"), ("metroid.sfc", b"rom")], + ); + fixture.user_approving(&content_root); + let root = fixture + .root_handle(text!(catalog["installation_id"]), &["read"]) + .await; + let executable = fixture.child(&root, "zelda.sfc").await; + let zelda = fixture.child(&root, "zelda.sfc").await; + let metroid = fixture.child(&root, "metroid.sfc").await; + + let registered = fixture + .client() + .runtimes_register(RuntimeRegisterRequest { + mutation: Some(fixture.mutation("example-shared-runtime", 0)), + runtime: Some(RuntimeRecord { + id: text!(catalog["runtime_id"]).into(), + name: text!(catalog["runtime_name"]).into(), + version: text!(catalog["runtime_version"]).into(), + executable_handle: executable, + supported_formats: catalog["supported_formats"] + .as_array() + .unwrap() + .iter() + .map(|format| text!(format).to_owned()) + .collect(), + platform: std::env::consts::OS.into(), + argument_template: vec![RuntimeArgumentProto { + value: Some(RuntimeArgumentValue::ContentPath( + gamenode_plugin_sdk::proto::ContentPathArgument {}, + )), + }], + extensions: [( + "org.example.compatibility".into(), + ExtensionPayload { + schema_id: "org.example.compatibility.v1".into(), + schema_version: 1, + schema_digest: vec![3; 32], + data: Some(gamenode_plugin_sdk::prost_types::Struct { + fields: [( + "console".into(), + gamenode_plugin_sdk::prost_types::Value { + kind: Some( + gamenode_plugin_sdk::prost_types::value::Kind::StringValue( + "snes".into(), + ), + ), + }, + )] + .into(), + }), + }, + )] + .into(), + ..Default::default() + }), + }) + .await + .unwrap() + .into_inner(); + assert_eq!(registered.outcome, MutationOutcome::Applied as i32); + + for (index, (content_id, handle)) in [ + text!(&catalog["content_ids"][0]), + text!(&catalog["content_ids"][1]), + ] + .into_iter() + .zip([zelda, metroid]) + .enumerate() + { + let applied = fixture + .client() + .games_register_content(ContentRegistrationRequest { + mutation: Some(fixture.mutation(&format!("example-content-{index}"), 0)), + game_id: text!(catalog["game_id"]).into(), + installation_id: text!(catalog["installation_id"]).into(), + content_handle: handle, + content_kind: text!(catalog["content_kind"]).into(), + runtime_id: text!(catalog["runtime_id"]).into(), + supported_platforms: vec![std::env::consts::OS.into()], + content_id: content_id.into(), + }) + .await + .unwrap() + .into_inner(); + assert_eq!(applied.outcome, MutationOutcome::Applied as i32); + } + + let consumer = consumer_session_with_grants( + &fixture, + &[ + cap::LIBRARY_READ, + cap::LIBRARY_READ_ALL, + cap::GAME_RUNTIME_READ, + cap::FILES_READ, + ], + ) + .await; + let context = consumer.host.resource_context().unwrap().clone(); + let identity = super::data::authenticated_identity(&fixture, &context); + + // Without the category grant the explicit selector is refused. + assert_eq!( + recipes::list_shared_runtimes(&consumer.host) + .await + .unwrap_err() + .code(), + Code::PermissionDenied + ); + fixture + .shared_policies + .set_activation_grants( + &identity, + ActivationReadGrant::new( + [ + CommonDataCategory::RuntimeCatalog, + CommonDataCategory::ContentAvailability, + ], + std::iter::empty(), + ) + .unwrap(), + ) + .unwrap(); + + let listed = recipes::list_shared_runtimes(&consumer.host).await.unwrap(); + assert_eq!(listed.runtimes.len(), 1); + let runtime = &listed.runtimes[0]; + assert_eq!(runtime.id, text!(catalog["runtime_id"])); + assert_eq!(runtime.name, text!(catalog["runtime_name"])); + // A shared projection never carries the producer's executable handle. + assert_eq!( + runtime.executable_handle, + text!(catalog["executable_handle_in_shared_projection"]) + ); + assert_eq!( + runtime.provenance.as_ref().unwrap().producer_plugin_id, + "fixture.plugin" + ); + + let availability = + recipes::content_availability(&consumer.host, text!(catalog["installation_id"])) + .await + .unwrap() + .entry + .unwrap(); + let mut content_ids = availability + .runtime_availability + .iter() + .map(|row| row.content_id.as_str()) + .collect::>(); + content_ids.sort_unstable(); + assert_eq!(content_ids, ["rom:metroid", "rom:zelda"]); + for row in &availability.runtime_availability { + assert_eq!(row.runtime_id, text!(catalog["runtime_id"])); + assert_eq!(row.content_kind, text!(catalog["content_kind"])); + assert_eq!(row.publisher_id, "fixture.plugin"); + } + assert!(!format!("{availability:?}").contains(content_root.to_str().unwrap())); + + // Revocation closes the same call again. + fixture + .shared_policies + .clear_activation_grants(&identity) + .unwrap(); + assert_eq!( + recipes::list_shared_runtimes(&consumer.host) + .await + .unwrap_err() + .code(), + Code::PermissionDenied + ); +} diff --git a/crates/app/src/plugin_host/resources/tests/sdk_extension_data.rs b/crates/app/src/plugin_host/resources/tests/sdk_extension_data.rs new file mode 100644 index 000000000..c037c0b9b --- /dev/null +++ b/crates/app/src/plugin_host/resources/tests/sdk_extension_data.rs @@ -0,0 +1,539 @@ +//! Hybrid records, opaque envelopes and custom datasets: the Rust example recipes against the +//! real fixture host. + +use std::collections::{BTreeSet, HashMap}; + +use gamenode_plugin_sdk::proto::{ + CommonDataCategory, CommonDataSelector, DataListRequest, DomainGetRequest, DomainListRequest, + ExtensionPatch, MutationContext, MutationOutcome, PageRequest, RuntimeRegisterRequest, + RuntimeUpdateRequest, ServiceContext, +}; +use serde_json::Value; + +use gamenode_plugin_protocol::WireError; + +use super::data::{authenticated_identity, consumer_session_with_grants}; +use super::*; + +#[path = "../../../../../plugin-sdk/examples/extension_data_recipes.rs"] +mod recipes; + +const CONTRACT: &str = + include_str!("../../../../../plugin-protocol/contracts/data_exchange_fixtures.json"); + +fn contract() -> Value { + serde_json::from_str(CONTRACT).unwrap() +} + +macro_rules! text { + ($value:expr) => { + $value.as_str().unwrap() + }; +} + +fn mutation(context: &ServiceContext, key: &str, expected_revision: u64) -> MutationContext { + MutationContext { + context: Some(context.clone()), + operation_id: String::new(), + idempotency_key: key.into(), + expected_revision, + } +} + +/// A third-party plugin registered under the example identity the recipes use. +async fn example_producer(fixture: &Fixture, grants: &[&'static str]) -> Session { + let mut capabilities = vec![cap::CONTEXT]; + capabilities.extend_from_slice(grants); + fixture + .api + .register(Registration { + provider_id: "org.example".into(), + plugin_id: "org.example".into(), + kind: crate::plugin_host::provider::RegistrationKind::Provider, + declared_developer: "Example developer".into(), + package_digest: vec![6; 32], + origin: RegistrationOrigin::ThirdParty { + publisher_fingerprint: "ab".repeat(32), + }, + capabilities: capabilities.iter().map(|cap| (*cap).into()).collect(), + shared_catalog: false, + playtime: Default::default(), + services: Arc::new(NoServices), + }) + .unwrap(); + let launch = fixture.api.begin_launch("org.example").unwrap(); + let credential = (0..launch.credential.len()) + .step_by(2) + .map(|index| u8::from_str_radix(&launch.credential[index..index + 2], 16).unwrap()) + .collect(); + let session = Session::open_with_options( + Launch { + endpoint: fixture.endpoint.clone(), + credential, + operation_id: "example-producer-launch".into(), + }, + "org.example", + "org.example", + "1.0", + &capabilities, + SessionOptions { + min_api_major: 1, + min_api_minor: cap::THIRD_PARTY_API_MINOR, + max_api_major: 1, + max_api_minor: gamenode_plugin_protocol::API_MINOR, + ..SessionOptions::default() + }, + ) + .await + .unwrap(); + launch.ready.await.unwrap(); + session +} + +#[tokio::test(flavor = "multi_thread")] +async fn hybrid_runtime_keeps_the_future_namespace_and_projects_only_known_fields() { + use crate::plugin_host::sharing_policy::ActivationReadGrant; + use gamenode_plugin_sdk::proto::{ + ExtensionNamespacePatch, extension_namespace_patch::Operation, + }; + + // The fixture plugin owns the namespaces the real host accepts; the example's generic + // identities are asserted locally below. + const HOST_KNOWN: &str = "fixture.plugin.runtime"; + const HOST_FUTURE: &str = "fixture.plugin.future-runtime"; + + let contract = contract(); + let extension = &contract["extension"]; + let grants = [ + cap::FILES_READ, + cap::GAME_RUNTIME_CREATE, + cap::GAME_RUNTIME_READ, + cap::GAME_RUNTIME_UPDATE, + ]; + let fixture = Fixture::new(&grants).await; + fixture.with_host(); + let dir = fixture.game_dir("hybrid-runtime", &[("emulator", b"binary")]); + fixture.library_in(&[("fixture:1", Some(3), "Hybrid Game", &dir)]); + let root = fixture.approve("id-fixture:1", "installation", &dir).await; + let executable = fixture.child(&root, "emulator").await; + // Only the namespace this plugin declares has a packaged descriptor. The future namespace is + // optional and must stay usable without one. + let mut descriptor = recipes::known_descriptor(); + descriptor.namespace = HOST_KNOWN.into(); + descriptor.schema_id = "fixture.plugin.runtime.v1".into(); + fixture + .api + .set_extension_schemas( + "fixture", + "fixture.plugin", + &"ab".repeat(32), + vec![descriptor], + ) + .unwrap(); + let context = fixture.context(); + + // Local schema handling with the example's own identities: a v9 payload is not validated as + // v1, and a declared field is the only thing projection keeps. + let example = recipes::hybrid_runtime(); + assert_eq!( + example.extensions[recipes::KNOWN_NAMESPACE].schema_id, + text!(extension["known_schema_id"]) + ); + assert_eq!( + example.extensions[recipes::FUTURE_NAMESPACE].schema_version, + extension["future_schema_version"].as_u64().unwrap() as u32 + ); + assert_eq!(recipes::reject_future_namespace(&example), Err(WireError)); + let projected = recipes::project_known_namespace( + &example, + &BTreeSet::from([text!(extension["known_field"]).into()]), + ) + .unwrap(); + assert_eq!( + projected.data.unwrap().fields.keys().collect::>(), + [text!(extension["known_field"])] + ); + + // The host accepts the hybrid record: the known namespace matches its packaged descriptor and + // the future namespace is carried opaquely. + let mut record = example.clone(); + record.executable_handle = executable; + record.platform = std::env::consts::OS.into(); + let known = record.extensions.remove(recipes::KNOWN_NAMESPACE).unwrap(); + let future = record.extensions.remove(recipes::FUTURE_NAMESPACE).unwrap(); + let mut known = known; + known.schema_id = "fixture.plugin.runtime.v1".into(); + let mut future = future; + future.schema_id = "fixture.plugin.future-runtime.v9".into(); + record.extensions = HashMap::from([(HOST_KNOWN.into(), known), (HOST_FUTURE.into(), future)]); + let registered = fixture + .client() + .runtimes_register(RuntimeRegisterRequest { + mutation: Some(fixture.mutation("hybrid-register", 0)), + runtime: Some(record.clone()), + }) + .await + .unwrap() + .into_inner(); + assert_eq!(registered.outcome, MutationOutcome::Applied as i32); + let current = registered.runtime.unwrap(); + assert_eq!(current.revision, 1); + + // The owner sees both namespaces, including the one it cannot interpret. + let owned = fixture + .client() + .runtimes_get(DomainGetRequest { + context: Some(context.clone()), + resource_id: current.id.clone(), + expected_revision: 0, + shared_records: None, + }) + .await + .unwrap() + .into_inner() + .runtime + .unwrap(); + assert_eq!( + owned.extensions[HOST_FUTURE], + record.extensions[HOST_FUTURE] + ); + + // An owner update from a client that understands only the known namespace changes that + // namespace and the typed name; the host keeps the future namespace intact. + let mut patch = recipes::known_namespace_patch(current.revision); + patch.namespaces[0].namespace = HOST_KNOWN.into(); + match patch.namespaces[0].operation.as_mut().unwrap() { + Operation::Set(payload) => payload.schema_id = "fixture.plugin.runtime.v1".into(), + Operation::Remove(_) => unreachable!(), + } + let mut proposed = current.clone(); + proposed.name = "Example Runtime (handheld)".into(); + let updated = fixture + .client() + .runtimes_update(RuntimeUpdateRequest { + mutation: Some(fixture.mutation("hybrid-patch", current.revision)), + runtime: Some(proposed), + field_mask: Vec::new(), + extension_patch: Some(patch), + }) + .await + .unwrap() + .into_inner(); + assert_eq!(updated.outcome, MutationOutcome::Applied as i32); + let updated = updated.runtime.unwrap(); + assert_eq!(updated.revision, current.revision + 1); + assert_eq!(updated.name, "Example Runtime (handheld)"); + assert_eq!( + updated.extensions[HOST_FUTURE], + record.extensions[HOST_FUTURE] + ); + assert_eq!( + updated.extensions[HOST_KNOWN].data.as_ref().unwrap().fields + [text!(extension["known_field"])] + .kind, + Some(gamenode_plugin_sdk::prost_types::value::Kind::StringValue( + "handheld".into() + )) + ); + + // A stale patch is an explicit conflict, not a partial write. + let stale = fixture + .client() + .runtimes_update(RuntimeUpdateRequest { + mutation: Some(fixture.mutation("hybrid-stale", current.revision)), + runtime: Some(current.clone()), + field_mask: Vec::new(), + extension_patch: Some(ExtensionPatch { + expected_revision: current.revision, + typed_field_mask: vec!["name".into()], + namespaces: vec![ExtensionNamespacePatch { + namespace: HOST_KNOWN.into(), + operation: Some(Operation::Set(record.extensions[HOST_KNOWN].clone())), + }], + }), + }) + .await + .unwrap() + .into_inner(); + assert_eq!(stale.outcome, MutationOutcome::RevisionConflict as i32); + + // A consumer with the runtime-catalog grant sees a safe shared projection: producer + // provenance and the validated known namespace, no executable handle and no unknown namespace. + let consumer = consumer_session_with_grants( + &fixture, + &[cap::LIBRARY_READ, cap::GAME_RUNTIME_READ, cap::FILES_READ], + ) + .await; + let consumer_context = consumer.host.resource_context().unwrap().clone(); + let identity = authenticated_identity(&fixture, &consumer_context); + fixture + .shared_policies + .clear_activation_grants(&identity) + .unwrap(); + let selector = CommonDataSelector { + categories: vec![CommonDataCategory::RuntimeCatalog as i32], + selected_record_ids: Vec::new(), + }; + assert_eq!( + consumer + .host + .resource_client() + .runtimes_list(DomainListRequest { + page: Some(PageRequest { + context: Some(consumer_context.clone()), + page_size: 10, + common_data_categories: Some(selector.clone()), + ..Default::default() + }), + ..Default::default() + }) + .await + .unwrap_err() + .code(), + Code::PermissionDenied + ); + fixture + .shared_policies + .set_activation_grants( + &identity, + ActivationReadGrant::new([CommonDataCategory::RuntimeCatalog], std::iter::empty()) + .unwrap(), + ) + .unwrap(); + let shared = consumer + .host + .resource_client() + .runtimes_list(DomainListRequest { + page: Some(PageRequest { + context: Some(consumer_context), + page_size: 10, + common_data_categories: Some(selector), + ..Default::default() + }), + ..Default::default() + }) + .await + .unwrap() + .into_inner(); + assert_eq!(shared.runtimes.len(), 1); + let shared = &shared.runtimes[0]; + assert_eq!(shared.id, current.id); + assert!(shared.executable_handle.is_empty()); + assert_eq!( + shared.provenance.as_ref().unwrap().producer_plugin_id, + "fixture.plugin" + ); + assert_eq!( + shared.extensions[HOST_KNOWN].schema_id, + "fixture.plugin.runtime.v1" + ); + // The shared catalog carries the bounded extension set as an opaque envelope: a consumer must + // not interpret a namespace it has no descriptor for, and Core projects no typed authority + // from it. The owner record is unchanged and the shared record has no executable handle. + assert_eq!( + shared.extensions[HOST_FUTURE], + record.extensions[HOST_FUTURE] + ); + assert!( + format!("{shared:?}").find("emulator").is_none(), + "the shared projection never discloses the executable handle or a path" + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn custom_struct_and_opaque_envelopes_project_only_granted_fields() { + use crate::plugin_host::sharing_policy::{SharingClass, SourceRecipientPolicy}; + + let contract = contract(); + let extension = &contract["extension"]; + let fixture = Fixture::new(&[]).await; + let producer = example_producer(&fixture, &[cap::DATA_PUBLISH]).await; + let producer_context = producer.host.resource_context().unwrap().clone(); + let consumer = consumer_session_with_grants(&fixture, &[]).await; + let consumer_context = consumer.host.resource_context().unwrap().clone(); + let source = authenticated_identity(&fixture, &producer_context); + let recipient = authenticated_identity(&fixture, &consumer_context); + let policy = |dataset: &str, fields: &[&str]| { + SourceRecipientPolicy::new( + source.clone(), + recipient.clone(), + SharingClass::Custom, + dataset.into(), + fields.iter().map(|field| (*field).to_string()), + true, + false, + ) + .unwrap() + }; + + // The custom envelope is versioned and names only data. The example's fields match the shared + // fixture, and Core does not interpret their meaning. + let mut custom = recipes::custom_dataset_wire_shape(); + assert_eq!(custom.dataset_id, text!(extension["custom_dataset_id"])); + assert_eq!(custom.schema_id, text!(extension["custom_schema_id"])); + assert_eq!( + custom.schema_version, + extension["custom_schema_version"].as_u64().unwrap() as u32 + ); + custom.mutation = Some(mutation(&producer_context, "custom-notes", 0)); + let published = producer + .host + .resource_client() + .data_publish(custom) + .await + .unwrap() + .into_inner(); + assert_eq!(published.outcome, MutationOutcome::Applied as i32); + + let list = |context: &ServiceContext, dataset: &str| DataListRequest { + page: Some(PageRequest { + context: Some(context.clone()), + page_size: 10, + ..Default::default() + }), + dataset_id: dataset.into(), + ..Default::default() + }; + fixture + .shared_policies + .set_source_recipient_policy(policy( + text!(extension["custom_dataset_id"]), + &[text!(extension["projection_paths"][0])], + )) + .unwrap(); + let projected = consumer + .host + .resource_client() + .data_list(list( + &consumer_context, + text!(extension["custom_dataset_id"]), + )) + .await + .unwrap() + .into_inner(); + assert_eq!(projected.records.len(), 1); + let record = &projected.records[0]; + assert_eq!(record.record_id, published.record_id); + let fields = record.value.as_ref().unwrap().fields.clone(); + assert_eq!( + fields.keys().cloned().collect::>(), + BTreeSet::from([text!(extension["projection_paths"][0]).to_string()]) + ); + assert!(!fields.contains_key(text!(extension["custom_fields"]["note"]))); + // The example's local projection keeps the same field; it never creates authority. + assert_eq!( + recipes::project_custom_dataset( + record.value.as_ref().unwrap(), + &BTreeSet::from([text!(extension["projection_paths"][0]).to_string()]), + ) + .unwrap(), + record.value.clone().unwrap() + ); + + // A later schema version is an opaque label for custom data: the same grant still returns the + // same field, and the version is retained for the owner. + let mut future = recipes::custom_dataset_wire_shape_with_version( + extension["unsupported_schema_version"].as_u64().unwrap() as u32, + ); + future.mutation = Some(mutation(&producer_context, "custom-notes-v10", 0)); + future.sequence = 2; + future.source_observation_id = "game-notes-observation-v10".into(); + let published = producer + .host + .resource_client() + .data_publish(future) + .await + .unwrap() + .into_inner(); + assert_eq!(published.outcome, MutationOutcome::Applied as i32); + let projected_again = consumer + .host + .resource_client() + .data_list(list( + &consumer_context, + text!(extension["custom_dataset_id"]), + )) + .await + .unwrap() + .into_inner(); + assert_eq!(projected_again.records.len(), 2); + assert!(projected_again.records.iter().all(|record| { + record.schema_version == extension["unsupported_schema_version"].as_u64().unwrap() as u32 + || record.schema_version == 2 + })); + + // Opaque bytes need their own explicit grant and arrive whole; no Struct field is invented. + let mut opaque = recipes::opaque_dataset_wire_shape(); + assert_eq!(opaque.opaque_payload, vec![0, 1, 2, 255]); + opaque.mutation = Some(mutation(&producer_context, "custom-notes-binary", 0)); + let published = producer + .host + .resource_client() + .data_publish(opaque) + .await + .unwrap() + .into_inner(); + assert_eq!(published.outcome, MutationOutcome::Applied as i32); + let without_grant = consumer + .host + .resource_client() + .data_list(list( + &consumer_context, + text!(extension["opaque_dataset_id"]), + )) + .await + .unwrap() + .into_inner(); + assert!(without_grant.records.is_empty()); + fixture + .shared_policies + .set_source_recipient_policy(policy( + text!(extension["opaque_dataset_id"]), + &[text!(extension["opaque_grant_field"])], + )) + .unwrap(); + let with_grant = consumer + .host + .resource_client() + .data_list(list( + &consumer_context, + text!(extension["opaque_dataset_id"]), + )) + .await + .unwrap() + .into_inner(); + assert_eq!(with_grant.records.len(), 1); + let bytes = &with_grant.records[0]; + assert_eq!(bytes.opaque_payload, vec![0, 1, 2, 255]); + assert!( + bytes + .value + .as_ref() + .is_none_or(|value| value.fields.is_empty()) + ); + + // Revoking the custom grant fences the next list immediately. + fixture + .shared_policies + .revoke_source_recipient_policy( + &source, + &recipient, + SharingClass::Custom, + text!(extension["custom_dataset_id"]), + ) + .unwrap(); + assert!( + consumer + .host + .resource_client() + .data_list(list( + &consumer_context, + text!(extension["custom_dataset_id"]) + )) + .await + .unwrap() + .into_inner() + .records + .is_empty() + ); +} diff --git a/crates/app/src/plugin_host/resources/tests/sdk_utilities.rs b/crates/app/src/plugin_host/resources/tests/sdk_utilities.rs new file mode 100644 index 000000000..eaaf5781e --- /dev/null +++ b/crates/app/src/plugin_host/resources/tests/sdk_utilities.rs @@ -0,0 +1,721 @@ +//! The SDK's utility helpers (storage, files, network, notifications) and the published recipes +//! against the same fixture host as the raw gRPC tests (task 6.5). Every call is made through the +//! SDK and again by hand, and the answers must be the same. A write is compared by replaying it +//! raw under the SDK's idempotency key: the host only returns the original outcome for a request +//! that is identical, so a match proves the SDK sent exactly what the hand-written call sends. + +use std::time::Duration as StdDuration; + +use gamenode_plugin_sdk::{ + Durability, Fetch, Notice, Outcome, Resources, Severity, Written, idempotency_key, +}; + +use super::*; + +#[path = "../../../../../plugin-sdk/examples/utility_recipes.rs"] +mod recipes; + +const STORAGE: &[&str] = &[ + cap::STORAGE_READ, + cap::STORAGE_WRITE, + cap::STORAGE_DELETE, + cap::STORAGE_PERSIST, +]; +const FILES: &[&str] = &[cap::FILES_READ, cap::FILES_WRITE, cap::FILES_DELETE]; +const NETWORK: &[&str] = &[cap::NETWORK_FETCH]; +const NOTICES: &[&str] = &[cap::NOTIFICATIONS_PUBLISH]; + +fn sdk(fixture: &Fixture) -> Resources { + fixture.host.resources().expect("an API 1.6 session") +} + +fn raw_written(reply: MutationReply) -> Written { + Written::try_from(reply).unwrap() +} + +// ---- Storage ---- + +#[tokio::test] +async fn storage_helpers_equal_the_raw_calls() { + let fixture = Fixture::new(STORAGE).await; + let sdk = sdk(&fixture); + + // Absent key: not an error, revision 0. + let absent = sdk.storage_get("settings").await.unwrap(); + let raw = fixture.load("settings").await.unwrap(); + assert!(!absent.found && absent.durability.is_none()); + assert_eq!((absent.revision, absent.found), (raw.revision, raw.found)); + + // A write through the SDK, then the same request by hand under the SDK's key: the host + // returns the original outcome, which it only does for an identical request. + let key = idempotency_key(); + let put = sdk + .storage_put( + "settings", + 0, + &key, + b"{\"a\":1}".to_vec(), + Durability::Persistent, + Some(StdDuration::from_secs(3600)), + ) + .await + .unwrap(); + assert_eq!((put.revision, put.outcome), (1, Outcome::Applied)); + assert_eq!(put.durability, Some(Durability::Persistent)); + assert!(put.usage_bytes > 0 && put.quota_bytes >= put.usage_bytes); + let replay = fixture + .put_value( + "settings", + b"{\"a\":1}", + StorageDurability::Persistent, + 3600, + 0, + &key, + ) + .await + .unwrap(); + assert_eq!( + ( + replay.revision, + replay.usage_bytes, + replay.quota_bytes, + replay.expires_at + ), + ( + put.revision, + put.usage_bytes, + put.quota_bytes, + put.expires_at + ) + ); + assert_eq!(replay.outcome, MutationOutcome::Applied as i32); + + let stored = sdk.storage_get("settings").await.unwrap(); + let raw = fixture.load("settings").await.unwrap(); + assert_eq!( + (stored.value.clone(), stored.revision, stored.expires_at), + (raw.value.clone(), raw.revision, raw.expires_at) + ); + assert_eq!(stored.durability, Some(Durability::Persistent)); + assert_eq!(stored.expires_at, put.expires_at); + + // A stale revision is an answer, not an error. + let conflict = sdk + .storage_put( + "settings", + 0, + &idempotency_key(), + b"x".to_vec(), + Durability::SessionOnly, + None, + ) + .await + .unwrap(); + assert_eq!( + (conflict.outcome, conflict.revision), + (Outcome::RevisionConflict, 1) + ); + + // Delete, then the same delete by hand: same outcome and revision. + let key = idempotency_key(); + let deleted = sdk.storage_delete("settings", 1, &key).await.unwrap(); + assert_eq!(deleted.outcome, Outcome::Applied); + assert_eq!( + raw_written(fixture.remove("settings", 1, &key).await.unwrap()), + deleted + ); + assert!(!sdk.storage_get("settings").await.unwrap().found); + let again = sdk + .storage_delete("settings", 0, &idempotency_key()) + .await + .unwrap(); + assert_eq!(again.outcome, Outcome::AlreadyApplied); +} + +#[tokio::test] +async fn storage_refusals_are_the_hosts_own() { + // Durable writes need `storage.persist`; the host never turns them into a volatile success. + let fixture = Fixture::new(&[cap::STORAGE_READ, cap::STORAGE_WRITE]).await; + let sdk = sdk(&fixture); + let denied = sdk + .storage_put( + "k", + 0, + &idempotency_key(), + b"v".to_vec(), + Durability::Persistent, + None, + ) + .await + .unwrap_err(); + let raw = fixture + .store("k", b"v", StorageDurability::Persistent, 0) + .await + .unwrap_err(); + assert_eq!(denied.code(), Code::PermissionDenied); + assert_eq!( + (denied.code(), denied.message()), + (raw.code(), raw.message()) + ); + assert!(!sdk.storage_get("k").await.unwrap().found); + // Session-only is allowed with `storage.write` alone, and says so. + let session = sdk + .storage_put( + "k", + 0, + &idempotency_key(), + b"v".to_vec(), + Durability::SessionOnly, + None, + ) + .await + .unwrap(); + assert_eq!(session.durability, Some(Durability::SessionOnly)); + + // A value over the limit changes nothing. + let big = vec![0u8; MAX_VALUE_BYTES + 1]; + let status = sdk + .storage_put( + "big", + 0, + &idempotency_key(), + big, + Durability::SessionOnly, + None, + ) + .await + .unwrap_err(); + assert_eq!(status.code(), Code::InvalidArgument); +} + +use crate::plugin_host::storage::MAX_VALUE_BYTES; + +#[tokio::test(flavor = "multi_thread")] +async fn the_storage_recipes_read_modify_write_and_recover_from_a_conflict() { + let fixture = Fixture::new(STORAGE).await; + let sdk = sdk(&fixture); + assert_eq!(recipes::recall(&sdk, "n").await.unwrap(), None); + + let first = recipes::update(&sdk, "n", Durability::Persistent, None, |old| { + assert!(old.is_none()); + b"1".to_vec() + }) + .await + .unwrap(); + assert_eq!(first.outcome, Outcome::Applied); + assert_eq!( + recipes::recall(&sdk, "n").await.unwrap(), + Some(b"1".to_vec()) + ); + + // Another writer gets in between the read and the write: the first attempt conflicts, the + // recipe reads again, and `change` sees what the other writer wrote. + let mut calls = 0; + let merged = recipes::update(&sdk, "n", Durability::Persistent, None, |old| { + calls += 1; + if calls == 1 { + // Runs after the recipe's read, before its write. + let raw = futures_block(fixture.store("n", b"other", StorageDurability::Persistent, 1)); + raw.unwrap(); + } + let mut next = old.unwrap(); + next.extend_from_slice(b"+mine"); + next + }) + .await + .unwrap(); + assert_eq!(merged.outcome, Outcome::Applied); + assert_eq!(calls, 2); + assert_eq!( + recipes::recall(&sdk, "n").await.unwrap(), + Some(b"other+mine".to_vec()) + ); + + // A value that keeps changing is reported, not overwritten. + let moving = recipes::update(&sdk, "n", Durability::Persistent, None, |old| { + let current = fixture_revision(&fixture); + futures_block(fixture.store("n", b"again", StorageDurability::Persistent, current)) + .unwrap(); + old.unwrap() + }) + .await + .unwrap_err(); + assert_eq!(moving.code(), Code::Aborted); + + // Forget removes it, and forgetting what is not there succeeds. + assert_eq!( + recipes::forget(&sdk, "n").await.unwrap().outcome, + Outcome::Applied + ); + assert_eq!(recipes::recall(&sdk, "n").await.unwrap(), None); + assert_eq!( + recipes::forget(&sdk, "n").await.unwrap().outcome, + Outcome::AlreadyApplied + ); +} + +/// Runs a fixture call from inside a synchronous recipe callback. +fn futures_block(future: impl std::future::Future) -> T { + tokio::task::block_in_place(|| tokio::runtime::Handle::current().block_on(future)) +} + +fn fixture_revision(fixture: &Fixture) -> u64 { + futures_block(fixture.load("n")).unwrap().revision +} + +// ---- Files ---- + +#[tokio::test] +async fn file_helpers_equal_the_raw_calls() { + let fixture = Fixture::new(FILES).await; + let dir = fixture.game_dir( + "portal", + &[ + ("readme.txt", b"hello world"), + ("saves/slot1.sav", b"s1"), + ("big.bin", &vec![7u8; 10_000]), + ], + ); + fixture.library_in(&[("fixture:1", Some(7), "Portal", &dir)]); + fixture.user_approving(&dir); + let sdk = sdk(&fixture); + + let key = idempotency_key(); + let handles = sdk + .files_request_access("id-fixture:1", &["read", "write", "delete"], &[], &key) + .await + .unwrap(); + let raw = fixture + .request_access("id-fixture:1", &["read", "write", "delete"], &[]) + .await + .unwrap(); + // Handles are sealed per call, so compare what the plugin can tell apart. + let describe = |handles: &[FileHandle]| -> Vec<(String, String, bool)> { + handles + .iter() + .map(|h| (h.display_name.clone(), h.resource_kind.clone(), h.writable)) + .collect() + }; + assert_eq!(describe(&handles), describe(&raw.handles)); + let root = &handles[0].handle; + + // Listing: every page is walked, in the host's order, with the same names and sizes. + let listed = sdk.files_list(root).await.unwrap(); + let by_hand = fixture.ls(root).await.unwrap(); + let summary = |entries: &[FileEntry]| -> Vec<(String, bool, u64)> { + entries + .iter() + .map(|e| (e.name.clone(), e.directory, e.size_bytes)) + .collect() + }; + assert_eq!(summary(&listed), summary(&by_hand.entries)); + assert_eq!( + summary(&listed), + [ + ("big.bin".to_owned(), false, 10_000), + ("readme.txt".to_owned(), false, 11), + ("saves".to_owned(), true, 0) + ] + ); + + // Reading: a chunk equals the raw chunk, and the whole file is assembled from chunks. + let readme = listed.iter().find(|e| e.name == "readme.txt").unwrap(); + let chunk = sdk.files_read(&readme.handle, 6, 5).await.unwrap(); + let raw_chunk = fixture.cat(&readme.handle, 6, 5).await.unwrap(); + assert_eq!(chunk, raw_chunk); + assert_eq!(chunk.contents, b"world"); + let big = listed.iter().find(|e| e.name == "big.bin").unwrap(); + assert_eq!( + sdk.files_read_all(&big.handle, 10_000).await.unwrap(), + vec![7u8; 10_000] + ); + // A file longer than the limit is refused whole, never returned in part. + let over = sdk.files_read_all(&big.handle, 9_999).await.unwrap_err(); + assert_eq!(over.code(), Code::ResourceExhausted); + + // Creating a file, then the same request by hand under the SDK's key. + let key = idempotency_key(); + let created = sdk + .files_create(root, "notes.txt", b"first".to_vec(), &key) + .await + .unwrap(); + assert_eq!(created.outcome, Outcome::Applied); + let replay = fixture + .write_to(root, "notes.txt", b"first", 0, true, &key) + .await + .unwrap(); + assert_eq!(raw_written(replay), created); + assert_eq!(std::fs::read(dir.join("notes.txt")).unwrap(), b"first"); + + // Writing into the existing file by handle, and the same request by hand. + let key = idempotency_key(); + let written = sdk + .files_write(&created.resource_id, 5, b"+more".to_vec(), false, &key) + .await + .unwrap(); + let replay = fixture + .write_to(&created.resource_id, "", b"+more", 5, false, &key) + .await + .unwrap(); + assert_eq!(raw_written(replay), written); + assert_eq!(std::fs::read(dir.join("notes.txt")).unwrap(), b"first+more"); + + // Deleting, and the same delete by hand. + let key = idempotency_key(); + let deleted = sdk.files_delete(&created.resource_id, &key).await.unwrap(); + assert_eq!( + raw_written(fixture.rm(&created.resource_id, &key).await.unwrap()), + deleted + ); + assert!(!dir.join("notes.txt").exists()); + + // A forged handle and a directory read are the host's own refusals. + for bad in ["forged", ""] { + let via_sdk = sdk.files_read(bad, 0, 1).await.unwrap_err(); + let raw = fixture.cat(bad, 0, 1).await.unwrap_err(); + assert_eq!( + (via_sdk.code(), via_sdk.message()), + (raw.code(), raw.message()), + "{bad:?}" + ); + } +} + +#[tokio::test] +async fn the_file_recipes_find_read_and_save_by_name_and_name_what_to_do_next() { + let fixture = Fixture::new(FILES).await; + let dir = fixture.game_dir("portal", &[("slot1.sav", b"s1")]); + fixture.library_in(&[("fixture:1", Some(7), "Portal", &dir)]); + let sdk = sdk(&fixture); + + // No approval dialog: ask again later. Declined: do not ask again at once. + assert!(matches!( + recipes::open_installation(&sdk, "id-fixture:1", &["read"]).await, + Err(recipes::Access::AskAgain) + )); + let user = fixture.user_approving(&dir); + user.consent.store(false, Ordering::SeqCst); + assert!(matches!( + recipes::open_installation(&sdk, "id-fixture:1", &["read"]).await, + Err(recipes::Access::Declined) + )); + user.consent.store(true, Ordering::SeqCst); + + // Read first; a read-only approval gives no write, and widening asks the user again. + let root = recipes::open_installation(&sdk, "id-fixture:1", &["read"]) + .await + .unwrap(); + assert_eq!( + recipes::read_named(&sdk, &root, "slot1.sav", 1024) + .await + .unwrap(), + Some(b"s1".to_vec()) + ); + assert_eq!( + recipes::read_named(&sdk, &root, "nope.sav", 1024) + .await + .unwrap(), + None + ); + let too_small = recipes::read_named(&sdk, &root, "slot1.sav", 1) + .await + .unwrap_err(); + assert_eq!(too_small.code(), Code::ResourceExhausted); + let no_write = recipes::save_named(&sdk, &root, "slot2.sav", b"s2") + .await + .unwrap_err(); + assert_eq!(no_write.code(), Code::PermissionDenied); + assert!(!dir.join("slot2.sav").exists()); + + let asked = user.asked(); + let root = recipes::open_installation(&sdk, "id-fixture:1", &["read", "write"]) + .await + .unwrap(); + assert_eq!(user.asked(), asked + 1); + let handle = recipes::save_named(&sdk, &root, "slot2.sav", b"s2") + .await + .unwrap(); + assert!(!handle.is_empty()); + assert_eq!(std::fs::read(dir.join("slot2.sav")).unwrap(), b"s2"); + // A name that is not one plain component never reaches the disk. + let escape = recipes::save_named(&sdk, &root, "../escape.sav", b"x") + .await + .unwrap_err(); + assert_eq!(escape.code(), Code::InvalidArgument); + assert!(!dir.parent().unwrap().join("escape.sav").exists()); +} + +// ---- Network ---- + +#[tokio::test] +async fn fetch_helpers_equal_the_raw_call() { + let fixture = Fixture::new(NETWORK).await; + fixture.user_approving_origins(&["https://api.example.com"]); + let sdk = sdk(&fixture); + + let fetched = sdk + .network_fetch( + &Fetch::get("https://api.example.com/v1/items?limit=3") + .method("POST", b"{\"a\":1}".to_vec()) + .header("Content-Type", "application/json") + .max_response_bytes(2048) + .timeout(StdDuration::from_millis(1500)), + ) + .await + .unwrap(); + let raw = fixture + .fetch_with( + "https://api.example.com/v1/items?limit=3", + "POST", + &[("Content-Type", "application/json")], + b"{\"a\":1}", + 2048, + 1500, + ) + .await + .unwrap(); + assert_eq!(fetched.status_code, 200); + assert_eq!(u32::from(fetched.status_code), raw.status_code); + assert_eq!(fetched.body, raw.body); + assert_eq!(fetched.final_origin, raw.final_origin); + assert_eq!( + fetched.headers.into_iter().collect::>(), + raw.headers.into_iter().collect::>() + ); + // Both reached the fetch with the same request. + let [via_sdk, by_hand] = fixture.fetcher.calls().try_into().unwrap(); + assert_eq!( + ( + &via_sdk.url, + &via_sdk.method, + &via_sdk.body, + via_sdk.max_response_bytes, + via_sdk.timeout + ), + ( + &by_hand.url, + &by_hand.method, + &by_hand.body, + by_hand.max_response_bytes, + by_hand.timeout + ) + ); + assert_eq!(via_sdk.headers, by_hand.headers); + + // A refusal is the host's own. + let denied = sdk + .network_fetch(&Fetch::get("https://other.example.com/")) + .await + .unwrap_err(); + let raw = fixture + .fetch_url_text("https://other.example.com/") + .await + .unwrap_err(); + assert_eq!(denied.code(), Code::PermissionDenied); + assert_eq!( + (denied.code(), denied.message()), + (raw.code(), raw.message()) + ); +} + +#[tokio::test] +async fn the_fetch_recipe_says_whether_to_ask_the_user_or_retry() { + let fixture = Fixture::new(NETWORK).await; + fixture.user_approving_origins(&["https://api.example.com"]); + let sdk = sdk(&fixture); + + let ok = recipes::fetch_bytes(&sdk, "https://api.example.com/x", 1024) + .await + .unwrap(); + assert_eq!(ok.body, b"fetched"); + // The recipe sent its own header and deadline, and nothing of GameNode's. + let [seen] = fixture.fetcher.calls().try_into().unwrap(); + assert_eq!( + seen.headers, + [("accept".to_owned(), "application/json".to_owned())] + ); + assert_eq!( + (seen.max_response_bytes, seen.timeout), + (1024, StdDuration::from_secs(10)) + ); + + assert!(matches!( + recipes::fetch_bytes(&sdk, "https://elsewhere.example.com/", 1024).await, + Err(recipes::FetchFailure::NotApproved) + )); + assert!(matches!( + recipes::fetch_bytes(&sdk, "http://api.example.com/", 1024).await, + Err(recipes::FetchFailure::Other(_)) + )); + fixture.fetcher.script(|_, _| { + std::future::ready(Err(gamenode_platform::plugin_network::FetchError::TooLarge)) + }); + assert!(matches!( + recipes::fetch_bytes(&sdk, "https://api.example.com/big", 1024).await, + Err(recipes::FetchFailure::Busy(status)) if status.code() == Code::ResourceExhausted + )); +} + +// ---- Notifications ---- + +#[tokio::test] +async fn notification_helpers_equal_the_raw_call() { + let fixture = Fixture::new(NOTICES).await; + let sdk = sdk(&fixture); + let notice = Notice::new("en", "Sync finished") + .body("3 games updated") + .severity(Severity::Success) + .translation("pt-BR", "Sincronização concluída", "3 jogos atualizados"); + + let key = idempotency_key(); + let written = sdk.notify(¬ice, &key).await.unwrap(); + assert_eq!(written.outcome, Outcome::Applied); + // The same notice by hand under the SDK's key is a replay: shown once, not twice, which the + // host only does for an identical request. + let replay = fixture + .notify_full( + &key, + "Sync finished", + "3 games updated", + "en", + "success", + vec![("pt-BR", "Sincronização concluída", "3 jogos atualizados")], + ) + .await + .unwrap(); + assert_eq!(raw_written(replay), written); + let shown = fixture.notices.all(); + assert_eq!(shown.len(), 1); + assert_eq!(shown[0].plugin_id, "fixture.plugin"); + assert_eq!(shown[0].severity, Severity_::Success); + + // A refusal is the host's own. + let bad = sdk + .notify(&Notice::new("en", ""), &idempotency_key()) + .await + .unwrap_err(); + assert_eq!(bad.code(), Code::InvalidArgument); +} + +use crate::plugin_host::notifications::Severity as Severity_; + +#[tokio::test] +async fn the_notification_recipe_stops_at_the_rate_limit_and_reports_the_wait() { + let fixture = Fixture::new(NOTICES).await; + let sdk = sdk(&fixture); + for index in 0..5 { + fixture.advance_notice_clock(1000); + assert!( + recipes::tell_user( + &sdk, + (&format!("Title {index}"), "body"), + ("Título", "corpo"), + Severity::Info, + ) + .await + .unwrap() + ); + } + assert_eq!(fixture.notices.all().len(), 5); + + // The sixth is over the limit: the recipe says so, and nothing more was shown. + assert!( + !recipes::tell_user( + &sdk, + ("Too many", "body"), + ("Demais", "corpo"), + Severity::Info + ) + .await + .unwrap() + ); + assert_eq!(fixture.notices.all().len(), 5); + // The wait is available to a plugin that wants to try again later. + let status = sdk + .notify(&Notice::new("en", "Later"), &idempotency_key()) + .await + .unwrap_err(); + assert_eq!(status.code(), Code::ResourceExhausted); + let wait = recipes::retry_after(&status).expect("the host says how long to wait"); + assert!(wait > StdDuration::ZERO && wait <= StdDuration::from_secs(60)); + + // After the window the same recipe works again. + fixture.advance_notice_clock(61_000); + assert!( + recipes::tell_user( + &sdk, + ("Back", "body"), + ("De volta", "corpo"), + Severity::Warning + ) + .await + .unwrap() + ); +} + +// ---- The examples of the development guide ---- + +#[tokio::test] +async fn the_documented_examples_count_launches_and_read_a_save_slot() { + let fixture = Fixture::new(&[ + cap::STORAGE_READ, + cap::STORAGE_WRITE, + cap::STORAGE_PERSIST, + cap::FILES_READ, + ]) + .await; + let sdk = sdk(&fixture); + for _ in 0..3 { + recipes::count_launch(&sdk).await.unwrap(); + } + assert_eq!(fixture.load("launches").await.unwrap().value, b"3"); + + let dir = fixture.game_dir("portal", &[("slot1.sav", b"save")]); + fixture.library_in(&[("fixture:1", Some(7), "Portal", &dir)]); + // Before any dialog is connected the example carries on without the file. + assert_eq!( + recipes::read_slot(&sdk, "id-fixture:1").await.unwrap(), + None + ); + fixture.user_approving(&dir); + assert_eq!( + recipes::read_slot(&sdk, "id-fixture:1").await.unwrap(), + Some(b"save".to_vec()) + ); +} + +#[tokio::test] +async fn the_save_folder_recipe_suggests_per_platform_and_takes_what_the_user_chose() { + let fixture = Fixture::new(FILES).await; + let saves = fixture.base().join("saves"); + std::fs::create_dir_all(&saves).unwrap(); + std::fs::write(saves.join("slot1.sav"), b"s1").unwrap(); + let game = fixture.game_dir("portal", &[("a.txt", b"a")]); + fixture.library_in(&[("fixture:1", Some(7), "Portal", &game)]); + let sdk = sdk(&fixture); + let user = fixture.user_approving(&saves); + + let root = recipes::open_save_folder(&sdk, "id-fixture:1") + .await + .unwrap(); + // The user chose their own folder; the plugin can read it through the handle. + assert_eq!( + recipes::read_named(&sdk, &root, "slot1.sav", 1024) + .await + .unwrap(), + Some(b"s1".to_vec()) + ); + // Only the suggestions that apply here reached the user (none of the Windows ones), and the + // folder the user chose was not one of them. + let asked = user.asked.lock().unwrap()[0].clone(); + assert_eq!(asked.kind, "save"); + assert!( + asked + .declared + .iter() + .all(|folder| !folder.path.to_string_lossy().contains("AppData")) + ); + assert!(asked.declared.iter().all(|folder| folder.path != saves)); + let [scope] = user.confirmed.lock().unwrap().clone().try_into().unwrap(); + assert!(!scope.declared_by_plugin); +} diff --git a/crates/app/src/plugin_host/resources/tests/storage.rs b/crates/app/src/plugin_host/resources/tests/storage.rs new file mode 100644 index 000000000..01067cf8a --- /dev/null +++ b/crates/app/src/plugin_host/resources/tests/storage.rs @@ -0,0 +1,585 @@ +//! `StorageGet`/`StoragePut`/`StorageDelete` over the real local socket (task 6.1). + +use super::*; +use crate::plugin_host::storage::{MAX_KEY_BYTES, MAX_TTL_SECONDS, MAX_VALUE_BYTES, QUOTA_BYTES}; + +const STORAGE: &[&str] = &[ + cap::STORAGE_READ, + cap::STORAGE_WRITE, + cap::STORAGE_DELETE, + cap::STORAGE_PERSIST, +]; +const SESSION: StorageDurability = StorageDurability::SessionOnly; +const DURABLE: StorageDurability = StorageDurability::Persistent; + +impl Fixture { + pub(super) async fn put_value( + &self, + key: &str, + value: &[u8], + durability: StorageDurability, + ttl_seconds: u64, + expected: u64, + idempotency: &str, + ) -> Result { + self.client() + .storage_put(StoragePutRequest { + mutation: Some(self.mutation(idempotency, expected)), + key: key.into(), + value: value.to_vec(), + durability: durability as i32, + ttl_seconds, + }) + .await + .map(Response::into_inner) + } + + /// Writes with a fresh idempotency key each time. + pub(super) async fn store( + &self, + key: &str, + value: &[u8], + durability: StorageDurability, + expected: u64, + ) -> Result { + static NEXT: AtomicUsize = AtomicUsize::new(0); + let idempotency = format!("put-{}", NEXT.fetch_add(1, Ordering::SeqCst)); + self.put_value(key, value, durability, 0, expected, &idempotency) + .await + } + + pub(super) async fn load(&self, key: &str) -> Result { + self.client() + .storage_get(StorageGetRequest { + context: Some(self.context()), + key: key.into(), + }) + .await + .map(Response::into_inner) + } + + pub(super) async fn remove( + &self, + key: &str, + expected: u64, + idempotency: &str, + ) -> Result { + self.client() + .storage_delete(StorageDeleteRequest { + mutation: Some(self.mutation(idempotency, expected)), + key: key.into(), + }) + .await + .map(Response::into_inner) + } + + /// Ends the plugin's session and opens a new one, as when its process restarts. + pub(super) async fn reconnect(&mut self) { + self.api.disconnect("fixture").await; + let launch = self.api.begin_launch("fixture").unwrap(); + let credential = launch + .credential + .as_bytes() + .as_chunks::<2>() + .0 + .iter() + .map(|s| u8::from_str_radix(std::str::from_utf8(s).unwrap(), 16).unwrap()) + .collect(); + let session = Session::open_with_options( + Launch { + endpoint: self.endpoint.clone(), + credential, + operation_id: "launch".into(), + }, + "fixture.plugin", + "fixture", + "1.0", + &self.capabilities, + SessionOptions { + min_api_major: 1, + min_api_minor: cap::THIRD_PARTY_API_MINOR, + max_api_major: 1, + max_api_minor: gamenode_plugin_protocol::API_MINOR, + ..SessionOptions::default() + }, + ) + .await + .unwrap(); + launch.ready.await.unwrap(); + self.host = session.host; + self._commands = session.commands; + } + + pub(super) fn stored_files(&self) -> usize { + fn count(dir: &std::path::Path) -> usize { + std::fs::read_dir(dir).map_or(0, |entries| { + entries + .flatten() + .map(|entry| { + if entry.path().is_dir() { + count(&entry.path()) + } else { + 1 + } + }) + .sum() + }) + } + count(&self.plugin_data) + } +} + +#[tokio::test] +async fn a_plugin_stores_reads_and_deletes_its_own_values() { + let fixture = Fixture::new(STORAGE).await; + assert!(!fixture.load("settings").await.unwrap().found); + + let put = fixture + .store("settings", b"{\"a\":1}", DURABLE, 0) + .await + .unwrap(); + assert_eq!(put.outcome, MutationOutcome::Applied as i32); + assert_eq!(put.durability, DURABLE as i32); + assert_eq!(put.quota_bytes, QUOTA_BYTES); + assert_eq!(put.usage_bytes, "settings".len() as u64 + 7 + 64); + assert_eq!(put.expires_at, 0); + + let got = fixture.load("settings").await.unwrap(); + assert!(got.found); + assert_eq!(got.value, b"{\"a\":1}"); + assert_eq!(got.revision, put.revision); + assert_eq!(got.durability, DURABLE as i32); + + let next = fixture + .store("settings", b"v2", SESSION, put.revision) + .await + .unwrap(); + assert!(next.revision > put.revision); + assert_eq!( + fixture.load("settings").await.unwrap().durability, + SESSION as i32 + ); + + let deleted = fixture + .remove("settings", next.revision, "del-1") + .await + .unwrap(); + assert_eq!(deleted.outcome, MutationOutcome::Applied as i32); + assert_eq!(deleted.revision, next.revision); + assert!(!fixture.load("settings").await.unwrap().found); + // Deleting what is gone is a no-op, not an error. + let again = fixture.remove("settings", 0, "del-2").await.unwrap(); + assert_eq!(again.outcome, MutationOutcome::AlreadyApplied as i32); +} + +#[tokio::test] +async fn each_operation_needs_its_own_permission() { + let reader = Fixture::new(&[cap::STORAGE_READ]).await; + assert!(!reader.load("k").await.unwrap().found); + assert_eq!( + reader + .store("k", b"v", SESSION, 0) + .await + .unwrap_err() + .code(), + Code::PermissionDenied + ); + assert_eq!( + reader.remove("k", 0, "d").await.unwrap_err().code(), + Code::PermissionDenied + ); + + let writer = Fixture::new(&[cap::STORAGE_WRITE]).await; + writer.store("k", b"v", SESSION, 0).await.unwrap(); + assert_eq!( + writer.load("k").await.unwrap_err().code(), + Code::PermissionDenied + ); + assert_eq!( + writer.remove("k", 1, "d").await.unwrap_err().code(), + Code::PermissionDenied + ); + + // storage.persist supplements the write grant; it does not replace it. + let persist_only = Fixture::new(&[cap::STORAGE_PERSIST, cap::STORAGE_READ]).await; + for durability in [SESSION, DURABLE] { + assert_eq!( + persist_only + .store("k", b"v", durability, 0) + .await + .unwrap_err() + .code(), + Code::PermissionDenied + ); + } + assert_eq!(persist_only.stored_files(), 0); + + let deleter = Fixture::new(&[cap::STORAGE_WRITE, cap::STORAGE_READ, cap::STORAGE_DELETE]).await; + let put = deleter.store("k", b"v", SESSION, 0).await.unwrap(); + deleter.remove("k", put.revision, "d").await.unwrap(); +} + +#[tokio::test] +async fn a_durable_write_without_persist_is_denied_never_downgraded() { + let fixture = Fixture::new(&[cap::STORAGE_READ, cap::STORAGE_WRITE, cap::STORAGE_DELETE]).await; + let status = fixture.store("k", b"v", DURABLE, 0).await.unwrap_err(); + assert_eq!(status.code(), Code::PermissionDenied); + // The machine-readable denial names the missing permission. + use gamenode_plugin_protocol::prost::Message; + let detail = DenialDetail::decode(status.details()).unwrap(); + assert_eq!(detail.permission_id, cap::STORAGE_PERSIST); + // Not stored anywhere: not on disk and not in memory. + assert!(!fixture.load("k").await.unwrap().found); + assert_eq!(fixture.stored_files(), 0); + // Explicit session-only writes remain possible. + let put = fixture.store("k", b"v", SESSION, 0).await.unwrap(); + assert_eq!(put.durability, SESSION as i32); + assert_eq!(fixture.stored_files(), 0); + // And it stays a session-only value, whatever else is attempted. + assert_eq!( + fixture + .store("k", b"w", DURABLE, put.revision) + .await + .unwrap_err() + .code(), + Code::PermissionDenied + ); + assert_eq!(fixture.load("k").await.unwrap().value, b"v"); +} + +#[tokio::test] +async fn a_revoked_persist_grant_stops_durable_writes_but_not_reads_or_session_use() { + let fixture = Fixture::new(STORAGE).await; + let put = fixture.store("k", b"kept", DURABLE, 0).await.unwrap(); + fixture + .api + .revoke_session_permission("fixture", cap::STORAGE_PERSIST) + .await; + // The session's context is the same; its grant set changed. + assert_eq!( + fixture + .store("k", b"x", DURABLE, put.revision) + .await + .unwrap_err() + .code(), + Code::PermissionDenied + ); + assert_eq!(fixture.load("k").await.unwrap().value, b"kept"); + fixture.store("session", b"x", SESSION, 0).await.unwrap(); + fixture + .api + .revoke_session_permission("fixture", cap::STORAGE_WRITE) + .await; + assert_eq!( + fixture + .store("session", b"y", SESSION, 0) + .await + .unwrap_err() + .code(), + Code::PermissionDenied + ); +} + +#[tokio::test] +async fn durability_must_be_chosen() { + let fixture = Fixture::new(STORAGE).await; + for durability in [StorageDurability::Unspecified as i32, 99] { + let status = fixture + .client() + .storage_put(StoragePutRequest { + mutation: Some(fixture.mutation("k", 0)), + key: "k".into(), + value: b"v".to_vec(), + durability, + ttl_seconds: 0, + }) + .await + .unwrap_err(); + assert_eq!(status.code(), Code::InvalidArgument, "{durability}"); + } + assert!(!fixture.load("k").await.unwrap().found); +} + +#[tokio::test] +async fn keys_values_and_lifetimes_are_bounded() { + let fixture = Fixture::new(STORAGE).await; + let invalid = |status: Status| assert_eq!(status.code(), Code::InvalidArgument); + invalid(fixture.store("", b"v", SESSION, 0).await.unwrap_err()); + invalid( + fixture + .store(&"k".repeat(MAX_KEY_BYTES + 1), b"v", SESSION, 0) + .await + .unwrap_err(), + ); + invalid( + fixture + .store("bad\nkey", b"v", SESSION, 0) + .await + .unwrap_err(), + ); + invalid(fixture.load("").await.unwrap_err()); + invalid( + fixture + .load(&"k".repeat(MAX_KEY_BYTES + 1)) + .await + .unwrap_err(), + ); + invalid( + fixture + .store("k", &vec![0; MAX_VALUE_BYTES + 1], SESSION, 0) + .await + .unwrap_err(), + ); + invalid( + fixture + .put_value("k", b"v", SESSION, MAX_TTL_SECONDS + 1, 0, "ttl") + .await + .unwrap_err(), + ); + invalid( + fixture + .put_value("k", b"v", SESSION, 0, 0, "") + .await + .unwrap_err(), + ); + // The limits themselves are allowed. + fixture + .store( + &"k".repeat(MAX_KEY_BYTES), + &vec![0; MAX_VALUE_BYTES], + DURABLE, + 0, + ) + .await + .unwrap(); + fixture + .put_value("t", b"v", SESSION, MAX_TTL_SECONDS, 0, "ttl-max") + .await + .unwrap(); +} + +#[tokio::test] +async fn a_retried_write_returns_the_original_outcome_and_a_reused_key_is_refused() { + let fixture = Fixture::new(STORAGE).await; + let first = fixture + .put_value("k", b"one", DURABLE, 0, 0, "write-1") + .await + .unwrap(); + // The retry repeats the request exactly, so it neither conflicts nor writes again. + let retry = fixture + .put_value("k", b"one", DURABLE, 0, 0, "write-1") + .await + .unwrap(); + assert_eq!(retry.revision, first.revision); + assert_eq!(retry.outcome, MutationOutcome::Applied as i32); + assert_eq!(fixture.load("k").await.unwrap().revision, first.revision); + + // The same key for another request is an error, not a second write. + let status = fixture + .put_value("k", b"two", DURABLE, 0, 0, "write-1") + .await + .unwrap_err(); + assert_eq!(status.code(), Code::FailedPrecondition); + let status = fixture + .remove("k", first.revision, "write-1") + .await + .unwrap_err(); + assert_eq!(status.code(), Code::FailedPrecondition); + assert_eq!(fixture.load("k").await.unwrap().value, b"one"); + + // A retried delete is answered from the first one. + let deleted = fixture + .remove("k", first.revision, "delete-1") + .await + .unwrap(); + let again = fixture + .remove("k", first.revision, "delete-1") + .await + .unwrap(); + assert_eq!( + (again.outcome, again.revision), + (deleted.outcome, deleted.revision) + ); +} + +#[tokio::test] +async fn a_stale_revision_is_a_conflict_that_changes_nothing_and_is_not_remembered() { + let fixture = Fixture::new(STORAGE).await; + let put = fixture.store("k", b"one", DURABLE, 0).await.unwrap(); + + let conflict = fixture + .put_value("k", b"two", DURABLE, 0, 0, "retry-me") + .await + .unwrap(); + assert_eq!(conflict.outcome, MutationOutcome::RevisionConflict as i32); + assert_eq!(conflict.revision, put.revision); + let conflict = fixture.remove("k", put.revision + 5, "del").await.unwrap(); + assert_eq!(conflict.outcome, MutationOutcome::RevisionConflict as i32); + assert_eq!(conflict.revision, put.revision); + assert_eq!(fixture.load("k").await.unwrap().value, b"one"); + + // Nothing was committed, so the same key may be used again with the right revision. + let applied = fixture + .put_value("k", b"two", DURABLE, 0, put.revision, "retry-me") + .await + .unwrap(); + assert_eq!(applied.outcome, MutationOutcome::Applied as i32); + assert_eq!(fixture.load("k").await.unwrap().value, b"two"); +} + +#[tokio::test] +async fn exceeding_the_quota_is_resource_exhausted_and_preserves_stored_values() { + for durability in [SESSION, DURABLE] { + let fixture = Fixture::new(STORAGE).await; + let big = vec![9u8; MAX_VALUE_BYTES]; + let mut stored = 0; + let status = loop { + match fixture + .store(&format!("big-{stored}"), &big, durability, 0) + .await + { + Ok(_) => stored += 1, + Err(status) => break status, + } + assert!(stored < 40, "the quota never applied"); + }; + assert_eq!(status.code(), Code::ResourceExhausted, "{durability:?}"); + assert!(status.message().contains("nothing was changed")); + assert!((14..=15).contains(&stored), "{durability:?}: {stored}"); + // Every earlier value is intact, and smaller values still fit. + for index in 0..stored { + let got = fixture.load(&format!("big-{index}")).await.unwrap(); + assert!(got.found && got.value == big, "{durability:?} big-{index}"); + } + fixture + .store("small", b"fits", durability, 0) + .await + .unwrap(); + } +} + +#[tokio::test] +async fn durable_values_survive_a_restart_session_only_values_do_not() { + let first = Fixture::new(STORAGE).await; + let durable = first.store("durable", b"stays", DURABLE, 0).await.unwrap(); + first.store("volatile", b"goes", SESSION, 0).await.unwrap(); + let data = first.plugin_data.clone(); + + let second = Fixture::restarted(STORAGE, data).await; + let got = second.load("durable").await.unwrap(); + assert!(got.found); + assert_eq!(got.value, b"stays"); + assert_eq!(got.revision, durable.revision); + assert!(!second.load("volatile").await.unwrap().found); + // Revisions keep growing across the restart. + let next = second + .store("durable", b"newer", DURABLE, durable.revision) + .await + .unwrap(); + assert!(next.revision > durable.revision); +} + +#[tokio::test] +async fn session_only_values_end_with_the_plugin_session() { + let mut fixture = Fixture::new(STORAGE).await; + fixture + .store("volatile", b"goes", SESSION, 0) + .await + .unwrap(); + fixture + .store("durable", b"stays", DURABLE, 0) + .await + .unwrap(); + assert!(fixture.load("volatile").await.unwrap().found); + + fixture.reconnect().await; + assert!(!fixture.load("volatile").await.unwrap().found); + assert_eq!(fixture.load("durable").await.unwrap().value, b"stays"); +} + +#[tokio::test] +async fn namespaces_follow_the_account_profile() { + let mut fixture = Fixture::new(STORAGE).await; + fixture.store("k", b"account a", DURABLE, 0).await.unwrap(); + fixture.store("v", b"account a", SESSION, 0).await.unwrap(); + + // Another account signs in: the plugin restarts into a profile with nothing of a's. + fixture.api.profiles().update(Some("b"), true); + fixture.api.fence_third_party_sessions().await; + fixture.reconnect().await; + assert!(!fixture.load("k").await.unwrap().found); + assert!(!fixture.load("v").await.unwrap().found); + fixture.store("k", b"account b", DURABLE, 0).await.unwrap(); + assert_eq!(fixture.stored_files(), 2, "one private store per profile"); + + // Back to a: its durable value is there, its session-only value is not. + fixture.api.profiles().update(Some("a"), true); + fixture.api.fence_third_party_sessions().await; + fixture.reconnect().await; + assert_eq!(fixture.load("k").await.unwrap().value, b"account a"); + assert!(!fixture.load("v").await.unwrap().found); +} + +#[tokio::test] +async fn values_expire_after_their_lifetime() { + let fixture = Fixture::new(STORAGE).await; + let put = fixture + .put_value("k", b"v", DURABLE, 60, 0, "ttl") + .await + .unwrap(); + assert_eq!(put.expires_at, 1_000_060); + let got = fixture.load("k").await.unwrap(); + assert_eq!((got.found, got.expires_at), (true, 1_000_060)); + + fixture.clock.store(1_000_060, Ordering::SeqCst); + assert!(!fixture.load("k").await.unwrap().found); + // A retry of the original write still answers from its original outcome. + let retry = fixture + .put_value("k", b"v", DURABLE, 60, 0, "ttl") + .await + .unwrap(); + assert_eq!( + (retry.revision, retry.expires_at), + (put.revision, 1_000_060) + ); + // An expired key is a key that does not exist. + fixture.store("k", b"again", DURABLE, 0).await.unwrap(); +} + +#[tokio::test] +async fn failures_never_reveal_where_the_data_lives() { + let fixture = Fixture::new(STORAGE).await; + // Something that is not a folder where the plugin-data folder should be. + std::fs::remove_dir_all(&fixture.plugin_data).unwrap(); + std::fs::write(&fixture.plugin_data, b"in the way").unwrap(); + let status = fixture.store("k", b"v", DURABLE, 0).await.unwrap_err(); + assert_eq!(status.code(), Code::Unavailable); + let shown = format!("{status:?}"); + let root = fixture.plugin_data.to_str().unwrap(); + assert!( + !shown.contains(root) && !shown.contains("plugin-data"), + "{shown}" + ); + // Session-only use does not need the disk. + fixture.store("k", b"v", SESSION, 0).await.unwrap(); +} + +#[tokio::test] +async fn nothing_in_a_reply_is_a_path_or_another_namespaces_data() { + let fixture = Fixture::new(STORAGE).await; + let put = fixture.store("k", b"v", DURABLE, 0).await.unwrap(); + let got = fixture.load("k").await.unwrap(); + let data = fixture.plugin_data.to_str().unwrap().to_owned(); + for text in [format!("{put:?}"), format!("{got:?}")] { + assert!( + !text.contains(&data) && !text.contains("storage.sqlite"), + "{text}" + ); + } + // The request has no field that could name another owner: a key that looks like a path or + // an identity is just a key in the caller's own namespace. + for key in ["../other/k", "org.other.plugin/k", "C:\\x", "k/../../k"] { + fixture.store(key, b"mine", SESSION, 0).await.unwrap(); + assert_eq!(fixture.load(key).await.unwrap().value, b"mine"); + } +} diff --git a/crates/app/src/plugin_host/resources/tests/tools.rs b/crates/app/src/plugin_host/resources/tests/tools.rs new file mode 100644 index 000000000..ab4bf9f85 --- /dev/null +++ b/crates/app/src/plugin_host/resources/tests/tools.rs @@ -0,0 +1,301 @@ +//! Real socket authorization/job tests with a controlled Core review adapter. +use super::*; +use crate::plugin_host::jobs::JobOwner; + +const GRANTS: &[&str] = &[ + cap::GAME_LAUNCH, + cap::TOOLS_READ, + cap::TOOLS_APPLY, + cap::TOOLS_REMOVE, +]; +async fn setup() -> (Fixture, Arc, u64) { + let f = Fixture::new(GRANTS).await; + f.library(&[ + ("fixture:1", Some(3), "Game"), + ("steam:1", Some(5), "Foreign"), + ]); + let host = f.with_host(); + host.tool_support.store(true, Ordering::SeqCst); + let revision = f.feed.revision_of("fixture:1").unwrap(); + (f, host, revision) +} +async fn apply( + f: &Fixture, + key: &str, + revision: u64, + tool: &str, + game: &str, +) -> Result { + f.client() + .tools_request_apply(ToolApplyRequest { + mutation: Some(f.mutation(key, revision)), + tool_id: tool.into(), + game_id: game.into(), + user_intent_id: String::new(), + }) + .await + .map(Response::into_inner) +} +async fn reviewed(host: &FakeHost) { + tokio::time::timeout(Duration::from_secs(5), async { + while host.tool_reviews.lock().unwrap().is_empty() { + tokio::task::yield_now().await; + } + }) + .await + .unwrap(); +} +async fn ended(f: &Fixture, id: &str) -> JobReply { + let caller = f + .api + .authorize_resource_session(Some(&f.context())) + .unwrap(); + let owner = JobOwner::of(&caller).unwrap(); + tokio::time::timeout(Duration::from_secs(5), async { + loop { + let job = f.jobs.get(&owner, id).unwrap(); + if !matches!(job.state(), JobState::Queued | JobState::Running) { + return job; + } + tokio::time::sleep(Duration::from_millis(5)).await; + } + }) + .await + .unwrap() +} +#[tokio::test] +async fn catalog_is_paged_scoped_and_does_not_disclose_installer_inputs() { + let (f, _, _) = setup().await; + let list = |cursor: String| ToolsListRequest { + page: Some(PageRequest { + context: Some(f.context()), + page_size: 1, + cursor, + ..Default::default() + }), + game_id: "3".into(), + platform: "windows".into(), + }; + let first = f + .client() + .tools_list(list(String::new())) + .await + .unwrap() + .into_inner(); + assert_eq!(first.tools.len(), 1); + assert!(first.next_cursor.is_empty()); // The production catalog currently has one tool. + assert_eq!(first.tools[0].version, "fixture-v1"); + assert_eq!( + f.client() + .tools_list(list("edited".into())) + .await + .unwrap_err() + .code(), + Code::FailedPrecondition + ); + let mut foreign = list(String::new()); + foreign.game_id = "5".into(); + assert!(f.client().tools_list(foreign).await.is_err()); + let mut linux = list(String::new()); + linux.platform = "linux".into(); + assert!( + f.client() + .tools_list(linux) + .await + .unwrap() + .into_inner() + .tools + .is_empty() + ); + f.api + .revoke_session_permission("fixture", cap::TOOLS_READ) + .await; + assert_eq!( + f.client() + .tools_list(list(first.next_cursor)) + .await + .unwrap_err() + .code(), + Code::PermissionDenied + ); +} +#[tokio::test] +async fn apply_and_remove_wait_for_review_retries_do_not_duplicate_and_permissions_are_independent() +{ + let (f, host, revision) = setup().await; + let job = apply(&f, "apply", revision, "optiscaler", "3") + .await + .unwrap(); + reviewed(&host).await; + assert_eq!(host.tool_effects.load(Ordering::SeqCst), 0); + assert_eq!( + apply(&f, "apply", revision, "optiscaler", "3") + .await + .unwrap() + .job_id, + job.job_id + ); + assert_eq!(host.tool_reviews.lock().unwrap().len(), 1); + host.tool_gate.notify_one(); + assert_eq!(ended(&f, &job.job_id).await.state(), JobState::Succeeded); + assert_eq!(host.tool_effects.load(Ordering::SeqCst), 1); + let removed = f + .client() + .tools_request_remove(ToolRemoveRequest { + mutation: Some(f.mutation("remove", revision)), + tool_id: "optiscaler".into(), + game_id: "3".into(), + user_intent_id: String::new(), + }) + .await + .unwrap() + .into_inner(); + tokio::time::timeout(Duration::from_secs(5), async { + while host.tool_reviews.lock().unwrap().len() != 2 { + tokio::task::yield_now().await; + } + }) + .await + .unwrap(); + assert!(host.tool_reviews.lock().unwrap()[1].2); + host.tool_gate.notify_one(); + assert_eq!( + ended(&f, &removed.job_id).await.state(), + JobState::Succeeded + ); + f.api + .revoke_session_permission("fixture", cap::TOOLS_APPLY) + .await; + assert_eq!( + apply(&f, "denied", revision, "optiscaler", "3") + .await + .unwrap_err() + .code(), + Code::PermissionDenied + ); +} +#[tokio::test] +async fn arbitrary_installers_foreign_ambiguous_stale_and_unsupported_targets_never_reach_review() { + let (f, host, revision) = setup().await; + for bad in [ + "https://evil.invalid/install.exe", + "../optiscaler", + "", + "arbitrary", + ] { + assert_eq!( + apply(&f, "bad", revision, bad, "3") + .await + .unwrap_err() + .code(), + Code::NotFound + ); + } + assert!( + apply(&f, "foreign", revision, "optiscaler", "5") + .await + .is_err() + ); + assert_eq!( + apply(&f, "stale", revision + 1, "optiscaler", "3") + .await + .unwrap_err() + .code(), + Code::Aborted + ); + host.tool_support.store(false, Ordering::SeqCst); + assert_eq!( + apply(&f, "unsupported", revision, "optiscaler", "3") + .await + .unwrap_err() + .code(), + Code::Unavailable + ); + host.tool_support.store(true, Ordering::SeqCst); + f.library(&[ + ("fixture:1", Some(3), "Game"), + ("fixture:2", Some(3), "Other install"), + ]); + assert_eq!( + apply(&f, "ambiguous", revision, "optiscaler", "3") + .await + .unwrap_err() + .code(), + Code::FailedPrecondition + ); + assert!(host.tool_reviews.lock().unwrap().is_empty()); +} +#[tokio::test] +async fn decline_revocation_cancellation_and_changed_target_prevent_effects() { + for mode in ["decline", "revoke", "cancel", "change"] { + let (f, host, revision) = setup().await; + let job = apply(&f, mode, revision, "optiscaler", "3").await.unwrap(); + reviewed(&host).await; + match mode { + "decline" => host.tool_declined.store(true, Ordering::SeqCst), + "revoke" => { + f.api + .revoke_session_permission("fixture", cap::TOOLS_APPLY) + .await; + } + "change" => f.library(&[("fixture:1", Some(3), "Changed")]), + "cancel" => { + let caller = f + .api + .authorize_resource_session(Some(&f.context())) + .unwrap(); + let owner = JobOwner::of(&caller).unwrap(); + let jobs = f.jobs.clone(); + let id = job.job_id.clone(); + let cancel = tokio::spawn(async move { jobs.cancel(&owner, &id).await }); + tokio::time::sleep(Duration::from_millis(20)).await; + host.tool_gate.notify_one(); + cancel.await.unwrap().unwrap(); + } + _ => unreachable!(), + } + if mode != "cancel" { + host.tool_gate.notify_one(); + } + assert_ne!(ended(&f, &job.job_id).await.state(), JobState::Succeeded); + assert_eq!(host.tool_effects.load(Ordering::SeqCst), 0); + } +} + +#[tokio::test] +async fn an_extension_can_review_only_its_host_selected_foreign_provider_game() { + let f = Fixture::start_with_target( + GRANTS, + true, + None, + Some(TargetGameContext { + game_id: "5".into(), + installation_id: "id-steam:1".into(), + profile_id: String::new(), + revision: String::new(), + }), + ) + .await; + f.library(&[ + ("steam:1", Some(5), "Selected"), + ("steam:2", Some(6), "Other"), + ]); + let host = f.with_host(); + host.tool_support.store(true, Ordering::SeqCst); + let revision = f.feed.revision_of("steam:1").unwrap(); + assert!( + apply(&f, "other", revision, "optiscaler", "6") + .await + .is_err() + ); + let job = apply(&f, "selected", revision, "OPTISCALER", "5") + .await + .unwrap(); + reviewed(&host).await; + assert_eq!( + host.tool_reviews.lock().unwrap()[0], + ("steam:1".into(), "optiscaler".into(), false) + ); + host.tool_gate.notify_one(); + assert_eq!(ended(&f, &job.job_id).await.state(), JobState::Succeeded); +} diff --git a/crates/app/src/plugin_host/resources/tools.rs b/crates/app/src/plugin_host/resources/tools.rs new file mode 100644 index 000000000..ec33686ec --- /dev/null +++ b/crates/app/src/plugin_host/resources/tools.rs @@ -0,0 +1,226 @@ +//! Host catalog and user-reviewed tool operations. Plugins never choose installer inputs. +use super::mutations::{game_id, mutation_key, request_hash}; +use super::*; +use crate::plugin_host::jobs::{JobOwner, Outcome, work}; +use crate::plugin_host::library::{InstallState, Projected}; +use crate::plugin_host::provider::ResourceCaller; + +impl ResourceApi { + pub(super) fn tool_target( + &self, + caller: &ResourceCaller, + context: &ServiceContext, + game: &str, + ) -> Result<(String, Projected), Status> { + let game_id = + game_id(game)?.ok_or_else(|| Status::invalid_argument("game_id is required"))?; + let installation = if context.session_kind() == SessionKind::Extension { + context + .target_game + .as_ref() + .ok_or_else(|| Status::not_found("game not found"))? + .installation_id + .clone() + } else { + let scope = Scope { + own_provider: caller.provider_id.clone(), + read_all: false, + provider_filter: None, + }; + let (_, entries) = self.library.by_game(&scope, game_id); + let entries = entries + .into_iter() + .filter(|e| e.install_state == InstallState::Installed) + .collect::>(); + if entries.len() != 1 { + return Err(Status::failed_precondition( + "one installed game target is required", + )); + } + entries[0].installation_id.clone() + }; + let target = self.action_target(caller, context, game, &installation)?; + if target.1.install_state != InstallState::Installed { + return Err(Status::failed_precondition("game is not installed")); + } + Ok(target) + } + + pub(super) async fn list_tools( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + let page = request.page.unwrap_or_default(); + let context = page.context.clone().unwrap_or_default(); + let caller = self + .providers + .authorize_resource(Some(&context), cap::TOOLS_READ)?; + super::no_common_data(page.common_data_categories.as_ref())?; + if !matches!(request.platform.as_str(), "" | "windows" | "linux") { + return Err(Status::invalid_argument("unknown platform")); + } + let revision = self.library.revision(); + let host = self.library.host(); + let records = if request.game_id.is_empty() { + gamenode_core::tools::builtin_tools() + .into_iter() + .map(|d| ToolRecord { + tool_id: d.id.as_str().into(), + name: d.name, + version: String::new(), + availability: if host.as_ref().is_some_and(|h| h.tools_supported()) { + "available" + } else { + "unavailable" + } + .into(), + }) + .collect::>() + } else { + let (key, _) = self.tool_target(&caller, &context, &request.game_id)?; + host.as_ref() + .ok_or_else(|| Status::unavailable("tools unavailable"))? + .tools_list(key) + .await? + }; + let records = if !request.platform.is_empty() && request.platform != "windows" { + vec![] + } else { + records + }; + let binding = request_hash(&[ + "tools", + &request.game_id, + &request.platform, + &caller.grant_revision.to_string(), + &self.library.revision().to_string(), + &format!("{records:?}"), + ]); + let binding = format!("tools:{binding:?}"); + let after = if page.cursor.is_empty() { + 0 + } else { + self.files + .open_cursor(&caller.session_id, &binding, &page.cursor) + .and_then(|s| s.parse::().ok()) + .filter(|n| *n <= records.len()) + .ok_or_else(|| Status::failed_precondition("tool catalog changed; list again"))? + }; + let count = if page.page_size == 0 { + DEFAULT_PAGE_SIZE + } else { + (page.page_size as usize).min(MAX_PAGE_SIZE) + }; + let end = (after + count).min(records.len()); + let next_cursor = if end < records.len() { + self.files + .seal_cursor(&caller.session_id, &binding, &end.to_string()) + } else { + String::new() + }; + (self.guard(context, cap::TOOLS_READ, caller.grant_revision))()?; + if self.library.revision() != revision { + return Err(Status::failed_precondition( + "tool target changed; list again", + )); + } + Ok(Response::new(ToolsListReply { + tools: records[after..end].to_vec(), + next_cursor, + })) + } + + pub(super) async fn request_tool_action( + &self, + mutation: Option, + tool: String, + game: String, + intent: String, + remove: bool, + ) -> Result, Status> { + let mutation = mutation.ok_or_else(|| Status::invalid_argument("mutation required"))?; + let context = mutation.context.clone().unwrap_or_default(); + let permission = if remove { + cap::TOOLS_REMOVE + } else { + cap::TOOLS_APPLY + }; + let caller = self + .providers + .authorize_resource(Some(&context), permission)?; + let tool = gamenode_core::tools::find_tool(&tool) + .ok_or_else(|| Status::not_found("tool not found"))? + .id + .as_str() + .to_owned(); + if !intent.is_empty() { + return Err(Status::failed_precondition( + "tools require review in the Core tools window", + )); + } + let (entry_key, entry) = self.tool_target(&caller, &context, &game)?; + if entry.revision != mutation.expected_revision { + return Err(Status::aborted("game target changed; read it again")); + } + let host = self + .library + .host() + .filter(|h| h.tools_supported()) + .ok_or_else(|| Status::unavailable("tools are unavailable on this platform"))?; + let key = mutation_key(&mutation)?.to_owned(); + let hash = request_hash(&[ + permission, + &game, + &tool, + &mutation.expected_revision.to_string(), + ]); + let owner = JobOwner::of(&caller)?; + let _serial = self.mutations.lock.lock().await; + if let Some(job) = self.jobs.replay(&owner, &key, hash)? { + return Ok(Response::new(job)); + } + let identity = caller + .namespace + .as_ref() + .ok_or_else(|| Status::unavailable("plugin identity unavailable"))? + .identity(); + let review = gamenode_core::tools::ToolPluginRequest { + plugin_id: identity.plugin_id.clone(), + publisher_fingerprint: identity.publisher_fingerprint.clone(), + remove, + }; + let api = self.clone(); + let c = caller.clone(); + let cx = context.clone(); + let run = work(move |job| async move { + if let Err(e) = job.start() { + return Outcome::stopped(&e); + } + let checkpoint = job.checkpoint(); + let target_key = entry_key.clone(); + let check = Arc::new(move || { + checkpoint()?; + let (current_key, current) = api.tool_target(&c, &cx, &game)?; + if current_key != entry_key || current.revision != entry.revision { + return Err(Status::failed_precondition("tool target changed")); + } + Ok(()) + }); + match host.request_tool(target_key, tool, review, check).await { + Ok(()) => Outcome::succeeded("tool_complete", "tool operation completed"), + Err(e) => Outcome::stopped(&e), + } + }); + let (job, _) = self.start_job( + &caller, + context, + permission, + &key, + hash, + Some("review in Core tools"), + run, + )?; + Ok(Response::new(job)) + } +} diff --git a/crates/app/src/plugin_host/retention.rs b/crates/app/src/plugin_host/retention.rs new file mode 100644 index 000000000..955a71c44 --- /dev/null +++ b/crates/app/src/plugin_host/retention.rs @@ -0,0 +1,66 @@ +//! One keep-or-delete choice for a plugin's durable shared records and private persistence +//! entries. +//! +//! The same choice is used by single-plugin and bundle uninstall. Keeping makes the rows and +//! entries inert under the original owner; deleting removes only that owner's rows and private +//! namespace. Applying it is host code: a plugin RPC never reaches these types, and no physical +//! path is included in the outcome. + +use std::future::Future; +use std::pin::Pin; + +/// What an uninstall does with a producer's durable shared records. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum DataRetention { + /// Keep the records on disk but make them inert under the original owner. + Keep, + /// Delete the records and report the bytes actually reclaimed. + Delete, +} + +impl DataRetention { + pub fn as_str(self) -> &'static str { + match self { + Self::Keep => "kept", + Self::Delete => "deleted", + } + } +} + +/// The durable part of one uninstall or reviewed reuse decision. No physical path is included. +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct DurableRetentionOutcome { + pub plugin_id: String, + /// `kept` or `deleted`, matching the retention choice the host applied. + pub data_retention: &'static str, + pub archived_records: u64, + pub removed_records: u64, + pub reclaimed_bytes: u64, + /// Private-store entries archived by the same choice. Inert until a reviewed reuse. + pub private_archived_records: u64, + /// Private-store entries deleted by the same choice. + pub private_removed_records: u64, + /// Logical private bytes reclaimed by deletion. No path is disclosed. + pub private_reclaimed_bytes: u64, +} + +/// The result of a reviewed reuse of archived private entries. A reinstall needs this separate +/// decision before the old values become readable again. +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PrivateReuseOutcome { + pub plugin_id: String, + pub restored_records: u64, + pub logical_bytes: u64, +} + +/// Applies the host retention choice to one plugin identity. Implemented by the lifecycle; used +/// by both single-plugin and bundle uninstall so they cannot drift. +pub trait DurableRetentionSink: Send + Sync { + fn apply<'a>( + &'a self, + plugin_id: &'a str, + retention: DataRetention, + ) -> Pin> + Send + 'a>>; +} diff --git a/crates/app/src/plugin_host/runtime.rs b/crates/app/src/plugin_host/runtime.rs index 727217aae..8429d60fe 100644 --- a/crates/app/src/plugin_host/runtime.rs +++ b/crates/app/src/plugin_host/runtime.rs @@ -2,27 +2,115 @@ //! behind the public API; this layer owns process availability and initialization. use super::{ + grants::{PermissionRequest, PluginIdentity}, login::LoginBroker, - process::{PLUGIN_STOPPED, ProcessConfig, ProviderProcesses}, + managed_packages::{ManagedPackageLifecycle, PackageLifecycleError, lock_publisher_identity}, + process::{ + ExtensionIntent, ExtensionLaunch, ExtensionTarget, PLUGIN_STOPPED, ProcessConfig, + ProviderProcesses, + }, + profile::{PluginProfiles, PluginStateLayout}, provider::{Completion, ProviderApi, Registration}, - services::ProviderServices, + services::{ExternalAccountPersistence, ProviderServices}, + sharing_policy::{ + ActivationReadGrant, RecipientSharingSnapshot, SharedSharingPolicies, SharingPolicyError, + SourceRecipientPolicy, + }, }; +use gamenode_platform::plugin_registry::{InstalledPluginVersion, PluginPackageRegistry}; +use gamenode_platform::plugin_shared_data::OwnerScope; use gamenode_plugin_protocol::{ capability as cap, models, - proto::{OperationDisposition, ProviderOperation}, + proto::{OperationDisposition, ProviderContext, ProviderOperation}, }; use std::{ collections::BTreeMap, - path::PathBuf, + path::{Path, PathBuf}, sync::{Arc, Mutex}, - time::Duration, + time::{Duration, SystemTime, UNIX_EPOCH}, }; use tonic::Status; +struct UnavailableExternalAccounts; + +impl ExternalAccountPersistence for UnavailableExternalAccounts { + fn load( + &self, + _owner: &super::namespace::NamespaceOwner, + _provider: &str, + ) -> Result, Status> { + Ok(None) + } + + fn save( + &self, + _owner: &super::namespace::NamespaceOwner, + _account: models::StoreAccount, + _clear_ownership: bool, + ) -> Result<(), Status> { + Err(Status::unavailable( + "plugin account storage is not configured", + )) + } + + fn clear( + &self, + _owner: &super::namespace::NamespaceOwner, + _provider: &str, + ) -> Result<(), Status> { + Err(Status::unavailable( + "plugin account storage is not configured", + )) + } +} + pub type Observer = Arc; +#[derive(Clone, Copy, Debug)] +pub struct RuntimeContextRevision { + pub library_revision: u64, + pub binding_revision: u64, +} + +#[tonic::async_trait] +pub trait RuntimeSessionHandler: Send + Sync { + async fn authorize_context( + &self, + plugin_id: String, + publisher_fingerprint: String, + owner_key: String, + profile_epoch: u64, + request: gamenode_plugin_protocol::proto::RuntimeSessionContextRequest, + ) -> Result { + let _ = ( + plugin_id, + publisher_fingerprint, + owner_key, + profile_epoch, + request, + ); + Err(Status::unimplemented( + "runtime context changes are unavailable", + )) + } + async fn report( + &self, + plugin_id: String, + owner_key: String, + report: gamenode_plugin_protocol::proto::RuntimeSessionReport, + context_authorized: bool, + context_revision: Option, + received_at: std::time::Instant, + ) -> gamenode_plugin_protocol::proto::RuntimeSessionResult; + + async fn disconnected(&self, plugin_id: String); +} + #[async_trait::async_trait] pub trait ProviderRuntime: Send + Sync { + fn managed_plugin_inventory(&self) -> Vec { + Vec::new() + } fn accounts(&self) -> Vec; fn has_provider(&self, provider: &str) -> bool; fn status(&self, provider: &str) -> Option; @@ -39,11 +127,26 @@ pub trait ProviderRuntime: Send + Sync { } fn set_observer(&self, observer: Observer); fn set_account_persistence(&self, _accounts: Arc) {} + fn set_runtime_session_handler(&self, _handler: Arc) {} async fn execute( &self, provider: &str, operation: ProviderOperation, ) -> Result; + async fn start_extension( + &self, + _plugin_id: &str, + _target: ExtensionTarget, + _operation: super::intents::Operation, + ) -> Result<(), Status> { + Err(Status::unimplemented("extension actions are unavailable")) + } + async fn available_extensions( + &self, + _operation: super::intents::Operation, + ) -> Result, Status> { + Ok(Vec::new()) + } async fn execute_achievements( &self, _provider: &str, @@ -64,32 +167,2307 @@ pub trait ProviderRuntime: Send + Sync { "the {provider} plugin cannot be started" ))) } - async fn shutdown(&self); + async fn shutdown(&self); +} + +struct Entry { + services: Arc, + initialized: tokio::sync::Mutex>, + packaged: bool, + initialize: bool, +} + +pub(crate) fn managed_process_config( + installed: &gamenode_platform::plugin_registry::InstalledPluginVersion, + report: &super::managed_packages::PackageCandidateReport, + publisher_key: [u8; 32], +) -> Result { + let manifest = &report.manifest; + if manifest.id != installed.plugin_id || manifest.version != installed.version { + return Err(Status::failed_precondition( + "managed package identity does not match its registry record", + )); + } + let provider_id = match manifest.kind { + super::package::PluginKind::Provider => manifest + .provider_id + .clone() + .ok_or_else(|| Status::failed_precondition("provider package has no provider id"))?, + super::package::PluginKind::Extension => { + super::provider::extension_registration_id(&manifest.id) + } + }; + let target = report + .selected_target() + .map_err(|error| Status::failed_precondition(error.to_string()))?; + let mut manifest_capabilities = vec![cap::CONTEXT.to_owned()]; + let mut required_capabilities = Vec::new(); + for permission in &manifest.permissions { + if cap::KNOWN.contains(&permission.id.as_str()) { + manifest_capabilities.push(permission.id.clone()); + if permission.required { + required_capabilities.push(permission.id.clone()); + } + } else if permission.required { + return Err(Status::failed_precondition( + "required provider permission is unsupported", + )); + } + } + manifest_capabilities.sort(); + manifest_capabilities.dedup(); + required_capabilities.sort(); + required_capabilities.dedup(); + Ok(ProcessConfig { + provider_id, + executable: installed.package_path.join(&target.target.entrypoint), + arguments: vec![], + environment: vec![], + startup_timeout: Duration::from_secs(10), + manifest_capabilities, + required_capabilities, + blocked_capabilities: vec![], + integrity: Some(super::process::PackageIntegrity { + package_root: installed.package_path.clone(), + version: installed.version.clone(), + publisher_key, + emulation_policy: gamenode_platform::plugin_environment::EmulationPolicy::RequireNative, + }), + }) +} + +/// One active managed package that passed identity, publisher and compatibility validation and +/// is ready for host registration. +struct PreparedManagedPackage { + provider_id: String, + plugin_id: String, + publisher_fingerprint: String, + inventory: super::PluginInfo, + config: ProcessConfig, + registration: Registration, + extension_schemas: Vec, + entry: Option>, +} + +/// Host-owned composition surfaces used to register a package accepted after startup. The import +/// flow must not need a restart, so it reuses the same verified package data and service surface +/// as the startup loop instead of a weaker, second registration path. +#[derive(Clone)] +pub(crate) struct HostComposition { + paths: gamenode_platform::paths::DataPaths, + library: Arc, + login: Option>, + dynamic: Arc, +} + +/// One post-startup package registration attempt. A package that was installed but could not be +/// registered keeps its review outcome and reports the explicit reason instead of running. +pub(crate) struct InstalledPackageRegistration { + pub plugin_id: String, + pub error: Option, +} + +/// Provider entries and inventory rows added after the startup composition. +#[derive(Default)] +pub(crate) struct DynamicHostState { + entries: std::sync::RwLock>>, + inventory: std::sync::RwLock>, + /// Host callbacks wired before a package was registered. New provider services receive the + /// same observer and account persistence as the startup composition. + observer: Mutex>, + accounts: Mutex>>, +} + +impl DynamicHostState { + fn entry(&self, provider_id: &str) -> Option> { + self.entries + .read() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .get(provider_id) + .cloned() + } + + fn entries(&self) -> Vec<(String, Arc)> { + self.entries + .read() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .iter() + .map(|(id, entry)| (id.clone(), entry.clone())) + .collect() + } + + fn inventory(&self) -> Vec { + self.inventory + .read() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .clone() + } + + fn insert_entry(&self, provider_id: String, entry: Arc) { + if let Some(observer) = lock(&self.observer).clone() { + entry.services.set_observer(observer); + } + if let Some(accounts) = lock(&self.accounts).clone() { + entry.services.set_account_persistence(accounts); + } + self.entries + .write() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .insert(provider_id, entry); + } + + fn set_observer(&self, observer: Observer) { + for (_, entry) in self.entries() { + entry.services.set_observer(observer.clone()); + } + *lock(&self.observer) = Some(observer); + } + + fn set_account_persistence(&self, accounts: Arc) { + for (_, entry) in self.entries() { + entry.services.set_account_persistence(accounts.clone()); + } + *lock(&self.accounts) = Some(accounts); + } + + fn push_inventory(&self, plugin: super::PluginInfo) { + self.inventory + .write() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .push(plugin); + } +} + +/// Reads, validates and describes one active managed package under the pinned publisher key. +/// Every manifest, trust, compatibility and identity check runs here so the startup composition +/// and post-install registration cannot drift apart. +async fn prepare_managed_package( + installed: InstalledPluginVersion, + trust: &super::publisher_trust::PublisherTrustStore, + packages: &ManagedPackageLifecycle, + composition: Option<&HostComposition>, +) -> Result { + let package_root = installed.package_path.clone(); + let manifest = tokio::task::spawn_blocking(move || { + let path = package_root.join("plugin.json"); + let metadata = std::fs::symlink_metadata(&path).map_err(|error| { + Status::failed_precondition(format!("plugin manifest unavailable: {error}")) + })?; + if !metadata.is_file() + || metadata.file_type().is_symlink() + || metadata.len() > 4 * 1024 * 1024 + { + return Err(Status::failed_precondition( + "plugin manifest is not a bounded regular file", + )); + } + let bytes = std::fs::read(path).map_err(|error| { + Status::failed_precondition(format!("plugin manifest unavailable: {error}")) + })?; + super::package::Manifest::parse_json(&bytes).map_err(|error| { + Status::failed_precondition(format!("plugin manifest is invalid: {error}")) + }) + }) + .await + .map_err(|_| Status::internal("plugin manifest worker failed"))??; + let plugin_manifest = manifest.manifest(); + if plugin_manifest.id != installed.plugin_id || plugin_manifest.version != installed.version { + return Err(Status::failed_precondition( + "managed plugin registry identity does not match its manifest", + )); + } + let publisher_key = manifest.publisher_key(); + let publisher_fingerprint = match trust.inspect(&installed.plugin_id, &publisher_key) { + Ok(super::publisher_trust::KeyStatus::Trusted { fingerprint }) => fingerprint, + _ => { + return Err(Status::failed_precondition( + "managed plugin publisher is not currently trusted", + )); + } + }; + let report = packages + .inspect_candidate( + &installed.package_path, + publisher_key, + gamenode_platform::plugin_environment::EmulationPolicy::RequireNative, + ) + .await + .map_err(|error| Status::failed_precondition(error.to_string()))?; + let config = managed_process_config(&installed, &report, publisher_key)?; + let provider_id = config.provider_id.clone(); + let inventory = super::PluginInfo { + provider_id: report.manifest.provider_id.clone().unwrap_or_default(), + plugin_id: installed.plugin_id.clone(), + plugin_kind: match report.manifest.kind { + super::package::PluginKind::Provider => "provider".to_owned(), + super::package::PluginKind::Extension => "extension".to_owned(), + }, + name: report.manifest.name.clone(), + source: "community".to_owned(), + status: "installed".to_owned(), + // Manifest declarations are not grants. The permission viewer exposes effective grants + // separately; this legacy field is only for bundled plugins. + capabilities: vec![], + session: "stopped".to_owned(), + native_access: report.manifest.native_access.clone(), + publisher_fingerprint: Some(publisher_fingerprint.clone()), + version: installed.version.clone(), + enabled: None, + runtime_available: None, + compatibility_details: Some(report.compatibility_review()), + bundle_id: None, + bundle_name: None, + bundle_version: None, + bundle_component_kind: None, + bundle_publisher_fingerprint: None, + bundle_components: None, + }; + let services = if report.manifest.kind == super::package::PluginKind::Provider { + // ProviderServices validates the host context as a provider TOML manifest. A managed + // package has its own signed JSON manifest instead, so compose the minimal context from + // that already verified identity. Do not accept a manifest supplied over RPC or copy + // package data into host capabilities/actions. + match composition { + Some(composition) => { + let context_manifest = format!( + "id = {:?}\nname = {:?}\nplatforms = [{:?}]\nsource = {:?}\n\n[scan]\n", + provider_id, + report.manifest.name, + std::env::consts::OS, + installed.plugin_id + ); + Some(Arc::new(ProviderServices::new_external( + ProviderContext { + provider_id: provider_id.clone(), + platform: std::env::consts::OS.into(), + manifest_toml: context_manifest, + ..Default::default() + }, + composition.paths.clone(), + composition.library.clone(), + Arc::new(UnavailableExternalAccounts), + composition.login.clone(), + None, + )?)) + } + // The startup host always provides its composition. A test host that only exercises + // lifecycle registration still gets the process slot and extension schemas. + None => None, + } + } else { + None + }; + let host_services: Arc = match &services { + Some(services) => services.clone(), + None => Arc::new(super::provider::ExtensionServices), + }; + let package_root = installed.package_path.clone(); + let package_digest = + tokio::task::spawn_blocking(move || installed_package_digest(&package_root)) + .await + .map_err(|_| Status::internal("installed package digest worker failed"))? + .map_err(|_| Status::internal("installed package integrity is unavailable"))?; + let registration = Registration { + provider_id: provider_id.clone(), + plugin_id: installed.plugin_id.clone(), + kind: match report.manifest.kind { + super::package::PluginKind::Provider => super::provider::RegistrationKind::Provider, + super::package::PluginKind::Extension => super::provider::RegistrationKind::Extension, + }, + origin: super::provider::RegistrationOrigin::ThirdParty { + publisher_fingerprint: publisher_fingerprint.clone(), + }, + declared_developer: report.manifest.name.clone(), + package_digest, + playtime: report.manifest.playtime, + capabilities: config.manifest_capabilities.clone(), + shared_catalog: false, + services: host_services, + }; + let entry = services.map(|services| { + Arc::new(Entry { + services, + initialized: tokio::sync::Mutex::new(None), + packaged: true, + initialize: true, + }) + }); + Ok(PreparedManagedPackage { + provider_id, + plugin_id: installed.plugin_id, + publisher_fingerprint, + inventory, + config, + registration, + extension_schemas: report.extension_schemas, + entry, + }) +} + +/// Registers a prepared package with the shared API. A host rebuilt over an API that already +/// holds the same signed package (a restart or a test composition) continues composing the +/// process surface instead of dropping the package as a duplicate. +async fn register_prepared_management( + api: &ProviderApi, + provider_id: &str, + plugin_id: &str, + publisher_fingerprint: &str, + registration: Registration, + extension_schemas: &[gamenode_plugin_protocol::proto::ExtensionSchemaDescriptor], +) -> Result<(), Status> { + let registration_api = api.clone(); + match tokio::task::spawn_blocking(move || registration_api.register(registration)).await { + Ok(Ok(())) => {} + Ok(Err(error)) + if error.code() == tonic::Code::AlreadyExists + && api.third_party_identity(provider_id) + == Some((plugin_id.to_owned(), publisher_fingerprint.to_owned())) => {} + Ok(Err(error)) => return Err(error), + Err(_) => return Err(Status::internal("plugin registration worker failed")), + } + api.set_extension_schemas( + provider_id, + plugin_id, + publisher_fingerprint, + extension_schemas.to_vec(), + ) +} + +pub struct HostedProviders { + api: ProviderApi, + processes: ProviderProcesses, + intents: Arc, + endpoint_available: bool, + entries: BTreeMap>, + managed_plugins: Vec, + /// Registrations and inventory rows added by an accepted import after startup. + dynamic: Arc, + failures: Mutex>, + observer: Mutex>, + lifecycle: Arc, +} + +/// Account-scoped enable/disable controls for already registered managed plugins. Registration +/// and package validation remain host-owned; this service only starts verified process slots and +/// persists the user's per-account choice. +pub struct ThirdPartyPluginLifecycle { + api: ProviderApi, + processes: ProviderProcesses, + state: PluginStateLayout, + registry: gamenode_platform::plugin_registry::PluginPackageRegistry, + packages: ManagedPackageLifecycle, + mutation: tokio::sync::Mutex<()>, + /// Host composition used to register packages accepted after startup. Absent in tests that + /// only exercise lifecycle registration. + composition: Mutex>, + /// Host-only private store worker, connected by the desktop host. Absent in hosts and tests + /// that did not open `plugin-data`; private retention is then skipped rather than guessed. + private_storage: Mutex>>, + /// Single-use host-wide cleanup reviews. + cleanup_reviews: super::cleanup::CleanupReviews, + /// Single-use reviewed publisher-migration previews. + migration_reviews: super::migration::MigrationReviews, + #[cfg(test)] + sharing_commit_hook: Mutex>, + #[cfg(test)] + permission_commit_hook: Mutex>, +} + +/// Host-owned permission state for one installed third-party provider in the active account. +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct PluginPermissionSnapshot { + pub plugin_id: String, + pub publisher_fingerprint: String, + pub profile_id: String, + pub grant_revision: u64, + pub requested_permissions: Vec, + pub effective_grants: Vec, +} + +/// Host-owned configuration availability and the active signed package revision. +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct PluginConfigurationState { + pub plugin_id: String, + pub available: bool, + pub revision: Option, +} + +pub use super::retention::{ + DataRetention, DurableRetentionOutcome, DurableRetentionSink, PrivateReuseOutcome, +}; + +pub(crate) struct SharingIdentityObservation { + pub identity: PluginIdentity, + profile_epoch: u64, +} + +/// Host-resolved identity and owner used by uninstall retention and reviewed reuse. It comes from +/// the pinned registry and the active profile; a plugin RPC never supplies it. +struct RemovalIdentity { + resolver: super::namespace::ExternalNamespaceResolver, + owner: OwnerScope, + epoch: u64, +} + +#[cfg(test)] +#[derive(Clone, Copy)] +enum SharingCommitCheckpoint { + BeforeWrite, + AfterCommit, +} + +#[cfg(test)] +type SharingCommitHook = Arc; + +#[cfg(test)] +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum PermissionCommitCheckpoint { + Prepared, + BeforeWrite, + AfterCommit, +} + +#[cfg(test)] +type PermissionCommitHook = Arc; + +impl ThirdPartyPluginLifecycle { + pub fn new( + api: ProviderApi, + processes: ProviderProcesses, + state: PluginStateLayout, + registry: gamenode_platform::plugin_registry::PluginPackageRegistry, + packages: ManagedPackageLifecycle, + ) -> Self { + Self { + api, + processes, + state, + registry, + packages, + mutation: tokio::sync::Mutex::new(()), + composition: Mutex::new(None), + private_storage: Mutex::new(None), + cleanup_reviews: super::cleanup::CleanupReviews::default(), + migration_reviews: super::migration::MigrationReviews::default(), + #[cfg(test)] + sharing_commit_hook: Mutex::new(None), + #[cfg(test)] + permission_commit_hook: Mutex::new(None), + } + } + + /// Connects the host-owned composition surfaces a post-startup registration needs. This is + /// host wiring: no plugin IPC reaches it. + pub(crate) fn set_host_composition(&self, composition: HostComposition) { + *self + .composition + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(composition); + } + + /// Connects the host-only private store worker used by uninstall retention and host cleanup. + /// This is host wiring: no plugin IPC reaches it. + pub fn set_private_storage(&self, storage: Arc) { + *self + .private_storage + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(storage); + } + + pub(crate) fn private_storage(&self) -> Option> { + self.private_storage + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .clone() + } + + /// The provider API the host cleanup review enumerates producers from. + pub(crate) fn host_api(&self) -> &ProviderApi { + &self.api + } + + /// The issued host-wide cleanup reviews; single-use and bound to the active profile. + pub(crate) fn cleanup_reviews(&self) -> &super::cleanup::CleanupReviews { + &self.cleanup_reviews + } + + /// The issued publisher-migration previews; single-use and bound to the active profile. + pub(crate) fn migration_reviews(&self) -> &super::migration::MigrationReviews { + &self.migration_reviews + } + + /// The private trust directory, read by the reviewed migration preview for publisher history. + pub(crate) fn trust_dir(&self) -> std::path::PathBuf { + self.state.trust_dir() + } + + /// Registers every active, publisher-pinned package this runtime has not composed yet. + /// + /// The startup composition registers packages once. An explicitly accepted import installs a + /// package later, so this host-only step repeats the same manifest, trust, compatibility and + /// identity checks and registers the process slot without replacing the shared provider API + /// or process manager. The returned outcomes let a caller report a package that was installed + /// but could not be registered instead of claiming it is running. + pub(crate) async fn register_installed_packages( + &self, + ) -> Result, Status> { + let registry = self.registry.clone(); + let active = tokio::task::spawn_blocking(move || registry.active_versions()) + .await + .map_err(|_| Status::internal("plugin package registry worker failed"))? + .map_err(|_| Status::internal("plugin package registry is unavailable"))?; + let trust_dir = self.state.trust_dir(); + let trust = tokio::task::spawn_blocking(move || { + super::publisher_trust::PublisherTrustStore::open(trust_dir) + }) + .await + .map_err(|_| Status::internal("publisher trust worker failed"))? + .map_err(|_| Status::internal("publisher trust store is unavailable"))?; + let composition = self + .composition + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .clone(); + let mut outcomes = Vec::new(); + for installed in active { + let plugin_id = installed.plugin_id.clone(); + let registered = !self + .api + .third_party_provider_ids_for_plugin(&plugin_id) + .is_empty(); + let prepared = match prepare_managed_package( + installed, + &trust, + &self.packages, + composition.as_ref(), + ) + .await + { + Ok(prepared) => prepared, + Err(error) => { + outcomes.push(InstalledPackageRegistration { + plugin_id, + error: Some(error.message().to_owned()), + }); + continue; + } + }; + let PreparedManagedPackage { + provider_id, + plugin_id, + publisher_fingerprint, + inventory, + config, + registration, + extension_schemas, + entry, + } = prepared; + if registered { + // A newer version replaced the package while its provider stayed registered. + // Keep the host-owned identity, but point the supervised process at the new + // immutable config so an accepted import takes effect without a restart. The + // same immutable package is already fully registered and stays untouched. + let current_version = + self.processes + .config(&provider_id) + .ok() + .and_then(|current| { + current + .integrity + .as_ref() + .map(|integrity| integrity.version.clone()) + }); + let next_version = config + .integrity + .as_ref() + .map(|integrity| integrity.version.clone()); + if current_version == next_version { + continue; + } + let replaced = if self.processes.config(&provider_id).is_ok() { + self.processes.replace_config(&provider_id, config).await + } else { + self.processes.register_config(config) + }; + if let Err(error) = replaced { + outcomes.push(InstalledPackageRegistration { + plugin_id, + error: Some(error.message().to_owned()), + }); + continue; + } + if let Some(composition) = composition.as_ref() { + if let Some(entry) = entry { + composition.dynamic.insert_entry(provider_id, entry); + } + composition.dynamic.push_inventory(inventory); + } + outcomes.push(InstalledPackageRegistration { + plugin_id, + error: None, + }); + continue; + } + if let Err(error) = register_prepared_management( + &self.api, + &provider_id, + &plugin_id, + &publisher_fingerprint, + registration, + &extension_schemas, + ) + .await + { + outcomes.push(InstalledPackageRegistration { + plugin_id, + error: Some(error.message().to_owned()), + }); + continue; + } + if let Err(error) = self.processes.register_config(config) { + // Never leave a plugin registered without a process slot: a later retry would + // skip it as already registered. + let _ = self.api.unregister_third_party_plugin(&plugin_id).await; + outcomes.push(InstalledPackageRegistration { + plugin_id, + error: Some(error.message().to_owned()), + }); + continue; + } + if let Some(composition) = composition.as_ref() { + if let Some(entry) = entry { + composition.dynamic.insert_entry(provider_id, entry); + } + composition.dynamic.push_inventory(inventory); + } + outcomes.push(InstalledPackageRegistration { + plugin_id, + error: None, + }); + } + Ok(outcomes) + } + + /// Test-only observation that a package has a registered provider and a composed process + /// slot, not a half-applied registration. + #[cfg(test)] + pub(crate) fn has_process_slot(&self, plugin_id: &str) -> bool { + self.process_ids(plugin_id).is_ok() + } + + pub async fn enabled(&self, plugin_id: String) -> Result { + let profile = self.api.profiles().require()?; + let state = self.state.clone(); + tokio::task::spawn_blocking(move || { + state + .open_activation(&profile) + .map(|activation| activation.is_enabled(&plugin_id)) + .map_err(|error| Status::internal(format!("plugin activation state: {error}"))) + }) + .await + .map_err(|_| Status::internal("plugin activation worker failed"))? + } + + pub fn require_active_profile(&self) -> Result<(), Status> { + self.api.profiles().require().map(|_| ()) + } + + pub fn is_registered(&self, plugin_id: &str) -> bool { + self.api + .third_party_provider_ids_for_plugin(plugin_id) + .len() + == 1 + } + + pub(crate) fn extension_runtime_available(&self, plugin_id: &str) -> bool { + let slot = super::provider::extension_registration_id(plugin_id); + self.api.is_extension(&slot) && self.processes.extension_runtime_available(&slot) + } + + pub async fn enable(&self, plugin_id: String) -> Result<(), Status> { + self.set_enabled(plugin_id, true).await + } + + pub async fn disable(&self, plugin_id: String) -> Result<(), Status> { + self.set_enabled(plugin_id, false).await + } + + /// Reads the persisted permission decisions for one registered provider in the active + /// account. Disk access runs on a blocking worker, and a profile switch during that read + /// invalidates the result rather than returning another account's grants. + pub async fn permission_snapshot( + &self, + plugin_id: String, + ) -> Result { + let profile = self.api.profiles().require()?; + let provider_ids = self.api.third_party_provider_ids_for_plugin(&plugin_id); + let [provider_id] = provider_ids.as_slice() else { + return Err(Status::failed_precondition( + "plugin has no unique registered third-party provider", + )); + }; + let (registered_plugin_id, publisher_fingerprint) = self + .api + .third_party_identity(provider_id) + .ok_or_else(|| Status::failed_precondition("plugin identity is unavailable"))?; + if registered_plugin_id != plugin_id { + return Err(Status::failed_precondition( + "registered plugin identity changed", + )); + } + let requested_permissions = self + .managed_permission_requests(&plugin_id, &publisher_fingerprint) + .await?; + let profile_epoch = profile.epoch(); + let identity = super::grants::PluginIdentity { + plugin_id: registered_plugin_id.clone(), + publisher_fingerprint: publisher_fingerprint.clone(), + profile_id: profile.profile_id().to_owned(), + }; + let state = self.state.clone(); + let account = profile.clone(); + let (grant_revision, effective_grants) = tokio::task::spawn_blocking(move || { + let grants = state + .open_grants(&account) + .map_err(|error| Status::internal(format!("plugin grants unavailable: {error}")))?; + Ok::<_, Status>(( + grants.revision(&identity), + grants.effective_grants(&identity), + )) + }) + .await + .map_err(|_| Status::internal("plugin permission worker failed"))??; + if !self.api.profiles().is_current(profile_epoch) { + return Err(Status::failed_precondition( + "plugin profile changed while reading permissions", + )); + } + Ok(PluginPermissionSnapshot { + plugin_id: registered_plugin_id, + publisher_fingerprint, + profile_id: profile.profile_id().to_owned(), + grant_revision, + requested_permissions, + effective_grants, + }) + } + + /// Reads the permission review of a package that was just installed through a reviewed import + /// but whose provider is not registered for the active account yet. It resolves the same + /// verified manifest and grant store as [`Self::permission_snapshot`], so an import decision is + /// expressed in host-enforced scopes rather than manifest text. + pub(crate) async fn installed_permission_snapshot( + &self, + plugin_id: String, + publisher_fingerprint: String, + ) -> Result { + let profile = self.api.profiles().require()?; + let requested_permissions = self + .managed_permission_requests(&plugin_id, &publisher_fingerprint) + .await?; + let profile_epoch = profile.epoch(); + let identity = super::grants::PluginIdentity { + plugin_id: plugin_id.clone(), + publisher_fingerprint: publisher_fingerprint.clone(), + profile_id: profile.profile_id().to_owned(), + }; + let state = self.state.clone(); + let account = profile.clone(); + let (grant_revision, effective_grants) = tokio::task::spawn_blocking(move || { + let grants = state + .open_grants(&account) + .map_err(|error| Status::internal(format!("plugin grants unavailable: {error}")))?; + Ok::<_, Status>(( + grants.revision(&identity), + grants.effective_grants(&identity), + )) + }) + .await + .map_err(|_| Status::internal("plugin permission worker failed"))??; + if !self.api.profiles().is_current(profile_epoch) { + return Err(Status::failed_precondition( + "plugin profile changed while reading permissions", + )); + } + Ok(PluginPermissionSnapshot { + plugin_id, + publisher_fingerprint, + profile_id: profile.profile_id().to_owned(), + grant_revision, + requested_permissions, + effective_grants, + }) + } + + /// Observe the registered, trusted publisher and the active profile together. Package + /// signature verification uses the captured immutable installed version on a worker. + pub(crate) async fn observe_sharing_identity( + &self, + plugin_id: String, + expected_profile_id: &str, + ) -> Result { + let api = self.api.clone(); + let profiles = api.profiles(); + let registry = self.registry.clone(); + let trust_dir = self.state.trust_dir(); + let expected_profile_id = expected_profile_id.to_owned(); + let (observation, installed, key) = tokio::task::spawn_blocking(move || { + let _publisher = lock_publisher_identity(); + let profile = profiles.require()?; + if profile.profile_id() != expected_profile_id { + return Err(Status::failed_precondition("plugin profile changed")); + } + let fingerprint = registered_publisher(&api, &plugin_id)?; + let (installed, key) = + trusted_managed_package(®istry, &trust_dir, &plugin_id, &fingerprint)?; + let observation = SharingIdentityObservation { + identity: PluginIdentity { + plugin_id, + publisher_fingerprint: fingerprint, + profile_id: profile.profile_id().to_owned(), + }, + profile_epoch: profile.epoch(), + }; + Ok((observation, installed, key)) + }) + .await + .map_err(|_| Status::internal("plugin identity worker failed"))??; + self.verified_permission_requests(&installed, key).await?; + Ok(observation) + } + + pub(crate) async fn sharing_identity( + &self, + plugin_id: String, + expected_profile_id: &str, + ) -> Result { + let observation = self + .observe_sharing_identity(plugin_id, expected_profile_id) + .await?; + validate_sharing_profile(&self.api.profiles(), &observation)?; + Ok(observation.identity) + } + + /// The host-resolved durable shared-data owner of one installed plugin in the expected + /// profile. Settings use it to read retained usage and to delete it without uninstalling; the + /// publisher is verified exactly as for a policy review. + pub(crate) async fn durable_owner( + &self, + plugin_id: String, + expected_profile_id: &str, + ) -> Result { + let observation = self + .observe_sharing_identity(plugin_id, expected_profile_id) + .await?; + validate_sharing_profile(&self.api.profiles(), &observation)?; + let resolver = self.api.profiles().resolver( + &observation.identity.plugin_id, + &observation.identity.publisher_fingerprint, + None, + )?; + OwnerScope::new(*resolver.storage_owner().key(), observation.profile_epoch) + .map_err(|_| Status::failed_precondition("plugin profile is invalid")) + } + + pub(crate) async fn replace_sharing_policy( + &self, + observation: SharingIdentityObservation, + policies: Arc, + expected_revision: u64, + grant: ActivationReadGrant, + source_policies: Vec, + required_sources: Vec, + ) -> Result { + let api = self.api.clone(); + let registry = self.registry.clone(); + let trust_dir = self.state.trust_dir(); + #[cfg(test)] + let commit_hook = lock(&self.sharing_commit_hook).clone(); + tokio::task::spawn_blocking(move || { + // Fixed order: publisher identity, profile transition, then policy store. + // Publisher changes are fenced from validation through the durable commit. + let publisher = lock_publisher_identity(); + for identity in std::iter::once(&observation.identity).chain(&required_sources) { + let current = + registered_publisher(&api, &identity.plugin_id).and_then(|registered| { + if registered != identity.publisher_fingerprint { + return Err(sharing_identity_conflict()); + } + trusted_managed_package( + ®istry, + &trust_dir, + &identity.plugin_id, + ®istered, + ) + }); + match current { + Ok(_) => {} + Err(error) if error.code() == tonic::Code::Internal => return Err(error), + Err(_) => return Err(sharing_identity_conflict()), + } + } + let profiles = api.profiles(); + let transition = profiles.lock_transition(); + validate_sharing_profile(&profiles, &observation)?; + #[cfg(test)] + if let Some(hook) = &commit_hook { + hook(SharingCommitCheckpoint::BeforeWrite); + } + let saved = policies + .replace_recipient_policies_snapshot( + &observation.identity, + expected_revision, + grant, + source_policies, + ) + .map_err(|error| match error { + SharingPolicyError::StaleRevision => Status::aborted(error.to_string()), + _ => Status::internal(error.to_string()), + })?; + drop(transition); + drop(publisher); + #[cfg(test)] + if let Some(hook) = &commit_hook { + hook(SharingCommitCheckpoint::AfterCommit); + } + Ok(saved) + }) + .await + .map_err(|_| Status::internal("shared-data permission worker failed"))? + } + + /// Atomically replaces permissions only for the active account and the declarations in the + /// currently trusted package. The reviewed publisher, profile and revision fence stale UI writes. + pub(super) async fn replace_permissions( + &self, + activations: &tokio::sync::Mutex<()>, + plugin_id: String, + expected_profile_id: String, + expected_publisher_fingerprint: String, + expected_revision: u64, + decisions: Vec, + ) -> Result { + self.replace_reviewed_permissions( + activations, + plugin_id, + expected_profile_id, + expected_publisher_fingerprint, + expected_revision, + decisions, + true, + ) + .await + } + + /// Applies a reviewed import's permission decisions to the active profile. The package was + /// installed and publisher-pinned by the import, but its provider is only registered when the + /// host next composes the runtime, so the registration check is replaced by the installed and + /// trusted package verification the commit already performs. + pub(super) async fn replace_installed_permissions( + &self, + activations: &tokio::sync::Mutex<()>, + plugin_id: String, + expected_profile_id: String, + expected_publisher_fingerprint: String, + expected_revision: u64, + decisions: Vec, + ) -> Result { + self.replace_reviewed_permissions( + activations, + plugin_id, + expected_profile_id, + expected_publisher_fingerprint, + expected_revision, + decisions, + false, + ) + .await + } + + #[allow(clippy::too_many_arguments)] + async fn replace_reviewed_permissions( + &self, + activations: &tokio::sync::Mutex<()>, + plugin_id: String, + expected_profile_id: String, + expected_publisher_fingerprint: String, + expected_revision: u64, + decisions: Vec, + require_registration: bool, + ) -> Result { + let profiles = self.api.profiles(); + let profile = profiles.require()?; + if profile.profile_id() != expected_profile_id { + return Err(Status::failed_precondition("plugin profile changed")); + } + // Capture the profile before waiting on update activation so even a round trip + // to another account while queued invalidates this request. + let _activation = activations.lock().await; + let _mutation = self.mutation.lock().await; + let (installed, key) = self + .managed_package_for_permissions(&plugin_id, &expected_publisher_fingerprint) + .await?; + let requests = self.verified_permission_requests(&installed, key).await?; + let identity = PluginIdentity { + plugin_id, + publisher_fingerprint: expected_publisher_fingerprint, + profile_id: expected_profile_id, + }; + // A permission change fences a running extension before the new grants are saved. + let provider_ids = self + .api + .third_party_provider_ids_for_plugin(&identity.plugin_id); + if let [provider_id] = provider_ids.as_slice() + && self.api.is_extension(provider_id) + { + self.processes.terminate_provider(provider_id).await; + } + let state = self.state.clone(); + let registry = self.registry.clone(); + let api = self.api.clone(); + #[cfg(test)] + let commit_hook = lock(&self.permission_commit_hook).clone(); + tokio::task::spawn_blocking(move || { + #[cfg(test)] + let checkpoint = |point| { + if let Some(hook) = &commit_hook { + hook(point); + } + }; + #[cfg(test)] + checkpoint(PermissionCommitCheckpoint::Prepared); + + // Match the shared-data commit's lock order. The package was verified outside these + // locks. Recheck its immutable version and trusted publisher before saving. + let publisher = lock_publisher_identity(); + if require_registration + && registered_publisher(&api, &identity.plugin_id)? + != identity.publisher_fingerprint + { + return Err(Status::failed_precondition("plugin identity changed")); + } + let current = trusted_managed_package( + ®istry, + &state.trust_dir(), + &identity.plugin_id, + &identity.publisher_fingerprint, + )?; + if current != (installed, key) { + return Err(Status::failed_precondition( + "plugin package changed; reload and review", + )); + } + + let transition = profiles.lock_transition(); + if !profiles.current().is_some_and(|current| { + current.epoch() == profile.epoch() && current.profile_id() == identity.profile_id + }) { + return Err(Status::failed_precondition( + "plugin profile changed while saving permissions", + )); + } + let mut grants = state + .open_grants(&profile) + .map_err(|error| Status::internal(format!("plugin grants unavailable: {error}")))?; + if grants.revision(&identity) != expected_revision { + return Err(Status::aborted( + "plugin grants changed; refresh and try again", + )); + } + #[cfg(test)] + checkpoint(PermissionCommitCheckpoint::BeforeWrite); + let grant_revision = grants + .replace_grants(identity.clone(), &requests, &decisions) + .map_err(|error| { + Status::invalid_argument(format!("plugin permission decision: {error}")) + })?; + profiles.notify_permissions_changed(); + let saved = PluginPermissionSnapshot { + effective_grants: grants.effective_grants(&identity), + plugin_id: identity.plugin_id, + publisher_fingerprint: identity.publisher_fingerprint, + profile_id: identity.profile_id, + grant_revision, + requested_permissions: requests, + }; + drop(transition); + drop(publisher); + #[cfg(test)] + checkpoint(PermissionCommitCheckpoint::AfterCommit); + Ok(saved) + }) + .await + .map_err(|_| Status::internal("plugin permission worker failed"))? + } + + async fn managed_permission_requests( + &self, + plugin_id: &str, + registered_fingerprint: &str, + ) -> Result, Status> { + let (installed, publisher_key) = self + .managed_package_for_permissions(plugin_id, registered_fingerprint) + .await?; + self.verified_permission_requests(&installed, publisher_key) + .await + } + + async fn managed_package_for_permissions( + &self, + plugin_id: &str, + fingerprint: &str, + ) -> Result<(InstalledPluginVersion, [u8; 32]), Status> { + let registry = self.registry.clone(); + let trust_dir = self.state.trust_dir(); + let plugin_id = plugin_id.to_owned(); + let fingerprint = fingerprint.to_owned(); + tokio::task::spawn_blocking(move || { + trusted_managed_package(®istry, &trust_dir, &plugin_id, &fingerprint) + }) + .await + .map_err(|_| Status::internal("plugin publisher worker failed"))? + } + + async fn verified_permission_requests( + &self, + installed: &InstalledPluginVersion, + publisher_key: [u8; 32], + ) -> Result, Status> { + let report = self + .packages + .inspect_candidate( + &installed.package_path, + publisher_key, + gamenode_platform::plugin_environment::EmulationPolicy::RequireNative, + ) + .await + .map_err(|_| Status::failed_precondition("plugin package validation failed"))?; + if report.manifest.id != installed.plugin_id || report.manifest.version != installed.version + { + return Err(Status::failed_precondition( + "plugin manifest does not match the installed package", + )); + } + super::grants::manifest_permission_requests(&report.manifest.permissions).map_err(|error| { + Status::failed_precondition(format!( + "plugin permission scopes are unsupported: {error}" + )) + }) + } + + /// Reports only whether the active signed manifest offers host-supported configuration + /// modes and which package revision declared them. Plugin-owned preferences are never read. + pub async fn configuration_state( + &self, + plugin_id: String, + ) -> Result { + let provider_ids = self.api.third_party_provider_ids_for_plugin(&plugin_id); + let [provider_id] = provider_ids.as_slice() else { + return Err(Status::failed_precondition( + "plugin has no unique registered third-party provider", + )); + }; + let (registered_plugin_id, registered_fingerprint) = self + .api + .third_party_identity(provider_id) + .ok_or_else(|| Status::failed_precondition("plugin identity is unavailable"))?; + if registered_plugin_id != plugin_id { + return Err(Status::failed_precondition( + "registered plugin identity changed", + )); + } + + let registry = self.registry.clone(); + let lookup_id = plugin_id.clone(); + let installed = tokio::task::spawn_blocking(move || registry.active(&lookup_id)) + .await + .map_err(|_| Status::internal("plugin package state worker failed"))? + .map_err(|_| Status::internal("plugin package state is unavailable"))?; + let Some(installed) = installed else { + return Ok(PluginConfigurationState { + plugin_id, + available: false, + revision: None, + }); + }; + + let package_path = installed.package_path.clone(); + let package_plugin_id = installed.plugin_id.clone(); + let trust_dir = self.state.trust_dir(); + let (publisher_key, trusted_fingerprint) = tokio::task::spawn_blocking(move || { + let publisher_key = super::updates::package_key(&package_path) + .map_err(|_| Status::failed_precondition("active plugin package is invalid"))?; + let trust = super::publisher_trust::PublisherTrustStore::open(trust_dir) + .map_err(|_| Status::internal("plugin publisher trust is unavailable"))?; + if !trust + .is_pinned(&package_plugin_id, &publisher_key) + .map_err(|_| Status::internal("plugin publisher trust is invalid"))? + { + return Err(Status::permission_denied( + "active plugin publisher is not trusted", + )); + } + use sha2::Digest as _; + let fingerprint = format!("SHA256:{:x}", sha2::Sha256::digest(publisher_key)); + Ok((publisher_key, fingerprint)) + }) + .await + .map_err(|_| Status::internal("plugin publisher trust worker failed"))??; + if trusted_fingerprint != registered_fingerprint { + return Err(Status::failed_precondition( + "active plugin publisher does not match its registration", + )); + } + let report = self + .packages + .inspect_candidate( + &installed.package_path, + publisher_key, + gamenode_platform::plugin_environment::EmulationPolicy::RequireNative, + ) + .await + .map_err(|_| Status::failed_precondition("active plugin package is invalid"))?; + if report.manifest.id != plugin_id || report.manifest.version != installed.version { + return Err(Status::failed_precondition( + "active plugin manifest does not match its package revision", + )); + } + let modes = report.manifest.configuration; + Ok(PluginConfigurationState { + plugin_id, + available: modes.external || modes.declarative, + revision: Some(format!( + "{}:external={}:declarative={}", + installed.version, modes.external, modes.declarative + )), + }) + } + + /// Probes an inactive package in an Extension session before changing the active pointer. + async fn activate_extension_update( + &self, + previous_version: String, + installed: gamenode_platform::plugin_registry::InstalledPluginVersion, + mut config: ProcessConfig, + target: ExtensionTarget, + ) -> Result<(), Status> { + use super::{grants::PluginIdentity, publisher_trust}; + let profiles = self.api.profiles(); + let profile = profiles.require()?; + let validate_target = move |target: &ExtensionTarget| { + if !target.is_current() + || profiles.current().is_none_or(|profile| { + !profile.verified() + || profile.epoch() != target.profile_epoch + || profile.profile_id() != target.context.profile_id + }) + { + return Err(Status::failed_precondition( + "selected extension target or profile changed", + )); + } + Ok(()) + }; + validate_target(&target)?; + let slot = config.provider_id.clone(); + if !self.processes.extension_runtime_available(&slot) { + return Err(Status::unavailable("extension runtime is unavailable")); + } + let previous = self.processes.config(&slot)?; + let key = config + .integrity + .as_ref() + .filter(|integrity| { + integrity.version == installed.version + && integrity.package_root == installed.package_path + }) + .map(|integrity| integrity.publisher_key) + .ok_or_else(|| Status::failed_precondition("candidate package identity changed"))?; + let previous_root = previous + .integrity + .as_ref() + .filter(|integrity| { + integrity.version == previous_version && integrity.publisher_key == key + }) + .map(|integrity| integrity.package_root.clone()) + .ok_or_else(|| { + Status::failed_precondition("active extension package identity changed") + })?; + let identity = PluginIdentity { + plugin_id: installed.plugin_id.clone(), + publisher_fingerprint: publisher_trust::key_fingerprint(&key), + profile_id: profile.profile_id().to_owned(), + }; + let validate_package = { + let state = self.state.clone(); + let registry = self.registry.clone(); + let api = self.api.clone(); + let slot = slot.clone(); + let installed = installed.clone(); + let identity = identity.clone(); + let previous_version = previous_version.clone(); + move || { + let registered = api.third_party_identity(&slot); + let trusted = publisher_trust::PublisherTrustStore::open(state.trust_dir()) + .and_then(|trust| trust.is_pinned(&installed.plugin_id, &key)) + .map_err(|error| Status::internal(error.to_string()))?; + let active = registry + .active(&installed.plugin_id) + .map_err(|error| Status::internal(error.to_string()))?; + if !trusted + || !api.is_extension(&slot) + || registered.as_ref() + != Some(&( + identity.plugin_id.clone(), + identity.publisher_fingerprint.clone(), + )) + || active.is_none_or(|active| { + active.version != previous_version + || active.package_path != previous_root + || super::updates::package_key(&active.package_path).ok() != Some(key) + }) + { + return Err(Status::failed_precondition( + "active extension identity changed", + )); + } + Ok(()) + } + }; + // Fence the old process before changing grants. An old action is never restarted. + self.processes + .replace_config(&slot, previous.clone()) + .await?; + let grant_revision = { + let validate_package = validate_package.clone(); + let validate_target = validate_target.clone(); + let target = target.clone(); + let profiles = self.api.profiles(); + let state = self.state.clone(); + let profile = profile.clone(); + let identity = identity.clone(); + let blocked = config.blocked_capabilities.iter().cloned().collect(); + tokio::task::spawn_blocking(move || { + let _publisher = lock_publisher_identity(); + let _profile = profiles.lock_transition(); + validate_package()?; + validate_target(&target)?; + let mut grants = state + .open_grants(&profile) + .map_err(|error| Status::internal(error.to_string()))?; + grants + .revoke_permissions(&identity, &blocked) + .map_err(|error| Status::internal(error.to_string())) + }) + .await + .map_err(|_| Status::internal("extension grant worker failed"))?? + }; + let ready = self + .processes + .ensure_extension_ready_for_update(&slot, target.clone(), config.clone()) + .await; + // Wait for the provisional tree and fence its session before committing. + // The slot retains the previous configuration even if cleanup fails. + self.processes.replace_config(&slot, previous).await?; + ready?; + let registry = self.registry.clone(); + let profiles = self.api.profiles(); + let state = self.state.clone(); + tokio::task::spawn_blocking(move || { + let _publisher = lock_publisher_identity(); + let _profile = profiles.lock_transition(); + validate_package()?; + let grants = state.open_grants(&profile) + .map_err(|error| Status::internal(error.to_string()))?; + if grants.revision(&identity) != grant_revision { + return Err(Status::failed_precondition("extension grants changed during readiness")); + } + validate_target(&target)?; + let outcome = registry.set_active(&installed.plugin_id, &installed.version) + .map_err(|error| Status::internal(error.to_string())) + // Also catch library changes while the registry write was in progress. + .and_then(|()| validate_target(&target)); + if let Err(error) = outcome { + // set_active can report a sync error after replacing the pointer. + if registry.active(&installed.plugin_id).ok().flatten().as_ref() == Some(&installed) { + registry.set_active(&installed.plugin_id, &previous_version) + .map_err(|restore| Status::internal(format!( + "extension activation failed ({error}); previous version could not be restored ({restore})" + )))?; + } + return Err(error); + } + Ok(()) + }) + .await + .map_err(|_| Status::internal("extension activation worker failed"))??; + // Ordinary extension starts share the mutation lock and can only see this config + // once the guarded registry commit above has completed. + config.blocked_capabilities.clear(); + self.processes.replace_config(&slot, config).await + } + + /// Atomically activates an already-installed candidate only after its supervised process + /// completes the bounded Ready handshake with the account's current grants. + pub(crate) async fn activate_update( + &self, + plugin_id: String, + previous_version: String, + installed: gamenode_platform::plugin_registry::InstalledPluginVersion, + config: ProcessConfig, + extension_target: Option, + ) -> Result<(), Status> { + let _mutation = self.mutation.lock().await; + if installed.plugin_id != plugin_id || installed.version == previous_version { + return Err(Status::invalid_argument("invalid staged plugin update")); + } + let provider_ids = self.api.third_party_provider_ids_for_plugin(&plugin_id); + if provider_ids.len() != 1 || provider_ids[0] != config.provider_id { + return Err(Status::failed_precondition( + "managed plugin has no unique registered provider runtime", + )); + } + if self.api.is_extension(&config.provider_id) { + let target = extension_target.ok_or_else(|| { + Status::failed_precondition("select a game for the extension readiness check") + })?; + return self + .activate_extension_update(previous_version, installed, config, target) + .await; + } + if extension_target.is_some() { + return Err(Status::invalid_argument( + "provider updates take no extension target", + )); + } + let profile = self.api.profiles().require()?; + let profile_epoch = profile.epoch(); + let state = self.state.clone(); + let account = profile.clone(); + let enabled = tokio::task::spawn_blocking(move || { + state + .open_activation(&account) + .map(|activation| activation.is_enabled(&plugin_id)) + .map_err(|error| Status::internal(format!("plugin activation state: {error}"))) + }) + .await + .map_err(|_| Status::internal("plugin activation worker failed"))??; + let previous_config = self.processes.config(&config.provider_id)?; + self.processes.stop_plugin(&installed.plugin_id).await; + + let registry = self.registry.clone(); + let candidate_id = installed.plugin_id.clone(); + let candidate_version = installed.version.clone(); + let expected_previous = previous_version.clone(); + let transaction = tokio::task::spawn_blocking(move || { + let _publisher = lock_publisher_identity(); + registry.begin_activation(&candidate_id, &expected_previous, &candidate_version) + }) + .await + .map_err(|_| Status::internal("plugin activation worker failed"))? + .map_err(|error| Status::failed_precondition(error.to_string()))?; + + let result = async { + if !config.blocked_capabilities.is_empty() { + let (plugin_id, publisher_fingerprint) = self + .api + .third_party_identity(&config.provider_id) + .ok_or_else(|| Status::failed_precondition("plugin identity is unavailable"))?; + let blocked = config.blocked_capabilities.iter().cloned().collect(); + let state = self.state.clone(); + let account = profile.clone(); + tokio::task::spawn_blocking(move || { + let mut grants = state + .open_grants(&account) + .map_err(|error| Status::internal(format!("plugin grants: {error}")))?; + grants + .revoke_permissions( + &super::grants::PluginIdentity { + plugin_id, + publisher_fingerprint, + profile_id: account.profile_id().to_owned(), + }, + &blocked, + ) + .map_err(|error| { + Status::internal(format!("plugin grant revocation: {error}")) + }) + }) + .await + .map_err(|_| Status::internal("plugin grant worker failed"))??; + } + self.processes + .replace_config(&config.provider_id, config.clone()) + .await?; + if !self.api.profiles().is_current(profile_epoch) { + return Err(Status::failed_precondition( + "plugin profile changed during update activation", + )); + } + self.processes + .ensure_ready_for_update(&config.provider_id) + .await?; + if !self.api.profiles().is_current(profile_epoch) { + return Err(Status::failed_precondition( + "plugin profile changed during update readiness check", + )); + } + if !enabled { + self.processes.terminate_provider(&config.provider_id).await; + } + let registry = self.registry.clone(); + let transaction_to_commit = transaction.clone(); + let commit = tokio::task::spawn_blocking(move || { + let _publisher = lock_publisher_identity(); + registry.commit_activation(transaction_to_commit) + }) + .await; + match commit { + Ok(result) => result.map_err(|error| Status::internal(error.to_string()))?, + Err(_) => { + // The blocking worker cannot be aborted after it starts. Retry by transaction + // idempotently in case it durably committed before its JoinError was observed. + let registry = self.registry.clone(); + let retry = transaction.clone(); + tokio::task::spawn_blocking(move || { + let _publisher = lock_publisher_identity(); + registry.commit_activation(retry) + }) + .await + .map_err(|_| Status::internal("plugin activation worker failed"))? + .map_err(|error| Status::internal(error.to_string()))?; + } + } + Ok(()) + } + .await; + + if let Err(error) = result { + self.processes.terminate_provider(&config.provider_id).await; + let registry = self.registry.clone(); + let transaction_to_rollback = transaction; + let rollback = tokio::task::spawn_blocking(move || { + let _publisher = lock_publisher_identity(); + registry.rollback_activation(transaction_to_rollback) + }) + .await + .map_err(|_| Status::internal("plugin rollback worker failed"))?; + if let Err(rollback_error) = rollback { + return Err(Status::internal(format!( + "candidate activation failed ({error}); rollback is pending recovery ({rollback_error})" + ))); + } + let previous_provider_id = previous_config.provider_id.clone(); + self.processes + .replace_config(&previous_provider_id, previous_config) + .await?; + if enabled + && !self.api.is_extension(&config.provider_id) + && self.api.profiles().is_current(profile_epoch) + && let Err(restart_error) = self.processes.ensure_started(&config.provider_id).await + { + return Err(Status::unavailable(format!( + "candidate activation failed ({error}); previous version was restored but could not restart ({restart_error})" + ))); + } + return Err(error); + } + Ok(()) + } + + /// Starts the plugins enabled in the active account after registration has been restored. + pub async fn start_enabled_plugins(&self) -> Result<(), Status> { + let profile = self.api.profiles().require()?; + let profile_epoch = profile.epoch(); + let state = self.state.clone(); + let account_profile = profile.clone(); + let enabled = tokio::task::spawn_blocking(move || { + state + .open_activation(&account_profile) + .map(|activation| activation.enabled().map(str::to_owned).collect::>()) + .map_err(|error| Status::internal(format!("plugin activation state: {error}"))) + }) + .await + .map_err(|_| Status::internal("plugin activation worker failed"))??; + for plugin_id in enabled { + if !self.api.profiles().is_current(profile_epoch) { + return Err(Status::failed_precondition( + "plugin profile changed during lifecycle restore", + )); + } + self.set_enabled_for_profile(plugin_id, true, Some(profile_epoch)) + .await?; + } + Ok(()) + } + + async fn set_enabled(&self, plugin_id: String, enabled: bool) -> Result<(), Status> { + self.set_enabled_for_profile(plugin_id, enabled, None).await + } + + async fn set_enabled_for_profile( + &self, + plugin_id: String, + enabled: bool, + expected_epoch: Option, + ) -> Result<(), Status> { + let _mutation = self.mutation.lock().await; + let profile = self.api.profiles().require()?; + if expected_epoch.is_some_and(|expected| expected != profile.epoch()) { + return Err(Status::failed_precondition( + "plugin profile changed during lifecycle restore", + )); + } + let process_ids = self.process_ids(&plugin_id)?; + for id in process_ids.iter().filter(|id| self.api.is_extension(id)) { + if enabled { + if !self.processes.extension_runtime_available(id) { + return Err(Status::unavailable("extension runtime is unavailable")); + } + } else { + self.processes.terminate_provider(id).await; + } + } + let state = self.state.clone(); + let account = profile.clone(); + let plugin = plugin_id.clone(); + tokio::task::spawn_blocking(move || { + let mut activation = state + .open_activation(&account) + .map_err(|error| Status::internal(format!("plugin activation state: {error}")))?; + activation + .set_enabled(&plugin, enabled) + .map_err(|error| Status::internal(format!("plugin activation state: {error}"))) + }) + .await + .map_err(|_| Status::internal("plugin activation worker failed"))??; + + if !enabled { + for provider_id in process_ids { + if !self.api.is_extension(&provider_id) { + self.processes.terminate_provider(&provider_id).await; + self.api.disconnect(&provider_id).await; + } + } + return Ok(()); + } + + if !self.api.profiles().is_current(profile.epoch()) + || expected_epoch.is_some_and(|expected| expected != profile.epoch()) + { + return Err(Status::failed_precondition( + "plugin profile changed during lifecycle restore", + )); + } + for provider_id in &process_ids { + if self.api.is_extension(provider_id) { + continue; + } + if let Err(error) = self.processes.ensure_started(provider_id).await { + for provider_id in &process_ids { + self.processes.terminate_provider(provider_id).await; + self.api.disconnect(provider_id).await; + } + let state = self.state.clone(); + let account = profile; + let plugin = plugin_id; + let _ = tokio::task::spawn_blocking(move || { + if let Ok(mut activation) = state.open_activation(&account) { + let _ = activation.set_enabled(&plugin, false); + } + }) + .await; + return Err(error); + } + } + Ok(()) + } + + /// The host-resolved durable owner of an installed plugin, without re-reading its manifest. + /// + /// Uninstall must not depend on package byte verification: a broken or incompatible package + /// still has to be removable, while its retained data must stay attributed to the identity the + /// pinned registry and the active profile already established. + async fn removal_identity(&self, plugin_id: &str) -> Result { + let profile = self.api.profiles().require()?; + let provider_ids = self.api.third_party_provider_ids_for_plugin(plugin_id); + let [provider_id] = provider_ids.as_slice() else { + return Err(Status::failed_precondition( + "third-party plugin has no unique registered provider", + )); + }; + let (registered_id, publisher_fingerprint) = + self.api.third_party_identity(provider_id).ok_or_else(|| { + Status::failed_precondition("third-party plugin identity is unavailable") + })?; + if registered_id != plugin_id { + return Err(Status::failed_precondition( + "registered plugin identity changed", + )); + } + let resolver = self + .api + .profiles() + .resolver(plugin_id, &publisher_fingerprint, None)?; + let owner = OwnerScope::new(*resolver.storage_owner().key(), profile.epoch()) + .map_err(|_| Status::failed_precondition("plugin profile is invalid"))?; + Ok(RemovalIdentity { + resolver, + owner, + epoch: profile.epoch(), + }) + } + + /// Applies one keep-or-delete choice to a producer's durable shared records. Keep archives + /// them under the original owner; delete removes them and reports the reclaimed bytes. Another + /// owner's rows and the private plugin stores are never touched. + pub(crate) async fn apply_durable_retention( + &self, + plugin_id: &str, + retention: DataRetention, + ) -> Result { + let identity = self.removal_identity(plugin_id).await?; + self.apply_identity_retention(plugin_id, &identity, retention) + .await + } + + /// Applies the same choice to the durable shared rows and the private persistence entries of + /// one resolved identity. Private retention is skipped, not guessed, when this host has no + /// private store worker. + async fn apply_identity_retention( + &self, + plugin_id: &str, + identity: &RemovalIdentity, + retention: DataRetention, + ) -> Result { + let now = unix_now()?; + let pool = self.api.shared_pool(); + let mut outcome = DurableRetentionOutcome { + plugin_id: plugin_id.to_owned(), + data_retention: retention.as_str(), + archived_records: 0, + removed_records: 0, + reclaimed_bytes: 0, + private_archived_records: 0, + private_removed_records: 0, + private_reclaimed_bytes: 0, + }; + match retention { + DataRetention::Keep => { + outcome.archived_records = pool + .archive_owner(identity.owner, now) + .await? + .map_or(0, |archived| archived.records); + } + DataRetention::Delete => { + if let Some(deleted) = pool.delete_owner(identity.owner, now).await? { + outcome.removed_records = deleted.removed_records; + outcome.reclaimed_bytes = deleted.reclaimed_bytes; + } + } + } + if let Some(storage) = self.private_storage() { + match retention { + DataRetention::Keep => { + let archived = storage + .archive_persistence(&identity.resolver, identity.epoch) + .await?; + outcome.private_archived_records = archived.records; + } + DataRetention::Delete => { + let removed = storage + .remove_persistence_namespace(&identity.resolver, identity.epoch) + .await?; + outcome.private_removed_records = removed.records; + outcome.private_reclaimed_bytes = removed.logical_bytes; + } + } + } + Ok(outcome) + } + + /// Restores one reinstall's archived private entries after a separate host review. The owner + /// comes from the pinned registry identity and the active profile, so a consumer or a new + /// package cannot call this on another producer's data. Nothing changes without confirmation. + pub async fn reuse_archived_private_data( + &self, + plugin_id: String, + expected_profile_id: &str, + confirmed: bool, + ) -> Result { + if !confirmed { + return Err(Status::failed_precondition( + "reusing archived private data requires confirmation", + )); + } + let profile = self.api.profiles().require()?; + if profile.profile_id() != expected_profile_id { + return Err(Status::failed_precondition("plugin profile changed")); + } + let identity = self.removal_identity(&plugin_id).await?; + let storage = self.private_storage().ok_or_else(|| { + Status::failed_precondition("private plugin data is unavailable on this host") + })?; + let restored = storage + .reuse_archived_persistence(&identity.resolver, identity.epoch) + .await?; + Ok(PrivateReuseOutcome { + plugin_id, + restored_records: restored.records, + logical_bytes: restored.logical_bytes, + }) + } + + /// Restores one reinstall's archived durable records after a separate host review. The owner + /// comes from the pinned registry identity and the active profile, so a consumer or a new + /// package cannot call this on another producer's data. + pub async fn reuse_archived_durable_data( + &self, + plugin_id: String, + expected_profile_id: &str, + confirmed: bool, + ) -> Result { + if !confirmed { + return Err(Status::failed_precondition( + "reusing archived shared data requires confirmation", + )); + } + let profile = self.api.profiles().require()?; + if profile.profile_id() != expected_profile_id { + return Err(Status::failed_precondition("plugin profile changed")); + } + // The package identity is pinned in the registry; byte verification is not required to + // find the owner, so a damaged reinstall can still be reviewed and cleaned up. + let identity = self.removal_identity(&plugin_id).await?; + let now = unix_now()?; + let reused = self + .api + .shared_pool() + .reuse_archived_owner(identity.owner, now) + .await? + .map_or(0, |reused| reused.records); + Ok(DurableRetentionOutcome { + plugin_id, + data_retention: DataRetention::Keep.as_str(), + archived_records: reused, + removed_records: 0, + reclaimed_bytes: 0, + private_archived_records: 0, + private_removed_records: 0, + private_reclaimed_bytes: 0, + }) + } + + /// Uninstalls one plugin after applying an explicit durable-data retention choice. The choice + /// is applied before the package and account state are removed, so the verified installation + /// identity is still available; keeping archives the rows, deleting removes only that owner. + pub async fn remove_with_retention( + &self, + plugin_id: String, + retention: DataRetention, + ) -> Result { + let _mutation = self.mutation.lock().await; + let profile = self.api.profiles().require()?; + let registry = self.registry.clone(); + let lookup_id = plugin_id.clone(); + let installed = tokio::task::spawn_blocking(move || registry.active(&lookup_id)) + .await + .map_err(|_| Status::internal("plugin package worker failed"))? + .map_err(|_| Status::internal("plugin package state is unavailable"))?; + if installed.is_none() { + return Err(Status::not_found("third-party plugin is not installed")); + } + let provider_ids = self.api.third_party_provider_ids_for_plugin(&plugin_id); + for id in provider_ids.iter().filter(|id| self.api.is_extension(id)) { + self.processes.terminate_provider(id).await; + } + + let state = self.state.clone(); + let account = profile.clone(); + let plugin = plugin_id.clone(); + tokio::task::spawn_blocking(move || { + let mut activation = state + .open_activation(&account) + .map_err(|error| Status::internal(format!("plugin activation state: {error}")))?; + activation + .set_enabled(&plugin, false) + .map_err(|error| Status::internal(format!("plugin activation state: {error}"))) + }) + .await + .map_err(|_| Status::internal("plugin activation worker failed"))??; + for provider_id in provider_ids.iter().filter(|id| !self.api.is_extension(id)) { + self.processes.terminate_provider(provider_id).await; + self.api.disconnect(provider_id).await; + } + // Drop the immutable slots now, while the registration still lets us resolve them. + // Otherwise a reinstall accepted in this same session would collide with the old slot. + for provider_id in &provider_ids { + self.processes.unregister_config(provider_id).await; + } + // Apply the choice after the producer sessions are gone, so a publication racing the + // uninstall cannot leave a new live row behind. The registration is still available for + // resolving the owner; it is removed below. A plugin that was installed without a unique + // registration has no resolvable owner and must still be removable; no other identity's + // rows are guessed or touched. + let durable = match self.removal_identity(&plugin_id).await { + Ok(identity) => { + self.apply_identity_retention(&plugin_id, &identity, retention) + .await? + } + Err(error) if error.code() == tonic::Code::FailedPrecondition => { + tracing::warn!(plugin = %plugin_id, %error, "retention skipped at uninstall"); + DurableRetentionOutcome { + plugin_id: plugin_id.clone(), + data_retention: retention.as_str(), + archived_records: 0, + removed_records: 0, + reclaimed_bytes: 0, + private_archived_records: 0, + private_removed_records: 0, + private_reclaimed_bytes: 0, + } + } + Err(error) => return Err(error), + }; + if !provider_ids.is_empty() { + self.api.unregister_third_party_plugin(&plugin_id).await?; + } + self.packages + .remove_plugin(plugin_id.clone()) + .await + .map_err(package_status)?; + let state = self.state.clone(); + tokio::task::spawn_blocking(move || state.remove_plugin_account_state(&plugin_id)) + .await + .map_err(|_| Status::internal("plugin state removal worker failed"))? + .map_err(|error| Status::internal(format!("plugin account state: {error}")))?; + Ok(durable) + } + + /// Removes one plugin and keeps its durable shared records (the default uninstall choice). + pub async fn remove(&self, plugin_id: String) -> Result<(), Status> { + self.remove_with_retention(plugin_id, DataRetention::Keep) + .await + .map(|_| ()) + } + + /// Stops the supervised processes of one bundle component with the ordinary bounded grace + /// before a bundle update or rollback swaps its active package. Activation state, grants and + /// registrations are left untouched. + pub async fn stop_bundle_component(&self, plugin_id: &str) { + let provider_ids = self.api.third_party_provider_ids_for_plugin(plugin_id); + for provider_id in &provider_ids { + self.processes.terminate_provider(provider_id).await; + } + for provider_id in provider_ids.iter().filter(|id| !self.api.is_extension(id)) { + self.api.disconnect(provider_id).await; + } + } + + /// Uninstalls one installed bundle: the shared removal primitive stops every active component + /// with the bounded grace and deletes the mapped package versions and mapping, then this + /// wrapper unregisters the removed components, clears their activation and grants for the + /// active account, and applies one private-data retention choice. + /// + /// A partial failure is returned in the outcome, never dropped: each component that could not + /// be removed (or whose account state or data could not be cleared) is listed by plugin id. + pub async fn remove_bundle( + &self, + bundle_id: String, + bundles: gamenode_platform::plugin_bundle_db::SqlitePluginBundleStore, + delete_data: bool, + ) -> Result { + let _mutation = self.mutation.lock().await; + let profile = self + .api + .profiles() + .require() + .map_err(|_| super::bundles::BundleUninstallError::SignInRequired)?; + let retention = if delete_data { + super::bundles::BundleDataRetention::Delete + } else { + super::bundles::BundleDataRetention::Keep + }; + let data_root = self.state.plugin_data_root().map(Path::to_path_buf); + let private_data = data_root + .as_deref() + .map(|root| super::bundles::BundlePrivateData { + root, + profile_id: profile.profile_id(), + }); + let mut outcome = super::bundles::uninstall_bundle( + bundle_id, + self.registry.clone(), + bundles, + &self.processes, + retention, + private_data, + ) + .await?; + + // The bundle mapping only covers packages, so the same keep-or-delete choice is applied + // separately to each removed component's durable shared records. Keeping archives them + // under the owner; deleting removes only that owner's rows. + let durable = super::bundles::apply_bundle_durable_retention( + &outcome.removed, + if delete_data { + DataRetention::Delete + } else { + DataRetention::Keep + }, + self, + ) + .await; + outcome + .failures + .extend(durable.failures.into_iter().map(|failure| { + super::bundles::BundleRemovalFailure { + plugin_id: failure.plugin_id, + version: failure.version, + error: format!("durable shared data: {}", failure.error), + } + })); + + // The private namespaces were archived or deleted directly on disk. Drop any cached + // connection now, while each removed component's registration still resolves its owner, + // so a later install cannot read through an old handle. + self.forget_removed_private_namespaces(&outcome.removed) + .await; + + let state = self.state.clone(); + let removed = outcome.removed.clone(); + let mut failures = Vec::new(); + for component in &removed { + // Resolve the slots before unregistering the plugin: the mapping is the only way to + // find them, and an uninstall followed by a reinstall in the same session must not + // collide with a stale immutable configuration. + let slot_ids = self + .api + .third_party_provider_ids_for_plugin(&component.plugin_id); + // Packages are gone, so the runtime must not keep a registration that could start + // them again. A failure here is reported instead of aborting the other components. + if let Err(error) = self + .api + .unregister_third_party_plugin(&component.plugin_id) + .await + { + failures.push(super::bundles::BundleRemovalFailure { + plugin_id: component.plugin_id.clone(), + version: component.version.clone(), + error: format!("runtime registration: {}", error.message()), + }); + } else { + for slot_id in &slot_ids { + self.processes.unregister_config(slot_id).await; + } + } + } + let account_failures = tokio::task::spawn_blocking(move || { + let mut problems = Vec::new(); + for component in removed { + if let Err(error) = state.remove_plugin_account_state(&component.plugin_id) { + problems.push(super::bundles::BundleRemovalFailure { + plugin_id: component.plugin_id, + version: component.version, + error: format!("account state: {error}"), + }); + } + } + problems + }) + .await + .map_err(|_| super::bundles::BundleUninstallError::WorkerFailed)?; + failures.extend(account_failures); + outcome.failures.extend(failures); + Ok(outcome) + } + + /// Drops cached private namespaces for removed bundle components. A component whose identity + /// no longer resolves is skipped; its files were already handled by the uninstall. + async fn forget_removed_private_namespaces( + &self, + removed: &[super::bundles::RemovedBundleComponent], + ) { + let Some(storage) = self.private_storage() else { + return; + }; + for component in removed { + let Ok(identity) = self.removal_identity(&component.plugin_id).await else { + continue; + }; + if let Err(error) = storage + .forget_persistence_namespace(&identity.resolver, identity.epoch) + .await + { + tracing::warn!( + plugin = %component.plugin_id, + %error, + "private namespace cache could not be dropped after bundle uninstall" + ); + } + } + } + + fn process_ids(&self, plugin_id: &str) -> Result, Status> { + let registered = self.api.third_party_provider_ids_for_plugin(plugin_id); + if registered.is_empty() { + return Err(Status::not_found("third-party plugin is not registered")); + } + let process_ids = registered + .into_iter() + .filter(|provider_id| self.processes.has_provider(provider_id)) + .collect::>(); + if process_ids.is_empty() { + return Err(Status::failed_precondition( + "third-party plugin has no verified process configuration", + )); + } + Ok(process_ids) + } + + pub(crate) fn spawn_profile_lifecycle(self: &Arc, runtime: &tokio::runtime::Handle) { + let lifecycle = self.clone(); + let mut changes = self.api.profiles().subscribe(); + runtime.spawn(async move { + let mut epoch = lifecycle.api.profiles().epoch(); + if lifecycle.api.profiles().current().is_some() + && let Err(error) = lifecycle.start_enabled_plugins().await + { + tracing::warn!(%error, "could not restore enabled third-party plugins"); + } + while changes.changed().await.is_ok() { + let current_epoch = lifecycle.api.profiles().epoch(); + if current_epoch == epoch { + continue; + } + epoch = current_epoch; + lifecycle.api.fence_third_party_sessions().await; + for provider_id in lifecycle.api.third_party_provider_ids() { + if !lifecycle.api.is_extension(&provider_id) { + lifecycle.processes.terminate_provider(&provider_id).await; + } + } + if lifecycle.api.profiles().current().is_some() + && let Err(error) = lifecycle.start_enabled_plugins().await + { + tracing::warn!(%error, "could not restore enabled third-party plugins"); + } + } + }); + } +} + +impl DurableRetentionSink for ThirdPartyPluginLifecycle { + fn apply<'a>( + &'a self, + plugin_id: &'a str, + retention: DataRetention, + ) -> std::pin::Pin< + Box> + Send + 'a>, + > { + Box::pin(async move { + self.apply_durable_retention(plugin_id, retention) + .await + .map_err(|error| error.message().to_owned()) + }) + } } -struct Entry { - services: Arc, - initialized: tokio::sync::Mutex>, - packaged: bool, - initialize: bool, +fn unix_now() -> Result { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|elapsed| elapsed.as_secs().max(1) as i64) + .map_err(|_| Status::failed_precondition("the system clock is before the Unix epoch")) } -pub struct HostedProviders { - api: ProviderApi, - processes: ProviderProcesses, - endpoint_available: bool, - entries: BTreeMap, - failures: Mutex>, - observer: Mutex>, +fn package_status(error: PackageLifecycleError) -> Status { + Status::internal(format!("plugin package lifecycle failed: {error}")) +} + +fn sharing_identity_conflict() -> Status { + Status::aborted( + "plugin identity changed while saving shared-data permissions; reload and review", + ) +} + +fn validate_sharing_profile( + profiles: &PluginProfiles, + observation: &SharingIdentityObservation, +) -> Result<(), Status> { + if profiles.current().is_some_and(|current| { + current.epoch() == observation.profile_epoch + && current.profile_id() == observation.identity.profile_id + }) { + Ok(()) + } else { + Err(sharing_identity_conflict()) + } +} + +// Call while holding the publisher identity lock so registration stays stable between lookups. +fn registered_publisher(api: &ProviderApi, plugin_id: &str) -> Result { + let provider_ids = api.third_party_provider_ids_for_plugin(plugin_id); + let [provider_id] = provider_ids.as_slice() else { + return Err(Status::failed_precondition( + "plugin has no unique registered third-party provider", + )); + }; + api.third_party_identity(provider_id) + .filter(|(registered_id, _)| registered_id == plugin_id) + .map(|(_, fingerprint)| fingerprint) + .ok_or_else(|| Status::failed_precondition("plugin identity is unavailable")) +} + +fn trusted_managed_package( + registry: &PluginPackageRegistry, + trust_dir: &Path, + plugin_id: &str, + registered_fingerprint: &str, +) -> Result<(InstalledPluginVersion, [u8; 32]), Status> { + let installed = registry + .active(plugin_id) + .map_err(|_| Status::internal("plugin package state is unavailable"))? + .ok_or_else(|| Status::failed_precondition("plugin package is not installed"))?; + let key = super::updates::package_key(&installed.package_path) + .map_err(|_| Status::failed_precondition("plugin package manifest is invalid"))?; + let trust = super::publisher_trust::PublisherTrustStore::open(trust_dir) + .map_err(|_| Status::internal("plugin publisher trust is unavailable"))?; + let status = trust + .inspect(plugin_id, &key) + .map_err(|_| Status::internal("plugin publisher trust is invalid"))?; + let super::publisher_trust::KeyStatus::Trusted { fingerprint } = status else { + return Err(Status::permission_denied("plugin publisher is not trusted")); + }; + if fingerprint != registered_fingerprint { + return Err(Status::failed_precondition( + "plugin publisher does not match its registration", + )); + } + Ok((installed, key)) } fn lock(m: &Mutex) -> std::sync::MutexGuard<'_, T> { m.lock().unwrap_or_else(std::sync::PoisonError::into_inner) } +/// The digest of the signed `integrity.json` that authenticated this installed package tree. +/// +/// The registry stores the verified tree rather than the original archive. The signed integrity +/// manifest is the stable package identity: it lists every payload digest and is itself covered by +/// the package signature, so shared-record provenance can name a 32-byte package digest without +/// trusting a caller-supplied value. +fn installed_package_digest(root: &Path) -> std::io::Result> { + use sha2::Digest as _; + let bytes = std::fs::read(root.join("integrity.json"))?; + Ok(sha2::Sha256::digest(&bytes).to_vec()) +} + impl HostedProviders { pub async fn bundled( api: ProviderApi, + intents: Arc, endpoint: Option, paths: gamenode_platform::paths::DataPaths, library: Arc, @@ -105,6 +2483,23 @@ impl HostedProviders { .ok_or_else(|| Status::unavailable("provider directory unavailable"))?; let mut entries = BTreeMap::new(); let mut configs = vec![]; + let mut managed_plugins = vec![]; + let state = PluginStateLayout::managed(&paths); + let registry_paths = paths.clone(); + let registry = tokio::task::spawn_blocking(move || { + gamenode_platform::plugin_registry::PluginPackageRegistry::open(®istry_paths) + }) + .await + .map_err(|_| Status::internal("plugin package registry worker failed"))? + .map_err(|_| Status::internal("plugin package registry is unavailable"))?; + let packages = ManagedPackageLifecycle::new(registry.clone()); + let trust_path = state.trust_dir(); + let trust = tokio::task::spawn_blocking(move || { + super::publisher_trust::PublisherTrustStore::open(trust_path) + }) + .await + .map_err(|_| Status::internal("publisher trust worker failed"))? + .map_err(|_| Status::internal("publisher trust store is unavailable"))?; for descriptor in super::descriptors().iter().filter(|p| p.has(cap::CONTEXT)) { if gamenode_core::provider::Platform::current() .is_none_or(|platform| !descriptor.supports(platform)) @@ -123,8 +2518,13 @@ impl HostedProviders { api.register(Registration { provider_id: descriptor.provider_id.clone(), plugin_id: descriptor.plugin_id.clone(), + kind: super::provider::RegistrationKind::Provider, + origin: crate::plugin_host::provider::RegistrationOrigin::Official, + declared_developer: descriptor.name.clone(), + package_digest: Vec::new(), capabilities: descriptor.capabilities.clone(), shared_catalog: descriptor.shared_catalog, + playtime: Default::default(), services: services.clone(), })?; let executable = executable_dir.join(descriptor.executable_name()); @@ -138,31 +2538,144 @@ impl HostedProviders { arguments: vec![], environment: vec![], startup_timeout: Duration::from_secs(10), + manifest_capabilities: vec![], + required_capabilities: vec![], + blocked_capabilities: vec![], + integrity: None, }); entries.insert( descriptor.provider_id.clone(), - Entry { + Arc::new(Entry { services, initialized: tokio::sync::Mutex::new(None), packaged, initialize: descriptor.has(cap::CONTEXT), - }, + }), ); } + + let dynamic = Arc::new(DynamicHostState::default()); + let composition = HostComposition { + paths: paths.clone(), + library: library.clone(), + login: login.clone(), + dynamic: dynamic.clone(), + }; + let active_packages = { + let registry = registry.clone(); + tokio::task::spawn_blocking(move || registry.active_versions()) + .await + .map_err(|_| Status::internal("plugin package registry worker failed"))? + .map_err(|_| Status::internal("plugin package registry is unavailable"))? + }; + for installed in active_packages { + let plugin_id = installed.plugin_id.clone(); + let prepared = match prepare_managed_package( + installed, + &trust, + &packages, + Some(&composition), + ) + .await + { + Ok(prepared) => prepared, + Err(error) => { + tracing::warn!(%plugin_id, %error, "managed plugin is not eligible for runtime registration"); + continue; + } + }; + let PreparedManagedPackage { + provider_id, + plugin_id, + publisher_fingerprint, + inventory, + config, + registration, + extension_schemas, + entry, + } = prepared; + if let Err(error) = register_prepared_management( + &api, + &provider_id, + &plugin_id, + &publisher_fingerprint, + registration, + &extension_schemas, + ) + .await + { + tracing::warn!(%plugin_id, %error, "managed plugin registration was rejected"); + continue; + } + managed_plugins.push(inventory); + configs.push(config); + if let Some(entry) = entry { + entries.insert(provider_id, entry); + } + } let endpoint_available = endpoint.is_some(); - let processes = ProviderProcesses::new(api.clone(), endpoint.unwrap_or_default(), configs)?; + let processes = ProviderProcesses::new_for_lifecycle( + api.clone(), + endpoint.unwrap_or_default(), + configs, + state.clone(), + )?; + let lifecycle = Arc::new(ThirdPartyPluginLifecycle::new( + api.clone(), + processes.clone(), + state, + registry, + packages, + )); + lifecycle.set_host_composition(composition); + lifecycle.spawn_profile_lifecycle(&tokio::runtime::Handle::try_current().map_err( + |_| Status::failed_precondition("plugin lifecycle requires an async runtime"), + )?); Ok(Arc::new(Self { api, processes, + intents, endpoint_available, entries, + managed_plugins, + dynamic, failures: Mutex::new(BTreeMap::new()), observer: Mutex::new(None), + lifecycle, })) } + pub fn lifecycle(&self) -> Arc { + self.lifecycle.clone() + } + + /// The composed process slots. Tests use this to point a real provider at a temporary + /// collection without changing production configuration. + #[cfg(test)] + pub(crate) fn processes(&self) -> &ProviderProcesses { + &self.processes + } + + /// The composed entry for a provider, including packages registered after startup. + fn entry(&self, id: &str) -> Option> { + self.entries + .get(id) + .cloned() + .or_else(|| self.dynamic.entry(id)) + } + + fn entries_snapshot(&self) -> Vec<(String, Arc)> { + let mut entries = self + .entries + .iter() + .map(|(id, entry)| (id.clone(), entry.clone())) + .collect::>(); + entries.extend(self.dynamic.entries()); + entries + } + pub fn availability(&self, id: &str) -> &'static str { - let Some(entry) = self.entries.get(id) else { + let Some(entry) = self.entry(id) else { return "unavailable"; }; if !entry.packaged { @@ -187,7 +2700,7 @@ impl HostedProviders { } pub fn services(&self, provider: &str) -> Option> { - self.entries.get(provider).map(|e| e.services.clone()) + self.entry(provider).map(|e| e.services.clone()) } async fn initialized(&self, id: &str) -> Result<(), Status> { @@ -195,8 +2708,7 @@ impl HostedProviders { return Err(Status::unavailable("provider endpoint unavailable")); } let entry = self - .entries - .get(id) + .entry(id) .ok_or_else(|| Status::unavailable("provider is not registered"))?; self.processes.ensure_started(id).await?; let mut initialized = entry.initialized.lock().await; @@ -261,19 +2773,50 @@ impl HostedProviders { #[async_trait::async_trait] impl ProviderRuntime for HostedProviders { - fn accounts(&self) -> Vec { - self.entries + fn managed_plugin_inventory(&self) -> Vec { + self.managed_plugins .iter() + .cloned() + .chain(self.dynamic.inventory()) + .map(|mut plugin| { + let slot = if plugin.plugin_kind == "extension" { + plugin.status = if self + .lifecycle + .extension_runtime_available(&plugin.plugin_id) + { + "installed" + } else { + "unavailable" + } + .into(); + super::provider::extension_registration_id(&plugin.plugin_id) + } else { + plugin.status = self.availability(&plugin.provider_id).to_owned(); + plugin.provider_id.clone() + }; + plugin.session = if self.api.connected(&slot) { + "active" + } else { + "stopped" + } + .into(); + plugin + }) + .collect() + } + + fn accounts(&self) -> Vec { + self.entries_snapshot() + .into_iter() .filter(|(_, e)| e.services.initial_status().is_some()) - .map(|(id, _)| id.clone()) + .map(|(id, _)| id) .collect() } fn has_provider(&self, id: &str) -> bool { - self.entries.contains_key(id) + self.entry(id).is_some() } fn status(&self, id: &str) -> Option { - self.entries - .get(id) + self.entry(id) .and_then(|e| e.services.status().or_else(|| e.services.initial_status())) } fn available(&self, id: &str) -> bool { @@ -286,15 +2829,20 @@ impl ProviderRuntime for HostedProviders { self.api.connected(id) } fn set_observer(&self, observer: Observer) { - for entry in self.entries.values() { + for (_, entry) in self.entries_snapshot() { entry.services.set_observer(observer.clone()); } + self.dynamic.set_observer(observer.clone()); *lock(&self.observer) = Some(observer); } fn set_account_persistence(&self, accounts: Arc) { - for entry in self.entries.values() { + for (_, entry) in self.entries_snapshot() { entry.services.set_account_persistence(accounts.clone()); } + self.dynamic.set_account_persistence(accounts); + } + fn set_runtime_session_handler(&self, handler: Arc) { + self.api.set_runtime_session_handler(handler); } async fn execute(&self, id: &str, operation: ProviderOperation) -> Result { let result = async { @@ -305,6 +2853,168 @@ impl ProviderRuntime for HostedProviders { self.record_result(id, &result); result } + + async fn start_extension( + &self, + plugin_id: &str, + target: ExtensionTarget, + operation: super::intents::Operation, + ) -> Result<(), Status> { + let permission = match operation { + super::intents::Operation::Launch => cap::GAME_LAUNCH, + super::intents::Operation::Install => cap::GAMES_INSTALL, + _ => return Err(Status::invalid_argument("unsupported extension action")), + }; + let _mutation = self.lifecycle.mutation.lock().await; + if !self.endpoint_available { + return Err(Status::unavailable("extension runtime is unavailable")); + } + let provider_id = super::provider::extension_registration_id(plugin_id); + if !self.api.is_extension(&provider_id) { + return Err(Status::not_found("extension is not installed and trusted")); + } + let profile = self.api.profiles().require()?; + if !profile.verified() + || profile.epoch() != target.profile_epoch + || profile.profile_id() != target.context.profile_id + || !target.is_current() + { + return Err(Status::failed_precondition( + "selected extension target is unavailable", + )); + } + let (registered_plugin, publisher_fingerprint) = self + .api + .third_party_identity(&provider_id) + .ok_or_else(|| Status::not_found("extension is not available"))?; + if registered_plugin != plugin_id { + return Err(Status::permission_denied("extension identity mismatch")); + } + let binding = super::intents::Binding { + plugin_id: registered_plugin, + publisher_fingerprint, + profile_epoch: profile.epoch(), + game_id: target.context.game_id.clone(), + installation_id: target.context.installation_id.clone(), + operation, + target_revision: target + .context + .revision + .parse() + .map_err(|_| Status::invalid_argument("invalid target revision"))?, + recipe_id: String::new(), + recipe_revision: 0, + plan_fingerprint: String::new(), + }; + let intent = ExtensionIntent { + id: self.intents.issue(binding)?, + store: self.intents.clone(), + }; + self.processes + .ensure_extension_started( + &provider_id, + ExtensionLaunch { + target, + required_permission: permission, + }, + intent, + ) + .await + } + + async fn available_extensions( + &self, + operation: super::intents::Operation, + ) -> Result, Status> { + let permission = match operation { + super::intents::Operation::Launch => cap::GAME_LAUNCH, + super::intents::Operation::Install => cap::GAMES_INSTALL, + _ => return Err(Status::invalid_argument("unsupported extension action")), + }; + if !self.endpoint_available { + return Ok(Vec::new()); + } + let profile = self.api.profiles().require()?; + if !profile.verified() { + return Ok(Vec::new()); + } + let mut eligible = Vec::new(); + let managed_extensions = self + .managed_plugins + .iter() + .cloned() + .chain(self.dynamic.inventory()) + .collect::>(); + for plugin in managed_extensions + .iter() + .filter(|plugin| plugin.plugin_kind == "extension") + { + let slot = super::provider::extension_registration_id(&plugin.plugin_id); + if !self + .lifecycle + .extension_runtime_available(&plugin.plugin_id) + { + continue; + } + let config = self.processes.config(&slot)?; + if config + .blocked_capabilities + .iter() + .any(|blocked| blocked == permission) + || !config + .manifest_capabilities + .iter() + .any(|capability| capability == permission) + { + continue; + } + let Some((plugin_id, publisher_fingerprint)) = self.api.third_party_identity(&slot) + else { + continue; + }; + let identity = super::grants::PluginIdentity { + plugin_id: plugin_id.clone(), + publisher_fingerprint, + profile_id: profile.profile_id().to_owned(), + }; + let state = self.lifecycle.state.clone(); + let account = profile.clone(); + let plugin_id_for_check = plugin_id.clone(); + let permission = permission.to_owned(); + let mut required = config.required_capabilities; + required.push(permission); + let can_start = tokio::task::spawn_blocking(move || -> Result { + let activation = state.open_activation(&account).map_err(|error| { + Status::internal(format!("plugin activation state: {error}")) + })?; + if !activation.is_enabled(&plugin_id_for_check) { + return Ok(false); + } + let grants = state + .open_grants(&account) + .map_err(|error| Status::internal(format!("plugin grants: {error}")))?; + let granted = grants.effective_grants(&identity); + Ok(required.iter().all(|permission| { + !config.blocked_capabilities.contains(permission) + && granted.iter().any(|grant| { + grant.permission_id == *permission + && grant.state == super::grants::PermissionState::Granted + }) + })) + }) + .await + .map_err(|_| Status::internal("plugin eligibility worker failed"))??; + if can_start { + let mut plugin = plugin.clone(); + plugin.runtime_available = Some(true); + eligible.push(plugin); + } + } + if !self.api.profiles().is_current(profile.epoch()) { + return Ok(Vec::new()); + } + Ok(eligible) + } async fn execute_achievements( &self, id: &str, @@ -319,7 +3029,7 @@ impl ProviderRuntime for HostedProviders { result } async fn stop(&self, id: &str) -> Result<(), Status> { - if !self.entries.contains_key(id) { + if self.entry(id).is_none() { return Err(Status::not_found("provider is not registered")); } // A pending sign-in owns a native window; ask the plugin to close it before the process @@ -336,7 +3046,7 @@ impl ProviderRuntime for HostedProviders { Ok(()) } async fn start(&self, id: &str) -> Result<(), Status> { - if !self.entries.contains_key(id) { + if self.entry(id).is_none() { return Err(Status::not_found("provider is not registered")); } self.processes.start_provider(id).await?; @@ -349,10 +3059,893 @@ impl ProviderRuntime for HostedProviders { } async fn shutdown(&self) { self.processes.shutdown().await; - for id in self.entries.keys() { - let _ = tokio::time::timeout(Duration::from_secs(3), self.api.disconnect(id)).await; + for (id, _) in self.entries_snapshot() { + let _ = tokio::time::timeout(Duration::from_secs(3), self.api.disconnect(&id)).await; + } + } +} + +#[cfg(test)] +mod managed_runtime_tests { + use super::*; + + #[derive(Default)] + struct PermissionSnapshotServices; + + #[tonic::async_trait] + impl super::super::provider::HostServices for PermissionSnapshotServices { + async fn context( + &self, + _lease: super::super::provider::Lease, + ) -> Result { + Err(Status::unimplemented("fixture")) + } + + async fn account( + &self, + _lease: super::super::provider::Lease, + _action: gamenode_plugin_protocol::proto::account_request::Action, + ) -> Result { + Err(Status::unimplemented("fixture")) + } + + async fn secret( + &self, + _lease: super::super::provider::Lease, + _request: gamenode_plugin_protocol::proto::SecretRequest, + ) -> Result { + Err(Status::unimplemented("fixture")) + } + + async fn login( + &self, + _lease: super::super::provider::Lease, + _request: gamenode_plugin_protocol::proto::LoginRequest, + ) -> Result { + Err(Status::unimplemented("fixture")) + } + + async fn actions( + &self, + _lease: super::super::provider::Lease, + _actions: gamenode_plugin_protocol::proto::ActionDeclaration, + ) -> Result { + Err(Status::unimplemented("fixture")) + } + } + + fn permission_lifecycle( + root: &std::path::Path, + api: ProviderApi, + state: PluginStateLayout, + ) -> ThirdPartyPluginLifecycle { + let registry = + gamenode_platform::plugin_registry::PluginPackageRegistry::at(root.join("registry")) + .unwrap(); + let processes = ProviderProcesses::new_for_lifecycle( + api.clone(), + root.join("provider.sock"), + vec![], + state.clone(), + ) + .unwrap(); + ThirdPartyPluginLifecycle::new( + api, + processes, + state, + registry.clone(), + ManagedPackageLifecycle::new(registry), + ) + } + + #[cfg(all(target_os = "linux", target_arch = "x86_64"))] + mod sharing_policy_races { + use super::*; + use crate::plugin_host::{ + managed_packages::tests::write_signed_package, + profile::profile_id_for_account, + provider::{RegistrationKind, RegistrationOrigin}, + publisher_trust::{PublisherTrustStore, key_fingerprint}, + updates::{PluginUpdateService, tests::add_tree}, + }; + use gamenode_platform::{paths::DataPaths, plugin_environment::EmulationPolicy}; + use gamenode_plugin_protocol::proto::CommonDataCategory; + use ring::signature::{Ed25519KeyPair, KeyPair}; + + const PLUGIN_ID: &str = "org.example.lifecycle"; + const WAIT: Duration = Duration::from_secs(10); + + struct Fixture { + root: tempfile::TempDir, + lifecycle: Arc, + policies: Arc, + original: RecipientSharingSnapshot, + } + + impl Fixture { + async fn new() -> (Self, SharingIdentityObservation) { + let root = tempfile::tempdir().unwrap(); + let api = ProviderApi::default(); + api.profiles().update(Some("account-a"), true); + let paths = DataPaths::at(root.path().join("app")); + let state = PluginStateLayout::new(paths.plugin_data_dir().join("state")); + let lifecycle = Arc::new(permission_lifecycle(root.path(), api.clone(), state)); + let key = install_package(&lifecycle, root.path(), "1.0.0", 42, true).await; + let fingerprint = key_fingerprint(&key); + let trust_dir = lifecycle.state.trust_dir(); + std::fs::create_dir_all(&trust_dir).unwrap(); + PublisherTrustStore::open(trust_dir) + .unwrap() + .confirm_first_key(PLUGIN_ID, &key, &fingerprint) + .unwrap(); + api.register(Registration { + provider_id: "lifecycle-fixture".into(), + plugin_id: PLUGIN_ID.into(), + kind: RegistrationKind::Provider, + origin: RegistrationOrigin::ThirdParty { + publisher_fingerprint: fingerprint, + }, + declared_developer: "Fixture developer".into(), + package_digest: vec![], + capabilities: vec![cap::CONTEXT.into()], + shared_catalog: false, + playtime: Default::default(), + services: Arc::new(PermissionSnapshotServices), + }) + .unwrap(); + let policies = + Arc::new(SharedSharingPolicies::open(root.path().join("policies")).unwrap()); + let observation = lifecycle + .observe_sharing_identity( + PLUGIN_ID.into(), + &profile_id_for_account("account-a"), + ) + .await + .unwrap(); + policies + .replace_recipient_policies( + &observation.identity, + 0, + grant(CommonDataCategory::GamePaths), + vec![], + ) + .unwrap(); + let original = policies.recipient_snapshot(&observation.identity).unwrap(); + let fixture = Self { + root, + lifecycle, + policies, + original, + }; + (fixture, observation) + } + + async fn save( + &self, + observation: SharingIdentityObservation, + ) -> Result { + self.lifecycle + .replace_sharing_policy( + observation, + self.policies.clone(), + self.original.revision, + grant(CommonDataCategory::RuntimeCatalog), + vec![], + vec![], + ) + .await + } + + fn on_disk(&self, identity: &PluginIdentity) -> RecipientSharingSnapshot { + SharedSharingPolicies::open(self.root.path().join("policies")) + .unwrap() + .recipient_snapshot(identity) + .unwrap() + } + + async fn assert_conflict(&self, observation: SharingIdentityObservation) { + let old_identity = observation.identity.clone(); + let error = self.save(observation).await.unwrap_err(); + assert_eq!(error.code(), tonic::Code::Aborted); + assert_eq!(self.on_disk(&old_identity), self.original); + } + } + + fn grant(category: CommonDataCategory) -> ActivationReadGrant { + ActivationReadGrant::new([category], []).unwrap() + } + + async fn install_package( + lifecycle: &ThirdPartyPluginLifecycle, + root: &Path, + version: &str, + seed: u8, + activate: bool, + ) -> [u8; 32] { + let key = Ed25519KeyPair::from_seed_unchecked(&[seed; 32]).unwrap(); + let public_key: [u8; 32] = key.public_key().as_ref().try_into().unwrap(); + let package = root.join(version); + write_signed_package(&package, version, "linux", &key); + lifecycle + .packages + .install_candidate( + &package, + public_key, + EmulationPolicy::RequireNative, + activate, + ) + .await + .unwrap(); + public_key + } + + #[tokio::test] + async fn profile_switch_after_review_rejects_the_durable_save() { + let (fixture, observation) = Fixture::new().await; + fixture + .lifecycle + .api + .profiles() + .update(Some("account-b"), true); + fixture.assert_conflict(observation).await; + } + + #[tokio::test] + async fn profile_switch_back_after_review_still_rejects_the_durable_save() { + let (fixture, observation) = Fixture::new().await; + let profiles = fixture.lifecycle.api.profiles(); + profiles.update(Some("account-b"), true); + profiles.update(Some("account-a"), true); + assert_eq!( + profiles.current().unwrap().profile_id(), + observation.identity.profile_id + ); + fixture.assert_conflict(observation).await; + } + + #[tokio::test] + async fn active_package_with_new_publisher_rejects_the_durable_save() { + let (fixture, observation) = Fixture::new().await; + let key = + install_package(&fixture.lifecycle, fixture.root.path(), "2.0.0", 43, false).await; + fixture + .lifecycle + .packages + .activate_version( + PLUGIN_ID.into(), + "2.0.0".into(), + key, + EmulationPolicy::RequireNative, + ) + .await + .unwrap(); + assert_ne!( + key_fingerprint(&key), + observation.identity.publisher_fingerprint + ); + // The existing registration is still for the original key. + assert_eq!( + registered_publisher(&fixture.lifecycle.api, PLUGIN_ID).unwrap(), + observation.identity.publisher_fingerprint, + ); + fixture.assert_conflict(observation).await; + } + + #[tokio::test] + async fn import_retrust_rejects_the_durable_save_before_install() { + let (fixture, observation) = Fixture::new().await; + let paths = DataPaths::at(fixture.root.path().join("app")); + let updates = PluginUpdateService::open(&paths).unwrap(); + updates.set_lifecycle(fixture.lifecycle.clone()); + let key = Ed25519KeyPair::from_seed_unchecked(&[43; 32]).unwrap(); + let package = fixture.root.path().join("import"); + write_signed_package(&package, "2.0.0", "linux", &key); + let archive = fixture.root.path().join("import.gnplugin"); + let mut zip = zip::ZipWriter::new(std::fs::File::create(&archive).unwrap()); + add_tree(&mut zip, &package, &package); + zip.finish().unwrap(); + + let review = updates.import_review(archive).await.unwrap(); + assert_eq!(review.package.trust, "changed"); + let trusted = updates + .import_confirm_publisher(&review.token, &review.package.publisher_fingerprint) + .await + .unwrap(); + assert_eq!(trusted.package.trust, "trusted"); + assert_eq!( + fixture + .lifecycle + .registry + .active(PLUGIN_ID) + .unwrap() + .unwrap() + .version, + "1.0.0", + ); + fixture.assert_conflict(observation).await; + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn committed_save_returns_saved_revision_after_profile_switch() { + use std::sync::mpsc; + + let (fixture, observation) = Fixture::new().await; + let fixture = Arc::new(fixture); + let old_identity = observation.identity.clone(); + let profiles = fixture.lifecycle.api.profiles(); + let (checkpoint_tx, checkpoint_rx) = mpsc::channel(); + let (release_tx, release_rx) = mpsc::channel(); + let release_rx = Mutex::new(release_rx); + *lock(&fixture.lifecycle.sharing_commit_hook) = Some(Arc::new(move |checkpoint| { + checkpoint_tx.send(checkpoint).unwrap(); + lock(&release_rx).recv_timeout(WAIT).unwrap(); + })); + let saver = fixture.clone(); + let save = tokio::spawn(async move { saver.save(observation).await }); + assert!(matches!( + checkpoint_rx.recv_timeout(WAIT).unwrap(), + SharingCommitCheckpoint::BeforeWrite, + )); + assert!(profiles.transition_is_locked()); + let (started_tx, started_rx) = tokio::sync::oneshot::channel(); + let switch = tokio::task::spawn_blocking(move || { + started_tx.send(()).unwrap(); + profiles.update(Some("account-b"), true); + }); + started_rx.await.unwrap(); + release_tx.send(()).unwrap(); + + assert!(matches!( + checkpoint_rx.recv_timeout(WAIT).unwrap(), + SharingCommitCheckpoint::AfterCommit, + )); + switch.await.unwrap(); + let durable = fixture.on_disk(&old_identity); + assert_eq!(durable.revision, fixture.original.revision + 1); + assert_eq!( + durable.categories, + [CommonDataCategory::RuntimeCatalog].into() + ); + let new_identity = PluginIdentity { + profile_id: profile_id_for_account("account-b"), + ..old_identity + }; + assert_eq!( + fixture.on_disk(&new_identity), + RecipientSharingSnapshot::default() + ); + release_tx.send(()).unwrap(); + assert_eq!(save.await.unwrap().unwrap(), durable); + } + } + + #[cfg(target_os = "linux")] + mod network_origin_review { + use super::*; + use crate::plugin_host::{ + PluginApi, + grants::{EffectiveGrant, GrantScope, PermissionDecision, PermissionState}, + profile::ProfileContext, + provider::{RegistrationKind, RegistrationOrigin}, + publisher_trust::{PublisherTrustStore, key_fingerprint}, + updates::tests::signed_package_with_permissions, + }; + use gamenode_platform::plugin_environment::EmulationPolicy; + use ring::signature::{Ed25519KeyPair, KeyPair}; + + const PLUGIN_ID: &str = "org.example.update"; + const WAIT: Duration = Duration::from_secs(10); + + struct Fixture { + _temp: tempfile::TempDir, + lifecycle: Arc, + identity: PluginIdentity, + profile: ProfileContext, + activations: tokio::sync::Mutex<()>, + } + + impl Fixture { + async fn new() -> Self { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path().join("package"); + let paths = gamenode_platform::paths::DataPaths::at(temp.path().join("app")); + paths.ensure_data_dir().unwrap(); + let state = PluginStateLayout::prepare_managed(&paths).unwrap(); + let key = Ed25519KeyPair::from_seed_unchecked(&[52; 32]).unwrap(); + let public_key: [u8; 32] = key.public_key().as_ref().try_into().unwrap(); + let fingerprint = key_fingerprint(&public_key); + signed_package_with_permissions( + &root, + "1.0.0", + &key, + vec![serde_json::json!({ + "id": cap::NETWORK_FETCH, "required": false, + "scope": "https://API.example.com:443, https://cdn.example.com:8443", + "reason": "Fetch plugin data" + })], + ); + PublisherTrustStore::open(state.trust_dir()) + .unwrap() + .confirm_first_key(PLUGIN_ID, &public_key, &fingerprint) + .unwrap(); + let api = PluginApi::default(); + api.set_state_layout(state.clone()); + api.providers.profiles().update(Some("account-one"), true); + api.providers + .register(Registration { + declared_developer: "Fixture developer".into(), + package_digest: Vec::new(), + provider_id: "update-fixture".into(), + plugin_id: PLUGIN_ID.into(), + kind: RegistrationKind::Provider, + origin: RegistrationOrigin::ThirdParty { + publisher_fingerprint: fingerprint.clone(), + }, + capabilities: vec![cap::CONTEXT.into(), cap::NETWORK_FETCH.into()], + shared_catalog: false, + playtime: Default::default(), + services: Arc::new(PermissionSnapshotServices), + }) + .unwrap(); + let profile = api.providers.profiles().require().unwrap(); + let lifecycle = Arc::new(permission_lifecycle( + temp.path(), + api.providers.clone(), + state, + )); + lifecycle + .packages + .install_candidate(&root, public_key, EmulationPolicy::RequireNative, true) + .await + .unwrap(); + let identity = PluginIdentity { + plugin_id: PLUGIN_ID.into(), + publisher_fingerprint: fingerprint, + profile_id: profile.profile_id().to_owned(), + }; + Self { + _temp: temp, + lifecycle, + identity, + profile, + activations: tokio::sync::Mutex::new(()), + } + } + + fn on_disk( + &self, + profile: &ProfileContext, + identity: &PluginIdentity, + ) -> (u64, Vec) { + let store = self.lifecycle.state.open_grants(profile).unwrap(); + (store.revision(identity), store.effective_grants(identity)) + } + + async fn save( + &self, + revision: u64, + granted: bool, + ) -> Result { + self.lifecycle + .replace_permissions( + &self.activations, + PLUGIN_ID.into(), + self.identity.profile_id.clone(), + self.identity.publisher_fingerprint.clone(), + revision, + vec![decision(granted)], + ) + .await + } + } + + fn decision(granted: bool) -> PermissionDecision { + PermissionDecision { + permission_id: cap::NETWORK_FETCH.into(), + scope: GrantScope::Declared { + value: "https://api.example.com".into(), + }, + granted, + } + } + + #[tokio::test] + async fn saves_only_explicit_choices_for_the_reviewed_publisher() { + let fixture = Fixture::new().await; + let snapshot = fixture + .lifecycle + .permission_snapshot(PLUGIN_ID.into()) + .await + .unwrap(); + assert!(snapshot.effective_grants.is_empty()); + let [request] = snapshot.requested_permissions.as_slice() else { + panic!("expected network permission"); + }; + assert_eq!(request.allowed_scopes.len(), 2); + assert!(request.allowed_scopes.contains(&decision(true).scope)); + let error = fixture + .lifecycle + .replace_permissions( + &fixture.activations, + PLUGIN_ID.into(), + snapshot.profile_id.clone(), + "old publisher".into(), + snapshot.grant_revision, + vec![decision(true)], + ) + .await + .unwrap_err(); + assert_eq!(error.code(), tonic::Code::FailedPrecondition); + let saved = fixture.save(snapshot.grant_revision, true).await.unwrap(); + let granted: Vec<_> = saved + .effective_grants + .iter() + .filter(|grant| grant.state == PermissionState::Granted) + .collect(); + assert_eq!(granted.len(), 1); + assert_eq!(granted[0].scope, decision(true).scope); + let stale = fixture + .save(snapshot.grant_revision, false) + .await + .unwrap_err(); + assert_eq!(stale.code(), tonic::Code::Aborted); + assert_eq!( + fixture.on_disk(&fixture.profile, &fixture.identity), + (saved.grant_revision, saved.effective_grants) + ); + let revoked = fixture.save(saved.grant_revision, false).await.unwrap(); + assert!( + revoked + .effective_grants + .iter() + .all(|grant| grant.state == PermissionState::Denied) + ); + } + + async fn profile_transition_wins(switch_back: bool) { + let fixture = Fixture::new().await; + let original = fixture.save(0, true).await.unwrap(); + let profiles = fixture.lifecycle.api.profiles(); + let changes = profiles.subscribe_permissions(); + *lock(&fixture.lifecycle.permission_commit_hook) = Some(Arc::new(move |checkpoint| { + assert_eq!(checkpoint, PermissionCommitCheckpoint::Prepared); + profiles.update(Some("account-two"), true); + if switch_back { + profiles.update(Some("account-one"), true); + } + })); + let error = fixture + .save(original.grant_revision, false) + .await + .unwrap_err(); + assert_eq!(error.code(), tonic::Code::FailedPrecondition); + assert_eq!( + fixture.on_disk(&fixture.profile, &fixture.identity), + (original.grant_revision, original.effective_grants) + ); + assert!(!changes.has_changed().unwrap()); + } + + #[tokio::test] + async fn profile_switch_before_commit_preserves_saved_origins() { + profile_transition_wins(false).await; + } + + #[tokio::test] + async fn profile_switch_back_before_commit_preserves_saved_origins() { + profile_transition_wins(true).await; + } + + #[tokio::test] + async fn profile_round_trip_while_queued_for_activation_rejects_save() { + let fixture = Fixture::new().await; + let original = fixture.save(0, true).await.unwrap(); + let activation = fixture.activations.lock().await; + let save = fixture.save(original.grant_revision, false); + tokio::pin!(save); + tokio::select! { + biased; + _ = &mut save => panic!("save must wait for update activation"), + _ = std::future::ready(()) => {} + } + let profiles = fixture.lifecycle.api.profiles(); + profiles.update(Some("account-two"), true); + profiles.update(Some("account-one"), true); + drop(activation); + + assert_eq!( + save.await.unwrap_err().code(), + tonic::Code::FailedPrecondition + ); + assert_eq!( + fixture.on_disk(&fixture.profile, &fixture.identity), + (original.grant_revision, original.effective_grants) + ); + } + + #[tokio::test] + async fn retrust_before_commit_preserves_saved_origins() { + let fixture = Fixture::new().await; + let original = fixture.save(0, true).await.unwrap(); + let trust_dir = fixture.lifecycle.state.trust_dir(); + *lock(&fixture.lifecycle.permission_commit_hook) = Some(Arc::new(move |checkpoint| { + assert_eq!(checkpoint, PermissionCommitCheckpoint::Prepared); + let _publisher = lock_publisher_identity(); + let key = Ed25519KeyPair::from_seed_unchecked(&[53; 32]).unwrap(); + let public_key: [u8; 32] = key.public_key().as_ref().try_into().unwrap(); + PublisherTrustStore::open(&trust_dir) + .unwrap() + .retrust_key(PLUGIN_ID, &public_key, &key_fingerprint(&public_key)) + .unwrap(); + })); + let error = fixture + .save(original.grant_revision, false) + .await + .unwrap_err(); + assert_eq!(error.code(), tonic::Code::PermissionDenied); + assert_eq!( + fixture.on_disk(&fixture.profile, &fixture.identity), + (original.grant_revision, original.effective_grants) + ); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn committed_save_returns_original_identity_after_switch() { + use std::sync::mpsc; + + let fixture = Arc::new(Fixture::new().await); + let original = fixture.save(0, true).await.unwrap(); + let profiles = fixture.lifecycle.api.profiles(); + let changes = profiles.subscribe_permissions(); + let (checkpoint_tx, checkpoint_rx) = mpsc::channel(); + let (release_tx, release_rx) = mpsc::channel(); + let release_rx = Mutex::new(release_rx); + *lock(&fixture.lifecycle.permission_commit_hook) = Some(Arc::new(move |checkpoint| { + if checkpoint != PermissionCommitCheckpoint::Prepared { + checkpoint_tx.send(checkpoint).unwrap(); + lock(&release_rx).recv_timeout(WAIT).unwrap(); + } + })); + let saver = fixture.clone(); + let revision = original.grant_revision; + let save = tokio::spawn(async move { saver.save(revision, false).await }); + assert_eq!( + checkpoint_rx.recv_timeout(WAIT).unwrap(), + PermissionCommitCheckpoint::BeforeWrite + ); + assert!(profiles.transition_is_locked()); + assert!(!changes.has_changed().unwrap()); + let (started_tx, started_rx) = tokio::sync::oneshot::channel(); + let switch = tokio::task::spawn_blocking(move || { + started_tx.send(()).unwrap(); + profiles.update(Some("account-two"), true); + profiles.require().unwrap() + }); + started_rx.await.unwrap(); + release_tx.send(()).unwrap(); + assert_eq!( + checkpoint_rx.recv_timeout(WAIT).unwrap(), + PermissionCommitCheckpoint::AfterCommit + ); + let next_profile = switch.await.unwrap(); + assert!(changes.has_changed().unwrap()); + + let durable = fixture.on_disk(&fixture.profile, &fixture.identity); + assert_eq!(durable.0, revision + 1); + assert_eq!(durable.1.len(), 2); + assert!( + durable + .1 + .iter() + .all(|grant| grant.state == PermissionState::Denied) + ); + let next_identity = PluginIdentity { + profile_id: next_profile.profile_id().to_owned(), + ..fixture.identity.clone() + }; + assert_eq!(fixture.on_disk(&next_profile, &next_identity), (0, vec![])); + + release_tx.send(()).unwrap(); + let saved = save.await.unwrap().unwrap(); + assert_eq!(saved.plugin_id, fixture.identity.plugin_id); + assert_eq!( + saved.publisher_fingerprint, + fixture.identity.publisher_fingerprint + ); + assert_eq!(saved.profile_id, fixture.identity.profile_id); + assert_eq!((saved.grant_revision, saved.effective_grants), durable); } } + + #[tokio::test] + async fn permission_snapshot_requires_the_installed_signed_package_for_scope_choices() { + use super::super::provider::{RegistrationKind, RegistrationOrigin}; + + let temp = tempfile::tempdir().unwrap(); + let api = ProviderApi::default(); + api.profiles().update(Some("account-one"), true); + let plugin_id = "org.example.community"; + let fingerprint = "cd".repeat(32); + api.register(Registration { + declared_developer: "Fixture developer".into(), + package_digest: Vec::new(), + provider_id: "community".into(), + plugin_id: plugin_id.into(), + kind: RegistrationKind::Provider, + origin: RegistrationOrigin::ThirdParty { + publisher_fingerprint: fingerprint.clone(), + }, + capabilities: vec![cap::CONTEXT.into()], + shared_catalog: false, + playtime: Default::default(), + services: Arc::new(PermissionSnapshotServices), + }) + .unwrap(); + let state = PluginStateLayout::new(temp.path().join("state")); + let lifecycle = permission_lifecycle(temp.path(), api, state); + + let error = lifecycle + .permission_snapshot(plugin_id.into()) + .await + .unwrap_err(); + assert_eq!(error.code(), tonic::Code::FailedPrecondition); + assert_eq!(error.message(), "plugin package is not installed"); + } + + #[tokio::test] + async fn permission_snapshot_requires_active_profile_and_unique_third_party_provider() { + use super::super::provider::{RegistrationKind, RegistrationOrigin}; + + let temp = tempfile::tempdir().unwrap(); + let api = ProviderApi::default(); + let state = PluginStateLayout::new(temp.path().join("state")); + let lifecycle = permission_lifecycle(temp.path(), api.clone(), state.clone()); + assert_eq!( + lifecycle + .permission_snapshot("org.example.community".into()) + .await + .unwrap_err() + .code(), + tonic::Code::Unavailable + ); + + api.profiles().update(Some("account-one"), true); + api.register(Registration { + declared_developer: "Fixture developer".into(), + package_digest: Vec::new(), + provider_id: "official".into(), + plugin_id: "org.example.official".into(), + kind: RegistrationKind::Provider, + origin: RegistrationOrigin::Official, + capabilities: vec![cap::CONTEXT.into()], + shared_catalog: false, + playtime: Default::default(), + services: Arc::new(PermissionSnapshotServices), + }) + .unwrap(); + assert_eq!( + lifecycle + .permission_snapshot("org.example.official".into()) + .await + .unwrap_err() + .code(), + tonic::Code::FailedPrecondition + ); + } + + #[tokio::test] + async fn removal_requires_an_active_profile_but_can_remove_a_not_yet_registered_package() { + let temp = tempfile::tempdir().unwrap(); + let api = ProviderApi::default(); + let state = PluginStateLayout::new(temp.path().join("state")); + let package = temp.path().join("package"); + std::fs::create_dir_all(&package).unwrap(); + std::fs::write(package.join("payload"), b"not executed").unwrap(); + let registry = gamenode_platform::plugin_registry::PluginPackageRegistry::at( + temp.path().join("registry"), + ) + .unwrap(); + registry + .install_verified("org.example.imported", "1.0.0", &package, true) + .unwrap(); + let lifecycle = permission_lifecycle(temp.path(), api.clone(), state); + + assert_eq!( + lifecycle + .remove("org.example.imported".into()) + .await + .unwrap_err() + .code(), + tonic::Code::Unavailable + ); + assert!(registry.active("org.example.imported").unwrap().is_some()); + + api.profiles().update(Some("account-one"), true); + lifecycle + .remove("org.example.imported".into()) + .await + .unwrap(); + assert!(registry.active("org.example.imported").unwrap().is_none()); + } + + #[test] + fn managed_process_config_uses_the_selected_signed_provider_target() { + let target = super::super::package::Target { + os: "linux".into(), + arch: "x86_64".into(), + abi: "gnu".into(), + entrypoint: "bin/provider".into(), + requires: None, + tested_on: vec![], + }; + let manifest = super::super::package::Manifest { + schema: 1, + id: "org.example.community".into(), + kind: super::super::package::PluginKind::Provider, + provider_id: Some("community".into()), + name: "Community provider".into(), + version: "1.2.3".into(), + api: super::super::package::ApiRange { + min: "1.6.0".into(), + max: "1.6.0".into(), + }, + permissions: vec![super::super::package::PermissionRequest { + id: cap::CONTEXT.into(), + required: true, + scope: "provider session".into(), + reason: "Open a provider session".into(), + impact_if_disabled: None, + }], + native_access: vec![], + supported_platforms: vec![], + targets: vec![target.clone()], + publisher: super::super::package::Publisher { + key_id: "publisher-key".into(), + public_key: "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=".into(), + }, + license: super::super::package::LicenseNotice { + expression: "MIT".into(), + files: vec!["LICENSE".into()], + notices: vec![], + }, + source_url: None, + update_url: None, + configuration: Default::default(), + resources: BTreeMap::new(), + schemas: vec![], + playtime: Default::default(), + }; + let package_path = PathBuf::from("managed-package"); + let installed = gamenode_platform::plugin_registry::InstalledPluginVersion { + plugin_id: manifest.id.clone(), + version: manifest.version.clone(), + package_path: package_path.clone(), + }; + let report = super::super::managed_packages::PackageCandidateReport { + manifest, + environment: gamenode_platform::plugin_environment::PluginEnvironment::default(), + targets: vec![super::super::compatibility::TargetCompatibilityAssessment { + target, + verdict: super::super::compatibility::CompatibilityVerdict { + state: super::super::compatibility::CompatibilityState::Compatible, + reasons: vec![], + unknown_facts: vec![], + }, + }], + extension_schemas: vec![], + }; + + let config = managed_process_config(&installed, &report, [7; 32]).unwrap(); + assert_eq!(config.provider_id, "community"); + assert_eq!(config.executable, package_path.join("bin/provider")); + assert_eq!(config.manifest_capabilities, [cap::CONTEXT]); + assert_eq!(config.required_capabilities, [cap::CONTEXT]); + assert!(config.blocked_capabilities.is_empty()); + assert_eq!( + config.integrity.unwrap().package_root, + installed.package_path + ); + } } #[cfg(all(test, target_os = "linux"))] diff --git a/crates/app/src/plugin_host/runtime/tests.rs b/crates/app/src/plugin_host/runtime/tests.rs index 9de1d65f0..cca65a9e6 100644 --- a/crates/app/src/plugin_host/runtime/tests.rs +++ b/crates/app/src/plugin_host/runtime/tests.rs @@ -2,11 +2,19 @@ //! plugin-process marker, so the host exercises the real process boundary. use super::*; -use crate::plugin_host::{PluginApiServer, provider::Registration}; -use gamenode_plugin_protocol::{capability as cap, proto::*}; -use std::path::Path; +use crate::plugin_host::{ + PluginApiServer, + provider::{Registration, RegistrationKind, RegistrationOrigin}, +}; +use gamenode_core::library::{Effect, Input, LastAccount, LibraryCache, LibraryMachine}; +use gamenode_plugin_protocol::capability as cap; +use std::collections::{BTreeMap, VecDeque}; use std::sync::Arc; use std::time::Duration; +use std::{ + io::Write, + path::{Path, PathBuf}, +}; const MANIFEST: &str = r#" id = "fixture" @@ -17,6 +25,117 @@ source = "fixture" [scan] "#; +#[test] +fn installed_package_digest_hashes_the_signed_integrity_manifest() { + use sha2::Digest as _; + let directory = tempfile::tempdir().unwrap(); + let bytes = b"signed integrity manifest"; + std::fs::write(directory.path().join("integrity.json"), bytes).unwrap(); + + let digest = installed_package_digest(directory.path()).unwrap(); + assert_eq!(digest.len(), 32); + assert_eq!(digest, sha2::Sha256::digest(bytes).to_vec()); + assert!( + installed_package_digest(&directory.path().join("missing")).is_err(), + "a package without its signed manifest has no digest" + ); +} + +#[cfg(target_os = "linux")] +fn signed_provider_archive(root: &Path) -> PathBuf { + signed_provider_archive_version(root, "1.0.0") +} + +fn signed_provider_archive_version(root: &Path, version: &str) -> PathBuf { + use base64::Engine as _; + use ring::signature::KeyPair as _; + use sha2::Digest as _; + use std::os::unix::fs::PermissionsExt; + use zip::write::SimpleFileOptions; + + std::fs::create_dir_all(root).unwrap(); + let key = ring::signature::Ed25519KeyPair::from_seed_unchecked(&[77; 32]).unwrap(); + let manifest = serde_json::to_vec(&serde_json::json!({ + "schema": 1, + "id": "fixture.plugin", + "kind": "provider", + "provider_id": "fixture", + "name": "Signed acceptance fixture", + "version": version, + "api": {"min": "1.6.0", "max": "1.6.0"}, + "permissions": [{ + "id": cap::CATALOG, + "required": false, + "scope": "own provider catalog", + "reason": "Submit the fixture catalog" + }, { + "id": cap::DISCOVERY, + "required": false, + "scope": "own-provider", + "reason": "Discover the fixture's games" + }], + "targets": [{ + "os": "linux", + "arch": "x86_64", + "abi": "gnu", + "entrypoint": "plugin" + }], + "publisher": { + "key_id": "acceptance-fixture-key", + "public_key": base64::engine::general_purpose::STANDARD.encode(key.public_key().as_ref()) + }, + "license": {"expression": "MIT", "files": ["LICENSE"]} + })) + .unwrap(); + let executable = format!( + "#!/bin/sh\nexport GAMENODE_TEST_PLUGIN_PROCESS=fixture\nexport GAMENODE_TEST_PLUGIN_MODE=provider-catalog\nexport GAMENODE_TEST_PLUGIN_VERSION={version}\nexec '{}' --exact plugin_host::process::tests::fixture_process --nocapture\n", + std::env::current_exe().unwrap().display() + ); + let license = b"fixture license"; + let payloads = [ + ("plugin.json", manifest.as_slice()), + ("plugin", executable.as_bytes()), + ("LICENSE", license.as_slice()), + ]; + let mut files = std::collections::BTreeMap::new(); + for (name, bytes) in payloads { + std::fs::write(root.join(name), bytes).unwrap(); + files.insert( + name.to_owned(), + format!("{:x}", sha2::Sha256::digest(bytes)), + ); + } + std::fs::set_permissions(root.join("plugin"), std::fs::Permissions::from_mode(0o700)).unwrap(); + let integrity = serde_json::to_vec(&serde_json::json!({"schema": 1, "files": files})).unwrap(); + let mut signed = gamenode_platform::plugin_packages::SIGNATURE_DOMAIN_PREFIX.to_vec(); + signed.extend_from_slice(&integrity); + let signature = key.sign(&signed); + // Keep the extracted source complete: `install_verified` copies it directly in tests that + // replace an active version without going through the archive importer. + std::fs::write(root.join("integrity.json"), &integrity).unwrap(); + std::fs::write(root.join("signature.ed25519"), signature.as_ref()).unwrap(); + + let archive = root.with_extension("gnplugin"); + let mut zip = zip::ZipWriter::new(std::fs::File::create(&archive).unwrap()); + for (name, bytes) in [ + ("plugin.json", manifest.as_slice()), + ("plugin", executable.as_bytes()), + ("LICENSE", license.as_slice()), + ("integrity.json", integrity.as_slice()), + ("signature.ed25519", signature.as_ref()), + ] { + let options = if name == "plugin" { + SimpleFileOptions::default().unix_permissions(0o755) + } else { + SimpleFileOptions::default() + }; + zip.start_file(name, options).unwrap(); + zip.write_all(bytes).unwrap(); + } + zip.finish().unwrap(); + archive +} + async fn hosted_fixture() -> (HostedProviders, PluginApiServer, tempfile::TempDir) { use std::os::unix::fs::PermissionsExt; @@ -49,6 +168,11 @@ async fn hosted_fixture() -> (HostedProviders, PluginApiServer, tempfile::TempDi .register(Registration { provider_id: "fixture".into(), plugin_id: "fixture.plugin".into(), + declared_developer: "Fixture".into(), + package_digest: vec![], + origin: RegistrationOrigin::Official, + kind: RegistrationKind::Provider, + playtime: Default::default(), capabilities: vec![cap::CONTEXT.into()], shared_catalog: false, services: services.clone(), @@ -78,30 +202,866 @@ async fn hosted_fixture() -> (HostedProviders, PluginApiServer, tempfile::TempDi ), ], startup_timeout: Duration::from_secs(10), + manifest_capabilities: vec![cap::CONTEXT.into()], + required_capabilities: vec![], + blocked_capabilities: vec![], + integrity: None, }], ) .unwrap(); let mut entries = std::collections::BTreeMap::new(); entries.insert( "fixture".into(), - Entry { + Arc::new(Entry { services, initialized: tokio::sync::Mutex::new(None), packaged: true, initialize: true, - }, + }), ); + let registry = gamenode_platform::plugin_registry::PluginPackageRegistry::at( + directory.path().join("registry"), + ) + .unwrap(); + let lifecycle = Arc::new(ThirdPartyPluginLifecycle::new( + api.clone(), + processes.clone(), + PluginStateLayout::new(directory.path().join("state")), + registry.clone(), + ManagedPackageLifecycle::new(registry), + )); let host = HostedProviders { + lifecycle, + intents: Arc::new(Default::default()), + managed_plugins: vec![], api, processes, endpoint_available: true, entries, + dynamic: Arc::new(DynamicHostState::default()), failures: Mutex::new(std::collections::BTreeMap::new()), observer: Mutex::new(None), }; (host, server, directory) } +#[cfg(target_os = "linux")] +#[tokio::test(flavor = "multi_thread")] +async fn imported_signed_provider_runs_from_registry_and_profile_fences_after_permission_revocation() + { + use crate::plugin_host::{ + PluginApi, grants::PermissionDecision, profile::PluginStateLayout, + updates::PluginUpdateService, + }; + use gamenode_platform::{ + db::{self, SqliteSettingsStore}, + paths::DataPaths, + plugin_registry::PluginPackageRegistry, + }; + use std::os::unix::fs::PermissionsExt; + + let directory = tempfile::tempdir().unwrap(); + std::fs::set_permissions( + directory.path(), + std::os::unix::fs::PermissionsExt::from_mode(0o700), + ) + .unwrap(); + let endpoint = directory.path().join("plugins.sock"); + let paths = DataPaths::at(directory.path().join("app-data")); + let api = PluginApi::default(); + let state = PluginStateLayout::managed(&paths); + api.set_state_layout(state.clone()); + api.providers.profiles().update(Some("account-one"), true); + + // Compose the host before the import: the accepted package must register into this same + // runtime, exactly as a running desktop does. No second HostedProviders is built. + let registry = PluginPackageRegistry::open(&paths).unwrap(); + // The update service prepares the private layout the host composition reads. + let importer = PluginUpdateService::open(&paths).unwrap(); + let store = SqliteSettingsStore::new(db::open(Path::new(":memory:")).unwrap()); + let library: Arc = Arc::new(store.library_store()); + let host = HostedProviders::bundled( + api.providers.clone(), + Arc::new(Default::default()), + Some(endpoint.clone()), + paths.clone(), + library, + None, + ) + .await + .unwrap(); + let server = + PluginApiServer::start(&tokio::runtime::Handle::current(), &endpoint, api.clone()).unwrap(); + + // Import uses the same signed archive and publisher-pin flow as the UI. + importer.set_lifecycle(host.lifecycle()); + let archive = signed_provider_archive(&directory.path().join("package")); + let review = importer.import_review(archive).await.unwrap(); + assert_eq!(review.package.trust, "untrusted"); + assert_eq!(review.package.compatibility, "compatible"); + importer + .import_confirm_publisher(&review.token, &review.package.publisher_fingerprint) + .await + .unwrap(); + assert_eq!( + importer + .import_install(&review.token, false, &[]) + .await + .unwrap() + .plugin_id, + "fixture.plugin" + ); + let imported = registry.active("fixture.plugin").unwrap().unwrap(); + let entrypoint = imported.package_path.join("plugin"); + let metadata = std::fs::symlink_metadata(&entrypoint).unwrap(); + assert!(metadata.is_file() && !metadata.file_type().is_symlink()); + assert_eq!( + metadata.permissions().mode() & 0o777, + 0o700, + "only the signed target entrypoint receives executable permissions" + ); + + let plugin = host + .managed_plugin_inventory() + .into_iter() + .find(|plugin| plugin.plugin_id == "fixture.plugin") + .expect("the active signed provider is loaded from the registry"); + assert_eq!(plugin.status, "installed"); + assert_eq!(plugin.version, "1.0.0"); + + let lifecycle = host.lifecycle(); + let snapshot = lifecycle + .permission_snapshot("fixture.plugin".into()) + .await + .unwrap(); + let decisions = |catalog_granted: bool| { + snapshot + .requested_permissions + .iter() + .flat_map(|request| { + request + .allowed_scopes + .iter() + .map(move |scope| PermissionDecision { + permission_id: request.permission_id.clone(), + scope: scope.clone(), + // The test revokes only the catalog grant; discovery stays usable so the + // signed child can keep its session while the catalog fence is exercised. + granted: catalog_granted || request.permission_id != cap::CATALOG, + }) + }) + .collect::>() + }; + let activation = tokio::sync::Mutex::new(()); + let granted = lifecycle + .replace_permissions( + &activation, + "fixture.plugin".into(), + snapshot.profile_id.clone(), + snapshot.publisher_fingerprint.clone(), + snapshot.grant_revision, + decisions(true), + ) + .await + .unwrap(); + assert_eq!( + granted.effective_grants[0].state, + crate::plugin_host::grants::PermissionState::Granted + ); + + lifecycle.enable("fixture.plugin".into()).await.unwrap(); + host.execute("fixture", ProviderOperation::Initialize) + .await + .unwrap(); + let catalog = host + .execute("fixture", ProviderOperation::SyncCatalog) + .await + .unwrap(); + let Some(Ok(owned)) = catalog.catalog.owned else { + panic!("the signed child must submit a complete catalog over Exchange"); + }; + assert_eq!(owned.len(), 1); + assert_eq!(owned[0].id, "fixture-game"); + + let revoked = lifecycle + .replace_permissions( + &activation, + "fixture.plugin".into(), + granted.profile_id, + granted.publisher_fingerprint, + granted.grant_revision, + decisions(false), + ) + .await + .unwrap(); + assert_eq!( + revoked.effective_grants[0].state, + crate::plugin_host::grants::PermissionState::Denied + ); + let persisted = lifecycle + .permission_snapshot("fixture.plugin".into()) + .await + .unwrap(); + assert_eq!( + persisted.effective_grants[0].state, + crate::plugin_host::grants::PermissionState::Denied, + "the host persists the revoked catalog grant for this identity" + ); + + api.providers.profiles().update(Some("account-two"), true); + tokio::time::timeout(Duration::from_secs(5), async { + while host.processes.process_id("fixture").await.is_some() + || api.providers.connected("fixture") + { + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .expect("profile fencing stops the imported provider process and session"); + host.shutdown().await; + server.shutdown().await; +} + +/// Starts the running library for one account, as the app does when a profile signs in. +#[cfg(target_os = "linux")] +fn start_library_machine() -> LibraryMachine { + let mut machine = LibraryMachine::new(Vec::new(), Default::default()); + let effects = machine.handle(Input::AccountChanged(Some(LastAccount { + id: "fixture-account".to_owned(), + name: "Fixture Account".to_owned(), + }))); + let op = effects + .iter() + .find_map(|effect| match effect { + Effect::LoadCache { op, .. } => Some(*op), + _ => None, + }) + .expect("the account load starts with a cache read"); + machine.handle(Input::Loaded { + op, + result: Ok(LibraryCache::default()), + }); + machine +} + +/// Drives the library's scan effects through the live provider host, mirroring the engine's +/// `RunScan` path without a second runtime or a restart. +#[cfg(target_os = "linux")] +async fn scan_library( + machine: &mut LibraryMachine, + runtime: &dyn ProviderRuntime, + effects: Vec, + now: i64, +) { + let mut queue: VecDeque = effects.into(); + while let Some(effect) = queue.pop_front() { + let Effect::RunScan { op, provider } = effect else { + continue; + }; + let result = match runtime + .execute(&provider, ProviderOperation::Discover) + .await + { + Ok(completion) => completion + .result + .discovery + .filter(|discovery| discovery.provider_id == provider) + .map(|discovery| { + gamenode_core::provider::record::finish_records( + &provider, + discovery + .records + .into_iter() + .map(|record| gamenode_core::provider::RawRecord { + id: Some(record.id), + name: Some(record.name), + install_dir: Some(record.install_dir), + fields: record.fields.into_iter().collect(), + }) + .collect(), + &[], + ) + }) + .ok_or_else(|| "provider discovery returned no observations".to_owned()), + Err(status) => Err(status.message().to_owned()), + }; + queue.extend(machine.handle(Input::ProviderScanned { + op, + provider, + result, + targets: BTreeMap::new(), + now, + })); + } +} + +/// The composed record one scan should have written for the fixture version. +#[cfg(target_os = "linux")] +fn fixture_key(version: &str) -> String { + format!("fixture:fixture-game-v{version}") +} + +#[cfg(target_os = "linux")] +fn fixture_name(version: &str) -> String { + format!("Fixture Game {version}") +} + +#[cfg(target_os = "linux")] +#[tokio::test(flavor = "multi_thread")] +async fn a_live_signed_provider_can_update_disable_remove_and_reinstall_without_a_restart() { + use crate::plugin_host::{PluginApi, profile::PluginStateLayout, updates::PluginUpdateService}; + use gamenode_platform::{ + db::{self, SqliteSettingsStore}, + paths::DataPaths, + plugin_registry::PluginPackageRegistry, + }; + + let directory = tempfile::tempdir().unwrap(); + std::fs::set_permissions( + directory.path(), + std::os::unix::fs::PermissionsExt::from_mode(0o700), + ) + .unwrap(); + let endpoint = directory.path().join("plugins.sock"); + let paths = DataPaths::at(directory.path().join("app-data")); + let api = PluginApi::default(); + let state = PluginStateLayout::managed(&paths); + api.set_state_layout(state.clone()); + api.providers.profiles().update(Some("account-one"), true); + + let registry = PluginPackageRegistry::open(&paths).unwrap(); + let importer = PluginUpdateService::open(&paths).unwrap(); + let store = SqliteSettingsStore::new(db::open(Path::new(":memory:")).unwrap()); + let library: Arc = Arc::new(store.library_store()); + let host = HostedProviders::bundled( + api.providers.clone(), + Arc::new(Default::default()), + Some(endpoint.clone()), + paths.clone(), + library, + None, + ) + .await + .unwrap(); + let server = + PluginApiServer::start(&tokio::runtime::Handle::current(), &endpoint, api.clone()).unwrap(); + importer.set_lifecycle(host.lifecycle()); + + // First import registers and enables the provider. + let archive = signed_provider_archive_version(&directory.path().join("package-1.0.0"), "1.0.0"); + let review = importer.import_review(archive).await.unwrap(); + importer + .import_confirm_publisher(&review.token, &review.package.publisher_fingerprint) + .await + .unwrap(); + let first = importer + .import_install(&review.token, false, &[]) + .await + .unwrap(); + assert!(first.activated, "{:?}", first.activation_error); + let lifecycle = host.lifecycle(); + lifecycle.enable("fixture.plugin".into()).await.unwrap(); + assert_eq!( + host.processes + .config("fixture") + .unwrap() + .integrity + .unwrap() + .version, + "1.0.0" + ); + + // The import adds the provider to the already running library, exactly as the desktop's + // post-import callback does, and a scan through the live host lists its store and game. + let imported_provider = crate::plugin_host::startup::installed_provider_from_registry( + gamenode_core::provider::Platform::Linux, + registry.clone(), + state.trust_dir(), + "fixture.plugin", + ) + .await + .unwrap() + .expect("the imported provider composes for the library"); + assert_eq!( + imported_provider.discovery_plugin(), + Some("fixture.plugin"), + "the plugin id and the provider id are deliberately different" + ); + let mut library = start_library_machine(); + library.put_provider(imported_provider); + let effects = library.handle(Input::ScanRequested); + scan_library(&mut library, host.as_ref(), effects, 100).await; + + let v1 = fixture_key("1.0.0"); + let entry = library + .entry(&v1) + .expect("the live scan added the imported provider's record"); + assert_eq!(entry.name.as_deref(), Some(fixture_name("1.0.0").as_str())); + assert!(entry.installed); + assert_eq!( + library + .scan_state("fixture") + .and_then(|state| state.last_success_at), + Some(100) + ); + assert!(library.visible_entries().any(|entry| entry.key == v1)); + let view = library.view().expect("the library view is available"); + assert!( + view.providers + .iter() + .any(|provider| provider.id == "fixture" && provider.count == 1), + "{:?}", + view.providers + ); + assert_eq!( + library + .query("") + .rows + .iter() + .map(|row| row.key.as_str()) + .collect::>(), + [v1.as_str()] + ); + + // Replacing the active package on disk while the provider stays registered must swap the + // supervised config, not keep the old version until the next desktop restart. The bundle + // import path installs the new component version and then calls this same registration. + let source = directory.path().join("package-2.0.0"); + signed_provider_archive_version(&source, "2.0.0"); + let installed = registry + .install_verified("fixture.plugin", "2.0.0", &source, true) + .unwrap(); + std::fs::set_permissions( + installed.package_path.join("plugin"), + std::os::unix::fs::PermissionsExt::from_mode(0o700), + ) + .unwrap(); + let registration = lifecycle.register_installed_packages().await.unwrap(); + for outcome in ®istration { + assert!( + outcome.error.is_none(), + "{}: {:?}", + outcome.plugin_id, + outcome.error + ); + } + assert_eq!( + host.processes + .config("fixture") + .unwrap() + .integrity + .unwrap() + .version, + "2.0.0", + "the live slot must run the version the import just accepted" + ); + lifecycle.enable("fixture.plugin".into()).await.unwrap(); + assert!(lifecycle.enabled("fixture.plugin".into()).await.unwrap()); + + // The updated package contributes the new record, and the same machine's next scan replaces + // the old rows instead of waiting for a restart. + let updated_provider = crate::plugin_host::startup::installed_provider_from_registry( + gamenode_core::provider::Platform::Linux, + registry.clone(), + state.trust_dir(), + "fixture.plugin", + ) + .await + .unwrap() + .expect("the updated provider composes for the library"); + library.put_provider(updated_provider); + let effects = library.handle(Input::ScanRequested); + scan_library(&mut library, host.as_ref(), effects, 101).await; + let v2 = fixture_key("2.0.0"); + assert!( + library.entry(&v1).is_some_and(|entry| !entry.installed), + "the fresh scan marks the provider's previous rows uninstalled" + ); + assert!( + !library.visible_entries().any(|entry| entry.key == v1), + "the old record leaves the visible game list" + ); + let entry = library + .entry(&v2) + .expect("the updated provider's record is live"); + assert_eq!(entry.name.as_deref(), Some(fixture_name("2.0.0").as_str())); + assert_eq!( + library + .scan_state("fixture") + .and_then(|state| state.last_success_at), + Some(101) + ); + assert_eq!( + library + .query("") + .rows + .iter() + .map(|row| row.key.as_str()) + .collect::>(), + [v2.as_str()] + ); + + // Deactivation stops the supervised process and keeps the installed package and grants. + lifecycle.disable("fixture.plugin".into()).await.unwrap(); + assert!(!lifecycle.enabled("fixture.plugin".into()).await.unwrap()); + assert_eq!(host.processes.process_id("fixture").await, None); + assert!( + !host.connected("fixture"), + "the store session reflects the stop" + ); + // The library keeps the cached rows and store card across the stop. + assert!(library.entry(&v2).is_some()); + assert!(library.visible_entries().any(|entry| entry.key == v2)); + assert!( + library + .view() + .expect("the library view is available") + .providers + .iter() + .any(|provider| provider.id == "fixture" && provider.count == 1), + "the stopped store keeps its cached card" + ); + + // Activation works again in the same host and a fresh scan refreshes the rows. + lifecycle.enable("fixture.plugin".into()).await.unwrap(); + assert!(lifecycle.enabled("fixture.plugin".into()).await.unwrap()); + assert!(host.processes.process_id("fixture").await.is_some()); + let effects = library.handle(Input::ScanRequested); + scan_library(&mut library, host.as_ref(), effects, 102).await; + assert_eq!( + library + .scan_state("fixture") + .and_then(|state| state.last_success_at), + Some(102) + ); + assert_eq!( + library + .entry(&v2) + .expect("the re-enabled provider's record is live") + .name + .as_deref(), + Some(fixture_name("2.0.0").as_str()) + ); + + // Uninstall unregisters the plugin and removes its slot without a restart. A scan requested + // just before the uninstall is still waiting for its answer. + let pending = library.handle(Input::ScanRequested); + let pending_scan = pending + .iter() + .find_map(|effect| match effect { + Effect::RunScan { op, provider } if provider == "fixture" => Some(*op), + _ => None, + }) + .expect("the uninstall interrupts a running scan"); + lifecycle.remove("fixture.plugin".into()).await.unwrap(); + assert!(!lifecycle.is_registered("fixture.plugin")); + assert!(!lifecycle.has_process_slot("fixture.plugin")); + assert!(!lifecycle.enabled("fixture.plugin".into()).await.unwrap()); + assert!(registry.active("fixture.plugin").unwrap().is_none()); + + // The store and its rows leave the running library immediately. + library.remove_provider_for_plugin("fixture.plugin"); + assert!(library.provider("fixture").is_none()); + assert!(library.entry(&v2).is_none(), "its live rows are dropped"); + assert!(library.scan_state("fixture").is_none()); + assert!( + !library + .visible_entries() + .any(|entry| entry.provider == "fixture") + ); + assert!( + !library + .view() + .expect("the library view is available") + .providers + .iter() + .any(|provider| provider.id == "fixture"), + "the store leaves the sidebar projection" + ); + assert_eq!(library.query("").total, 0); + assert!(library.query("").rows.is_empty()); + + // A late answer for the uninstalled provider is ignored instead of recreating its store. + let late = library.handle(Input::ProviderScanned { + op: pending_scan, + provider: "fixture".into(), + result: Ok(gamenode_core::provider::record::finish_records( + "fixture", + vec![gamenode_core::provider::RawRecord { + id: Some("fixture-game-late".into()), + name: Some("Late Fixture Game".into()), + install_dir: Some("/fixtures/Late Fixture Game".into()), + fields: Default::default(), + }], + &[], + )), + targets: BTreeMap::new(), + now: 103, + }); + assert!(late.is_empty(), "{late:?}"); + assert!(library.entry("fixture:fixture-game-late").is_none()); + assert_eq!(library.query("").total, 0); + + // Reinstall through the same reviewed import path: it installs, applies the reviewed grants, + // registers, enables and starts the plugin again in this session. + let archive = signed_provider_archive_version(&directory.path().join("package-3.0.0"), "3.0.0"); + let review = importer.import_review(archive).await.unwrap(); + if review.package.trust != "trusted" { + importer + .import_confirm_publisher(&review.token, &review.package.publisher_fingerprint) + .await + .unwrap(); + } + let reinstalled = importer + .import_install(&review.token, false, &[]) + .await + .unwrap(); + assert!(reinstalled.activated, "{:?}", reinstalled.activation_error); + assert!(lifecycle.is_registered("fixture.plugin")); + assert!(lifecycle.has_process_slot("fixture.plugin")); + assert!(lifecycle.enabled("fixture.plugin".into()).await.unwrap()); + assert_eq!( + host.processes + .config("fixture") + .unwrap() + .integrity + .unwrap() + .version, + "3.0.0" + ); + assert!(host.processes.process_id("fixture").await.is_some()); + + // The reinstalled provider returns to the same library machine and repopulates the store and + // rows with the new package's data. + let reinstalled_provider = crate::plugin_host::startup::installed_provider_from_registry( + gamenode_core::provider::Platform::Linux, + registry.clone(), + state.trust_dir(), + "fixture.plugin", + ) + .await + .unwrap() + .expect("the reinstalled provider composes for the library"); + library.put_provider(reinstalled_provider); + let effects = library.handle(Input::ScanRequested); + scan_library(&mut library, host.as_ref(), effects, 104).await; + let v3 = fixture_key("3.0.0"); + assert!(library.provider("fixture").is_some()); + assert!(library.entry(&v3).is_some()); + let view = library.view().expect("the library view is available"); + assert!( + view.providers + .iter() + .any(|provider| provider.id == "fixture" && provider.count == 1), + "{:?}", + view.providers + ); + assert_eq!( + library + .query("") + .rows + .iter() + .map(|row| row.key.as_str()) + .collect::>(), + [v3.as_str()] + ); + + host.shutdown().await; + server.shutdown().await; +} + +#[cfg(target_os = "linux")] +#[tokio::test(flavor = "multi_thread")] +async fn official_linux_providers_remain_composed_across_managed_registry_states() { + use crate::plugin_host::{ + PluginApi, grants::PermissionDecision, profile::PluginStateLayout, + updates::PluginUpdateService, + }; + use gamenode_platform::{ + db::{self, SqliteSettingsStore}, + paths::DataPaths, + plugin_registry::PluginPackageRegistry, + }; + use std::os::unix::fs::PermissionsExt; + + for state_name in ["empty", "invalid", "enabled", "disabled"] { + let directory = tempfile::tempdir().unwrap(); + std::fs::set_permissions(directory.path(), PermissionsExt::from_mode(0o700)).unwrap(); + let endpoint = directory.path().join("plugins.sock"); + let paths = DataPaths::at(directory.path().join("app-data")); + let api = PluginApi::default(); + let state = PluginStateLayout::managed(&paths); + api.set_state_layout(state.clone()); + api.providers.profiles().update(Some("account-one"), true); + let registry = PluginPackageRegistry::open(&paths).unwrap(); + + match state_name { + "invalid" => { + // A complete registry record pointing at an invalid manifest is ignored by + // runtime composition; it must not hide or replace an official provider. + let source = directory.path().join("invalid-package"); + std::fs::create_dir_all(&source).unwrap(); + std::fs::write(source.join("plugin.json"), b"{").unwrap(); + registry + .install_verified("invalid.plugin", "1.0.0", &source, true) + .unwrap(); + } + "enabled" | "disabled" => { + let preliminary_processes = ProviderProcesses::new_for_lifecycle( + api.providers.clone(), + endpoint.clone(), + vec![], + state.clone(), + ) + .unwrap(); + let preliminary = Arc::new(ThirdPartyPluginLifecycle::new( + api.providers.clone(), + preliminary_processes, + state.clone(), + registry.clone(), + crate::plugin_host::managed_packages::ManagedPackageLifecycle::new( + registry.clone(), + ), + )); + let importer = PluginUpdateService::open(&paths).unwrap(); + importer.set_lifecycle(preliminary); + let archive = signed_provider_archive(&directory.path().join("package")); + let review = importer.import_review(archive).await.unwrap(); + assert_eq!(review.package.compatibility, "compatible", "{state_name}"); + importer + .import_confirm_publisher(&review.token, &review.package.publisher_fingerprint) + .await + .unwrap(); + assert_eq!( + importer + .import_install(&review.token, false, &[]) + .await + .unwrap() + .plugin_id, + "fixture.plugin", + "{state_name}" + ); + } + "empty" => {} + _ => unreachable!(), + } + + // Normal application startup has initialized the package trust store before composing + // provider registrations; create the same host-owned state for every fixture variant. + let _updates = PluginUpdateService::open(&paths).unwrap(); + let store = SqliteSettingsStore::new(db::open(Path::new(":memory:")).unwrap()); + let library: Arc = + Arc::new(store.library_store()); + let host = HostedProviders::bundled( + api.providers.clone(), + Arc::new(Default::default()), + Some(endpoint.clone()), + paths, + library, + None, + ) + .await + .unwrap(); + let server = + PluginApiServer::start(&tokio::runtime::Handle::current(), &endpoint, api.clone()) + .unwrap(); + + // Official services remain registered and their static plugin-backed descriptors remain + // identical, whether the managed registry is empty, malformed, enabled or disabled. + for provider in ["steam", "packagekit"] { + if provider == "packagekit" { + assert_eq!( + gamenode_core::provider::Platform::current(), + Some(gamenode_core::provider::Platform::Linux) + ); + } + assert!( + host.services(provider).is_some(), + "{state_name}: {provider}" + ); + assert_eq!( + host.availability(provider), + "missing", + "{state_name}: {provider}" + ); + let unavailable = host + .execute(provider, ProviderOperation::Initialize) + .await + .expect_err("a missing official executable must not use an in-process substitute"); + assert_eq!( + unavailable.code(), + tonic::Code::Unavailable, + "{state_name}: {provider}" + ); + assert_eq!( + host.availability(provider), + "missing", + "{state_name}: {provider}" + ); + assert!(!host.connected(provider), "{state_name}: {provider}"); + assert_eq!( + host.processes.process_id(provider).await, + None, + "{state_name}: {provider}" + ); + } + + match state_name { + "enabled" => { + let lifecycle = host.lifecycle(); + let snapshot = lifecycle + .permission_snapshot("fixture.plugin".into()) + .await + .unwrap(); + let decisions = snapshot + .requested_permissions + .iter() + .flat_map(|request| { + request + .allowed_scopes + .iter() + .map(move |scope| PermissionDecision { + permission_id: request.permission_id.clone(), + scope: scope.clone(), + granted: true, + }) + }) + .collect::>(); + let activation = tokio::sync::Mutex::new(()); + lifecycle + .replace_permissions( + &activation, + "fixture.plugin".into(), + snapshot.profile_id, + snapshot.publisher_fingerprint, + snapshot.grant_revision, + decisions, + ) + .await + .unwrap(); + lifecycle.enable("fixture.plugin".into()).await.unwrap(); + assert!(host.connected("fixture")); + assert_eq!(host.availability("steam"), "missing"); + assert_eq!(host.availability("packagekit"), "missing"); + } + "disabled" => { + assert!( + !host + .lifecycle() + .enabled("fixture.plugin".into()) + .await + .unwrap() + ); + assert!(!host.connected("fixture")); + } + _ => assert!(host.managed_plugin_inventory().is_empty(), "{state_name}"), + } + + host.shutdown().await; + server.shutdown().await; + } +} + #[tokio::test(flavor = "multi_thread")] async fn a_stopped_provider_stays_installed_and_start_clears_obsolete_failures() { let (host, _server, _directory) = hosted_fixture().await; @@ -156,3 +1116,1284 @@ async fn a_stopped_provider_stays_installed_and_start_clears_obsolete_failures() host.shutdown().await; } + +/// A minimal installed and registered third-party plugin beside a host-owned durable pool. +struct UninstallFixture { + dir: tempfile::TempDir, + root: crate::plugin_host::PluginApi, + state: PluginStateLayout, + registry: gamenode_platform::plugin_registry::PluginPackageRegistry, + plugin_id: &'static str, + fingerprint: String, + owner: OwnerScope, +} + +impl UninstallFixture { + fn new(plugin_id: &'static str, provider_id: &'static str) -> Self { + use crate::plugin_host::{PluginApi, provider::ExtensionServices}; + use gamenode_platform::plugin_shared_data::OwnerScope; + + let dir = tempfile::tempdir().unwrap(); + let data_dir = dir.path().join("app-data"); + std::fs::create_dir_all(&data_dir).unwrap(); + let root = PluginApi { + shared_pool: Arc::new(crate::plugin_host::shared_pool::DurableSharedPool::new( + &data_dir, + )), + storage: Arc::new(crate::plugin_host::storage::PluginStorage::new( + dir.path().join("plugin-data"), + )), + ..Default::default() + }; + let state = PluginStateLayout::new(dir.path().join("state")); + root.set_state_layout(state.clone()); + root.providers.profiles().update(Some("account-one"), true); + let fingerprint = "ab".repeat(32); + root.providers + .register(Registration { + provider_id: provider_id.into(), + plugin_id: plugin_id.into(), + declared_developer: "Example Developer".into(), + package_digest: vec![7; 32], + kind: RegistrationKind::Provider, + origin: RegistrationOrigin::ThirdParty { + publisher_fingerprint: fingerprint.clone(), + }, + capabilities: vec![cap::CONTEXT.into()], + shared_catalog: false, + playtime: Default::default(), + services: Arc::new(ExtensionServices), + }) + .unwrap(); + let epoch = root.providers.profiles().require().unwrap().epoch(); + let resolver = root + .providers + .profiles() + .resolver(plugin_id, &fingerprint, None) + .unwrap(); + let owner = OwnerScope::new(*resolver.storage_owner().key(), epoch).unwrap(); + let registry = gamenode_platform::plugin_registry::PluginPackageRegistry::at( + dir.path().join("registry"), + ) + .unwrap(); + let source = dir.path().join("source"); + std::fs::create_dir_all(&source).unwrap(); + std::fs::write(source.join("plugin.json"), b"{}").unwrap(); + registry + .install_verified(plugin_id, "1.0.0", &source, true) + .unwrap(); + Self { + dir, + root, + state, + registry, + plugin_id, + fingerprint, + owner, + } + } + + fn lifecycle(&self) -> ThirdPartyPluginLifecycle { + let processes = ProviderProcesses::new_for_lifecycle( + self.root.providers.clone(), + self.dir.path().join("plugins.sock"), + vec![], + self.state.clone(), + ) + .unwrap(); + let lifecycle = ThirdPartyPluginLifecycle::new( + self.root.providers.clone(), + processes, + self.state.clone(), + self.registry.clone(), + ManagedPackageLifecycle::new(self.registry.clone()), + ); + lifecycle.set_private_storage(self.root.storage.clone()); + lifecycle + } + + fn reinstall(&self, version: &str) { + use crate::plugin_host::provider::ExtensionServices; + + self.root + .providers + .register(Registration { + provider_id: "producer".into(), + plugin_id: self.plugin_id.into(), + declared_developer: "Example Developer".into(), + package_digest: vec![7; 32], + kind: RegistrationKind::Provider, + origin: RegistrationOrigin::ThirdParty { + publisher_fingerprint: self.fingerprint.clone(), + }, + capabilities: vec![cap::CONTEXT.into()], + shared_catalog: false, + playtime: Default::default(), + services: Arc::new(ExtensionServices), + }) + .unwrap(); + let source = self.dir.path().join(format!("source-{version}")); + std::fs::create_dir_all(&source).unwrap(); + std::fs::write(source.join("plugin.json"), b"{}").unwrap(); + self.registry + .install_verified(self.plugin_id, version, &source, true) + .unwrap(); + } + + fn profile_id(&self) -> String { + self.root + .providers + .profiles() + .require() + .unwrap() + .profile_id() + .to_owned() + } + + fn private_root(&self) -> PathBuf { + self.dir.path().join("plugin-data") + } + + fn private_dir(&self, plugin_id: &str, profile_id: &str) -> PathBuf { + gamenode_platform::plugin_storage::namespace_dir( + &self.private_root(), + &self.fingerprint, + plugin_id, + profile_id, + ) + } + + fn write_private_at(&self, plugin_id: &str, profile_id: &str, key: &str, value: &[u8]) { + let mut store = gamenode_platform::plugin_storage::DurableStore::open( + &self.private_dir(plugin_id, profile_id), + ) + .unwrap(); + store + .put( + key, + value, + 1, + None, + 100, + gamenode_platform::plugin_storage::QUOTA_BYTES, + ) + .unwrap(); + } + + fn write_private(&self, plugin_id: &str, key: &str, value: &[u8]) { + self.write_private_at(plugin_id, &self.profile_id(), key, value); + } + + fn read_private_at(&self, plugin_id: &str, profile_id: &str, key: &str) -> Option> { + let store = gamenode_platform::plugin_storage::DurableStore::open_existing( + &self.private_dir(plugin_id, profile_id), + ) + .unwrap()?; + store.get(key, 100).unwrap().map(|stored| stored.value) + } + + fn read_private(&self, plugin_id: &str, key: &str) -> Option> { + self.read_private_at(plugin_id, &self.profile_id(), key) + } + + async fn publish(&self, resource: &str, title: &str) -> String { + use crate::plugin_host::shared_pool::DurableWrite; + use gamenode_platform::plugin_shared_data::RecordProvenance; + + let record = self + .root + .shared_pool + .persist(DurableWrite { + owner: self.owner, + dataset_id: "org.example.catalog".to_owned(), + schema_id: "org.example.catalog.v1".to_owned(), + schema_version: 1, + fields_json: format!(r#"{{"title":"{title}"}}"#), + opaque_payload: Vec::new(), + resource_id: Some(resource.to_owned()), + observed_at: 1_700_000_000, + sequence: 1, + source_observation_id: format!("observation-{resource}"), + expires_at: None, + now: 1_700_000_000, + provenance: RecordProvenance { + source_plugin_id: self.plugin_id.to_owned(), + source_publisher_fingerprint: self.fingerprint.clone(), + source_profile_id: "account-one".to_owned(), + declared_developer: "Example Developer".to_owned(), + origin: "registry".to_owned(), + package_version: "1.0.0".to_owned(), + package_digest: vec![7; 32], + }, + }) + .await + .unwrap(); + record.record_id + } +} + +#[tokio::test] +async fn uninstall_keep_archives_only_the_plugins_durable_records_and_keeps_private_storage() { + use crate::plugin_host::retention::DataRetention; + + let fixture = UninstallFixture::new("org.example.producer", "producer"); + let record_id = fixture.publish("disc-1", "Dolphin").await; + let other_owner = OwnerScope::new([9; 32], 1).unwrap(); + fixture + .root + .shared_pool + .persist(crate::plugin_host::shared_pool::DurableWrite { + owner: other_owner, + dataset_id: "org.example.catalog".to_owned(), + schema_id: "org.example.catalog.v1".to_owned(), + schema_version: 1, + fields_json: r#"{"title":"Other"}"#.to_owned(), + opaque_payload: Vec::new(), + resource_id: Some("disc-2".to_owned()), + observed_at: 1_700_000_000, + sequence: 1, + source_observation_id: "observation-other".to_owned(), + expires_at: None, + now: 1_700_000_000, + provenance: gamenode_platform::plugin_shared_data::RecordProvenance { + source_plugin_id: "org.example.other".to_owned(), + source_publisher_fingerprint: "cd".repeat(32), + source_profile_id: "account-one".to_owned(), + declared_developer: "Other".to_owned(), + origin: "registry".to_owned(), + package_version: "1.0.0".to_owned(), + package_digest: vec![8; 32], + }, + }) + .await + .unwrap(); + let private = fixture.dir.path().join("plugin-data/private.json"); + std::fs::create_dir_all(private.parent().unwrap()).unwrap(); + std::fs::write(&private, b"private").unwrap(); + + let lifecycle = fixture.lifecycle(); + let outcome = lifecycle + .remove_with_retention(fixture.plugin_id.to_owned(), DataRetention::Keep) + .await + .unwrap(); + assert_eq!(outcome.data_retention, "kept"); + assert_eq!(outcome.archived_records, 1); + assert_eq!(outcome.removed_records, 0); + + let usage = fixture + .root + .shared_pool + .usage(fixture.owner, 1_700_000_100) + .await + .unwrap() + .unwrap(); + assert_eq!(usage.records, 0, "kept rows are inert"); + assert_eq!(usage.archived_records, 1); + assert!( + fixture + .root + .shared_pool + .get_any(record_id, 1_700_000_100) + .await + .unwrap() + .is_none() + ); + let other = fixture + .root + .shared_pool + .usage(other_owner, 1_700_000_100) + .await + .unwrap() + .unwrap(); + assert_eq!(other.records, 1, "another owner is untouched"); + assert_eq!(other.archived_records, 0); + assert_eq!(std::fs::read(&private).unwrap(), b"private"); +} + +#[tokio::test] +async fn reinstalling_requires_a_reviewed_reuse_before_archived_records_are_readable() { + use crate::plugin_host::retention::DataRetention; + + let fixture = UninstallFixture::new("org.example.producer", "producer"); + let record_id = fixture.publish("disc-1", "Dolphin").await; + let lifecycle = fixture.lifecycle(); + lifecycle + .remove_with_retention(fixture.plugin_id.to_owned(), DataRetention::Keep) + .await + .unwrap(); + + // Archived rows are invisible to every ordinary read path, including a fresh consumer list. + assert!( + fixture + .root + .shared_pool + .list_dataset_any("org.example.catalog".to_owned(), 1_700_000_100) + .await + .unwrap() + .0 + .is_empty() + ); + assert!( + fixture + .root + .shared_pool + .get_any(record_id.clone(), 1_700_000_100) + .await + .unwrap() + .is_none() + ); + + // A reinstall shares the owner key, but still needs the separate reviewed reuse decision. + fixture.reinstall("1.0.1"); + let profile_id = fixture + .root + .providers + .profiles() + .require() + .unwrap() + .profile_id() + .to_owned(); + let denied = lifecycle + .reuse_archived_durable_data(fixture.plugin_id.to_owned(), &profile_id, false) + .await + .unwrap_err(); + assert_eq!(denied.code(), tonic::Code::FailedPrecondition); + assert!( + fixture + .root + .shared_pool + .get_any(record_id.clone(), 1_700_000_110) + .await + .unwrap() + .is_none(), + "an unconfirmed reuse changes nothing" + ); + + let reused = lifecycle + .reuse_archived_durable_data(fixture.plugin_id.to_owned(), &profile_id, true) + .await + .unwrap(); + assert_eq!(reused.archived_records, 1); + let listed = fixture + .root + .shared_pool + .list_dataset_any("org.example.catalog".to_owned(), 1_700_000_120) + .await + .unwrap() + .0; + assert_eq!(listed.len(), 1); + assert_eq!(listed[0].record_id, record_id); + assert_eq!( + listed[0].fields.get("title"), + Some(&serde_json::Value::String("Dolphin".to_owned())) + ); +} + +#[tokio::test] +async fn uninstall_delete_removes_only_the_selected_plugins_durable_records() { + use crate::plugin_host::retention::DataRetention; + + let fixture = UninstallFixture::new("org.example.producer", "producer"); + fixture.publish("disc-1", "Dolphin").await; + let other_owner = OwnerScope::new([9; 32], 1).unwrap(); + fixture + .root + .shared_pool + .persist(crate::plugin_host::shared_pool::DurableWrite { + owner: other_owner, + dataset_id: "org.example.catalog".to_owned(), + schema_id: "org.example.catalog.v1".to_owned(), + schema_version: 1, + fields_json: r#"{"title":"Other"}"#.to_owned(), + opaque_payload: Vec::new(), + resource_id: Some("disc-2".to_owned()), + observed_at: 1_700_000_000, + sequence: 1, + source_observation_id: "observation-other".to_owned(), + expires_at: None, + now: 1_700_000_000, + provenance: gamenode_platform::plugin_shared_data::RecordProvenance { + source_plugin_id: "org.example.other".to_owned(), + source_publisher_fingerprint: "cd".repeat(32), + source_profile_id: "account-one".to_owned(), + declared_developer: "Other".to_owned(), + origin: "registry".to_owned(), + package_version: "1.0.0".to_owned(), + package_digest: vec![8; 32], + }, + }) + .await + .unwrap(); + + let lifecycle = fixture.lifecycle(); + let outcome = lifecycle + .remove_with_retention(fixture.plugin_id.to_owned(), DataRetention::Delete) + .await + .unwrap(); + assert_eq!(outcome.data_retention, "deleted"); + assert_eq!(outcome.removed_records, 1); + assert!(outcome.reclaimed_bytes > 0); + let usage = fixture + .root + .shared_pool + .usage(fixture.owner, 1_700_000_100) + .await + .unwrap() + .unwrap(); + assert_eq!(usage.records, 0); + assert_eq!(usage.archived_records, 0); + let other = fixture + .root + .shared_pool + .usage(other_owner, 1_700_000_100) + .await + .unwrap() + .unwrap(); + assert_eq!(other.records, 1, "another owner is untouched"); +} + +#[tokio::test] +async fn uninstall_keep_archives_private_entries_and_needs_a_reviewed_reuse() { + use crate::plugin_host::retention::DataRetention; + + let fixture = UninstallFixture::new("org.example.producer", "producer"); + fixture.write_private(fixture.plugin_id, "kept", b"private value"); + fixture.write_private_at(fixture.plugin_id, "account-two", "kept", b"other profile"); + fixture.write_private("org.example.other", "kept", b"other plugin"); + let save = fixture.dir.path().join("saves/slot-1.sav"); + std::fs::create_dir_all(save.parent().unwrap()).unwrap(); + std::fs::write(&save, b"game save").unwrap(); + let backup = fixture.dir.path().join("backups/slot-1.zip"); + std::fs::create_dir_all(backup.parent().unwrap()).unwrap(); + std::fs::write(&backup, b"backup archive").unwrap(); + + let lifecycle = fixture.lifecycle(); + let outcome = lifecycle + .remove_with_retention(fixture.plugin_id.to_owned(), DataRetention::Keep) + .await + .unwrap(); + assert_eq!(outcome.data_retention, "kept"); + assert_eq!(outcome.private_archived_records, 1); + assert_eq!(outcome.private_removed_records, 0); + assert!(fixture.read_private(fixture.plugin_id, "kept").is_none()); + assert_eq!( + fixture.read_private("org.example.other", "kept").as_deref(), + Some(&b"other plugin"[..]) + ); + assert!( + std::fs::read( + fixture + .private_dir(fixture.plugin_id, "account-two") + .join("storage.sqlite3") + ) + .is_ok(), + "another profile is untouched" + ); + + // A reinstall shares the owner namespace but cannot read or replace the archived value. + fixture.reinstall("1.0.1"); + let dir = fixture.private_dir(fixture.plugin_id, &fixture.profile_id()); + let mut store = gamenode_platform::plugin_storage::DurableStore::open(&dir).unwrap(); + assert_eq!(store.archived_usage().unwrap().records, 1); + assert!(matches!( + store.put( + "kept", + b"replacement", + 2, + None, + 100, + gamenode_platform::plugin_storage::QUOTA_BYTES + ), + Err(gamenode_platform::plugin_storage::PluginStorageError::Archived) + )); + drop(store); + + let profile_id = fixture + .root + .providers + .profiles() + .require() + .unwrap() + .profile_id() + .to_owned(); + let unconfirmed = lifecycle + .reuse_archived_private_data(fixture.plugin_id.to_owned(), &profile_id, false) + .await + .unwrap_err(); + assert_eq!(unconfirmed.code(), tonic::Code::FailedPrecondition); + let wrong_profile = lifecycle + .reuse_archived_private_data(fixture.plugin_id.to_owned(), "another-profile", true) + .await + .unwrap_err(); + assert_eq!(wrong_profile.code(), tonic::Code::FailedPrecondition); + assert!(fixture.read_private(fixture.plugin_id, "kept").is_none()); + let reused = lifecycle + .reuse_archived_private_data(fixture.plugin_id.to_owned(), &profile_id, true) + .await + .unwrap(); + assert_eq!(reused.restored_records, 1); + assert_eq!( + fixture.read_private(fixture.plugin_id, "kept").as_deref(), + Some(&b"private value"[..]) + ); + + assert_eq!(std::fs::read(&save).unwrap(), b"game save"); + assert_eq!(std::fs::read(&backup).unwrap(), b"backup archive"); +} + +#[tokio::test] +async fn uninstall_delete_removes_only_the_selected_private_namespace() { + use crate::plugin_host::retention::DataRetention; + + let fixture = UninstallFixture::new("org.example.producer", "producer"); + fixture.write_private(fixture.plugin_id, "kept", b"private value"); + fixture.write_private_at(fixture.plugin_id, "account-two", "kept", b"other profile"); + fixture.write_private("org.example.other", "kept", b"other plugin"); + let other_owner = OwnerScope::new([9; 32], 1).unwrap(); + fixture + .root + .shared_pool + .persist(crate::plugin_host::shared_pool::DurableWrite { + owner: other_owner, + dataset_id: "org.example.catalog".to_owned(), + schema_id: "org.example.catalog.v1".to_owned(), + schema_version: 1, + fields_json: r#"{"title":"Other owner"}"#.to_owned(), + opaque_payload: Vec::new(), + resource_id: Some("disc-other".to_owned()), + observed_at: 1_700_000_000, + sequence: 1, + source_observation_id: "observation-other".to_owned(), + expires_at: None, + now: 1_700_000_000, + provenance: gamenode_platform::plugin_shared_data::RecordProvenance { + source_plugin_id: "org.example.other".to_owned(), + source_publisher_fingerprint: "cd".repeat(32), + source_profile_id: "account-one".to_owned(), + declared_developer: "Other".to_owned(), + origin: "registry".to_owned(), + package_version: "1.0.0".to_owned(), + package_digest: vec![8; 32], + }, + }) + .await + .unwrap(); + let save = fixture.dir.path().join("saves/slot-1.sav"); + std::fs::create_dir_all(save.parent().unwrap()).unwrap(); + std::fs::write(&save, b"game save").unwrap(); + + let lifecycle = fixture.lifecycle(); + let outcome = lifecycle + .remove_with_retention(fixture.plugin_id.to_owned(), DataRetention::Delete) + .await + .unwrap(); + assert_eq!(outcome.data_retention, "deleted"); + assert_eq!(outcome.private_removed_records, 1); + assert_eq!( + outcome.private_reclaimed_bytes, + gamenode_platform::plugin_storage::charge("kept", 13) + ); + assert!( + !fixture + .private_dir(fixture.plugin_id, &fixture.profile_id()) + .exists() + ); + assert!( + fixture + .private_dir(fixture.plugin_id, "account-two") + .exists(), + "another profile is untouched" + ); + assert_eq!( + fixture.read_private("org.example.other", "kept").as_deref(), + Some(&b"other plugin"[..]) + ); + assert_eq!(std::fs::read(&save).unwrap(), b"game save"); + assert_eq!( + fixture + .root + .shared_pool + .usage(other_owner, 1_700_000_100) + .await + .unwrap() + .unwrap() + .records, + 1, + "another owner's durable pool row is untouched" + ); +} + +#[cfg(target_os = "linux")] +struct NoConsumerServices; + +#[cfg(target_os = "linux")] +#[tonic::async_trait] +impl crate::plugin_host::provider::HostServices for NoConsumerServices { + async fn context( + &self, + _: crate::plugin_host::provider::Lease, + ) -> Result { + Err(Status::unimplemented("consumer fixture")) + } + async fn account( + &self, + _: crate::plugin_host::provider::Lease, + _: gamenode_plugin_protocol::proto::account_request::Action, + ) -> Result { + Err(Status::unimplemented("consumer fixture")) + } + async fn secret( + &self, + _: crate::plugin_host::provider::Lease, + _: gamenode_plugin_protocol::proto::SecretRequest, + ) -> Result { + Err(Status::unimplemented("consumer fixture")) + } + async fn login( + &self, + _: crate::plugin_host::provider::Lease, + _: gamenode_plugin_protocol::proto::LoginRequest, + ) -> Result { + Err(Status::unimplemented("consumer fixture")) + } + async fn actions( + &self, + _: crate::plugin_host::provider::Lease, + _: gamenode_plugin_protocol::proto::ActionDeclaration, + ) -> Result { + Err(Status::unimplemented("consumer fixture")) + } +} + +/// A second third-party plugin session for consumer reads. It is the ordinary host registration +/// and session handshake, not a fixture provider: only the Dolphin producer is the real artifact. +#[cfg(target_os = "linux")] +async fn durable_consumer_session( + api: &crate::plugin_host::PluginApi, + endpoint: &Path, +) -> gamenode_plugin_sdk::Session { + use gamenode_plugin_sdk::{Launch as SdkLaunch, Session, SessionOptions}; + + api.providers + .register(Registration { + provider_id: "consumer".into(), + plugin_id: "org.example.consumer".into(), + kind: RegistrationKind::Provider, + declared_developer: "Consumer developer".into(), + package_digest: vec![8; 32], + origin: RegistrationOrigin::ThirdParty { + publisher_fingerprint: "cd".repeat(32), + }, + capabilities: vec![cap::CONTEXT.into()], + shared_catalog: false, + playtime: Default::default(), + services: Arc::new(NoConsumerServices), + }) + .unwrap(); + let launch = api.providers.begin_launch("consumer").unwrap(); + let credential = (0..launch.credential.len()) + .step_by(2) + .map(|index| u8::from_str_radix(&launch.credential[index..index + 2], 16).unwrap()) + .collect(); + let session = Session::open_with_options( + SdkLaunch { + endpoint: endpoint.to_path_buf(), + credential, + operation_id: "consumer-launch".into(), + }, + "org.example.consumer", + "consumer", + "1.0", + &[cap::CONTEXT], + SessionOptions { + min_api_major: 1, + min_api_minor: cap::THIRD_PARTY_API_MINOR, + max_api_major: 1, + max_api_minor: gamenode_plugin_protocol::API_MINOR, + ..SessionOptions::default() + }, + ) + .await + .unwrap(); + launch.ready.await.unwrap(); + session +} + +/// The production `ResourceHost` handlers over a local TCP transport, so a consumer test sends +/// the same `DataGet`/`DataList`/`DataWatch` messages the SDK sends over the host socket. +#[cfg(target_os = "linux")] +async fn local_resource_client( + api: Arc, +) -> ( + gamenode_plugin_protocol::proto::resource_host_client::ResourceHostClient< + tonic::transport::Channel, + >, + tokio::task::JoinHandle<()>, +) { + use gamenode_plugin_protocol::proto::resource_host_server::ResourceHostServer; + use tokio_stream::wrappers::TcpListenerStream; + + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let server = tokio::spawn(async move { + tonic::transport::Server::builder() + .add_service(ResourceHostServer::new((*api).clone())) + .serve_with_incoming(TcpListenerStream::new(listener)) + .await + .unwrap(); + }); + let client = + gamenode_plugin_protocol::proto::resource_host_client::ResourceHostClient::connect( + format!("http://{address}"), + ) + .await + .unwrap(); + (client, server) +} + +#[cfg(target_os = "linux")] +fn catalog_projection( + record: &gamenode_plugin_protocol::proto::DataRecord, +) -> std::collections::BTreeMap { + use gamenode_plugin_protocol::prost_types::value::Kind; + + record + .value + .as_ref() + .expect("the catalog record carries a payload") + .fields + .iter() + .map(|(key, value)| { + ( + key.clone(), + match value.kind.as_ref() { + Some(Kind::StringValue(value)) => value.clone(), + other => panic!("the Dolphin catalog uses string fields: {other:?}"), + }, + ) + }) + .collect() +} + +#[cfg(target_os = "linux")] +fn assert_catalog_projection( + record: &gamenode_plugin_protocol::proto::DataRecord, + digest: &[u8], + fingerprint: &str, +) { + use gamenode_plugin_protocol::proto::StorageDurability; + + let fields = catalog_projection(record); + let expected = std::collections::BTreeMap::from([ + ("disc_id".to_owned(), "GZLE01".to_owned()), + ("title".to_owned(), "The Legend of Zelda".to_owned()), + ("platform".to_owned(), "gamecube".to_owned()), + ("content_id".to_owned(), "GZLE01".to_owned()), + ]); + assert_eq!(fields, expected, "only the reviewed fields are projected"); + assert_eq!(record.dataset_id, DOLPHIN_DATASET); + assert_eq!(record.publisher_id, DOLPHIN_PLUGIN); + assert_eq!( + record.durability, + StorageDurability::Persistent as i32, + "the record reports its actual durability" + ); + let provenance = record.provenance.as_ref().expect("host provenance"); + assert_eq!(provenance.producer_plugin_id, DOLPHIN_PLUGIN); + assert_eq!(provenance.publisher_fingerprint, fingerprint); + assert_eq!(provenance.package_digest, digest); + assert!( + provenance.package_digest.len() == 32, + "provenance names a 32-byte installed package digest" + ); + // No physical path and no reserved or scanner-only field crossed the API. + for (key, value) in &fields { + assert!( + !matches!(key.as_str(), "path" | "rom" | "install_dir" | "owner"), + "reserved or scanner-only field {key} leaked" + ); + assert!( + !value.contains(['/', '\\']), + "a physical path leaked in {key}" + ); + } +} + +#[cfg(target_os = "linux")] +const DOLPHIN_PLUGIN: &str = "dev.richmont.gamenode.dolphin-emu"; +#[cfg(target_os = "linux")] +const DOLPHIN_PROVIDER: &str = "dolphin-emu"; +#[cfg(target_os = "linux")] +const DOLPHIN_DATASET: &str = "dev.richmont.gamenode.dolphin-emu.catalog.v1"; + +/// 6.3/7.2 Linux acceptance with the real signed bundle: the installed provider discovers a disc, +/// publishes the durable catalog row under the production `HostedProviders::bundled` registration, +/// and a consumer reads it with Dolphin stopped, across a broker/pool restart, and after +/// revocation. The platform has no Windows Dolphin target, so this test is Linux-only. +#[cfg(target_os = "linux")] +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn the_real_dolphin_provider_publishes_a_durable_catalog_read_with_it_stopped() { + use crate::plugin_host::{ + PluginApi, + bundles::dolphin_bundle_artifact, + grants::PermissionDecision, + profile::PluginStateLayout, + resources::ResourceApi, + shared_data::DataBroker, + shared_pool::DurableSharedPool, + sharing_policy::{ActivationReadGrant, SharingClass, SourceRecipientPolicy}, + updates::PluginUpdateService, + }; + use gamenode_platform::{ + db::SqliteSettingsStore, paths::DataPaths, plugin_registry::PluginPackageRegistry, + }; + use gamenode_plugin_protocol::proto::{ + DataGetRequest, DataListRequest, DataWatchRequest, PageRequest, + }; + use std::ffi::OsString; + use std::os::unix::fs::PermissionsExt; + + let Some(artifact) = dolphin_bundle_artifact() else { + return; + }; + + let directory = tempfile::tempdir().unwrap(); + std::fs::set_permissions(directory.path(), std::fs::Permissions::from_mode(0o700)).unwrap(); + let paths = DataPaths::at(directory.path().join("app-data")); + let state = PluginStateLayout::managed(&paths); + let api = PluginApi { + shared_pool: Arc::new(DurableSharedPool::new(paths.data_dir())), + ..Default::default() + }; + api.set_state_layout(state.clone()); + api.providers + .profiles() + .update(Some("dolphin-emu-account"), true); + let registry = PluginPackageRegistry::open(&paths).unwrap(); + let settings = SqliteSettingsStore::open(&paths.database_file()).unwrap(); + let endpoint = paths.data_dir().join("plugins.sock"); + + // Compose the production runtime first: the accepted import must register into this same + // host, so no second HostedProviders is built and no restart is involved. Opening the update + // service prepares the private layout the host composition reads. + let service = PluginUpdateService::open(&paths).unwrap(); + let library: Arc = Arc::new( + SqliteSettingsStore::open(&paths.database_file()) + .unwrap() + .library_store(), + ); + let host = HostedProviders::bundled( + api.providers.clone(), + Arc::new(Default::default()), + Some(endpoint.clone()), + paths.clone(), + library, + None, + ) + .await + .unwrap(); + let server = + PluginApiServer::start(&tokio::runtime::Handle::current(), &endpoint, api.clone()).unwrap(); + + // Install the real bundle through the reviewed import flow, exactly as 7.1 does. + service.set_lifecycle(host.lifecycle()); + service.set_profiles(api.providers.profiles()); + service.set_bundle_store(settings.bundle_store()); + let review = service + .bundle_import_review(artifact.clone()) + .await + .unwrap(); + assert_eq!(review.bundle.id, "dev.richmont.gamenode.dolphin-emu.bundle"); + service + .bundle_import_confirm_publisher(&review.token, &review.bundle.publisher_fingerprint) + .await + .unwrap(); + let installed_bundle = service + .bundle_import_install(&review.token, false, &[]) + .await + .unwrap(); + assert_eq!( + installed_bundle.bundle_id, + "dev.richmont.gamenode.dolphin-emu.bundle" + ); + // The launch extension is runtime-available and enabled immediately after the accepted + // import; the provider is running from the same host composition. + let launch_component = installed_bundle + .components + .iter() + .find(|component| component.kind == "extension") + .expect("the bundle carries the launch extension"); + assert!(launch_component.active); + assert!( + launch_component.activated, + "{:?}", + launch_component.activation_error + ); + assert!( + host.lifecycle() + .extension_runtime_available(&launch_component.plugin_id) + ); + assert!( + host.lifecycle() + .enabled(launch_component.plugin_id.clone()) + .await + .unwrap() + ); + let provider_component = installed_bundle + .components + .iter() + .find(|component| component.kind == "provider") + .expect("the bundle carries the discovery provider"); + assert!( + provider_component.activated, + "{:?}", + provider_component.activation_error + ); + let installed = registry.active(DOLPHIN_PLUGIN).unwrap().unwrap(); + let digest = installed_package_digest(&installed.package_path).unwrap(); + assert_eq!(digest.len(), 32); + + // Grant exactly the catalog path the bundle declares and enable the component. + let activation = tokio::sync::Mutex::new(()); + let snapshot = host + .lifecycle() + .permission_snapshot(DOLPHIN_PLUGIN.into()) + .await + .unwrap(); + assert_eq!( + snapshot.publisher_fingerprint, + review.bundle.publisher_fingerprint + ); + let decisions = snapshot + .requested_permissions + .iter() + .flat_map(|request| { + request + .allowed_scopes + .iter() + .map(|scope| PermissionDecision { + permission_id: request.permission_id.clone(), + scope: scope.clone(), + granted: true, + }) + }) + .collect::>(); + let granted = host + .lifecycle() + .replace_permissions( + &activation, + DOLPHIN_PLUGIN.into(), + snapshot.profile_id.clone(), + snapshot.publisher_fingerprint.clone(), + snapshot.grant_revision, + decisions, + ) + .await + .unwrap(); + for permission in [ + "provider.context.read", + "library.discovery", + "data.publish", + "storage.persist", + ] { + assert!( + granted.effective_grants.iter().any(|grant| { + grant.permission_id == permission + && grant.state == crate::plugin_host::grants::PermissionState::Granted + }), + "{permission} is granted: {:?}", + granted.effective_grants + ); + } + host.lifecycle() + .enable(DOLPHIN_PLUGIN.into()) + .await + .unwrap(); + + // A temporary Dolphin collection. The scanner reads the six-byte disc header and takes the + // title from the ROM file name, so the plain-disc fixture is named like a real collection. + let rom_root = directory.path().join("collection"); + std::fs::create_dir_all(&rom_root).unwrap(); + std::fs::write( + rom_root.join("The Legend of Zelda.iso"), + b"GZLE01\x00\x00\x00\x00", + ) + .unwrap(); + let mut config = host.processes.config(DOLPHIN_PROVIDER).unwrap(); + config.environment.push(( + OsString::from("DOLPHIN_PLUGIN_ROOTS"), + rom_root.clone().into_os_string(), + )); + host.processes + .replace_config(DOLPHIN_PROVIDER, config) + .await + .unwrap(); + + let completion = host + .execute(DOLPHIN_PROVIDER, ProviderOperation::Discover) + .await + .unwrap(); + let discovery = completion + .result + .discovery + .expect("Discover returns the scanner's records"); + assert_eq!(discovery.provider_id, DOLPHIN_PROVIDER); + assert_eq!(discovery.records.len(), 1, "{discovery:?}"); + let discovered = &discovery.records[0]; + assert_eq!(discovered.id, "GZLE01"); + assert_eq!(discovered.name, "The Legend of Zelda"); + assert_eq!( + discovered.fields.get("platform").map(String::as_str), + Some("gamecube") + ); + + // The durable row is written by the provider's own DataPublish during Discover. Poll on a + // bounded timeout instead of sleeping: the publication has already completed by now. + let pool = api.shared_pool.clone(); + let now_seconds = || { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_secs() as i64 + }; + let stored = tokio::time::timeout(Duration::from_secs(5), async { + loop { + let (rows, _) = pool + .list_dataset_any(DOLPHIN_DATASET.to_owned(), now_seconds()) + .await + .unwrap(); + if let Some(row) = rows + .into_iter() + .find(|row| row.dataset_id == DOLPHIN_DATASET) + { + return row; + } + tokio::time::sleep(Duration::from_millis(25)).await; + } + }) + .await + .expect("the provider's durable catalog row reaches the host pool"); + assert_eq!(stored.provenance.source.plugin_id, DOLPHIN_PLUGIN); + assert_eq!( + stored.provenance.source.profile_id, snapshot.profile_id, + "provenance names the active account profile" + ); + assert_eq!(stored.provenance.package_version, "0.1.0"); + assert_eq!(stored.provenance.package_digest.len(), 32); + assert_eq!( + stored.provenance.package_digest, digest, + "provenance names the installed signed package" + ); + assert_eq!(stored.owner.plugin_id, DOLPHIN_PLUGIN); + let record_id = stored.record_id.clone(); + + // Stop the real provider before any consumer read. + host.stop(DOLPHIN_PROVIDER).await.unwrap(); + tokio::time::timeout(Duration::from_secs(5), async { + while host.processes.process_id(DOLPHIN_PROVIDER).await.is_some() { + tokio::time::sleep(Duration::from_millis(20)).await; + } + }) + .await + .expect("the stopped provider process exits"); + assert!(!api.providers.connected(DOLPHIN_PROVIDER)); + + // The exact source/recipient/dataset policy for the consumer plugin. + let consumer = durable_consumer_session(&api, &endpoint).await; + let consumer_context = consumer.host.resource_context().unwrap().clone(); + let caller = api + .providers + .authorize_resource_session(Some(&consumer_context)) + .unwrap(); + let recipient = caller + .namespace + .as_ref() + .expect("the consumer has a third-party namespace") + .identity() + .clone(); + let (source_plugin, source_fingerprint) = api + .providers + .third_party_identity(DOLPHIN_PROVIDER) + .unwrap(); + let source = crate::plugin_host::grants::PluginIdentity { + plugin_id: source_plugin, + publisher_fingerprint: source_fingerprint, + profile_id: snapshot.profile_id.clone(), + }; + api.shared_policies + .set_source_recipient_policy( + SourceRecipientPolicy::new( + source.clone(), + recipient.clone(), + SharingClass::Custom, + DOLPHIN_DATASET.into(), + ["disc_id", "title", "platform", "content_id"].map(str::to_owned), + true, + true, + ) + .unwrap(), + ) + .unwrap(); + + let (mut consumer_rpc, consumer_server) = local_resource_client(server.resource_api()).await; + let listed = consumer_rpc + .data_list(DataListRequest { + page: Some(PageRequest { + context: Some(consumer_context.clone()), + page_size: 10, + ..Default::default() + }), + dataset_id: DOLPHIN_DATASET.into(), + ..Default::default() + }) + .await + .unwrap() + .into_inner(); + assert_eq!(listed.records.len(), 1, "{listed:?}"); + assert_eq!(listed.records[0].record_id, record_id); + assert_catalog_projection( + &listed.records[0], + &digest, + &review.bundle.publisher_fingerprint, + ); + let fetched = consumer_rpc + .data_get(DataGetRequest { + context: Some(consumer_context.clone()), + dataset_id: DOLPHIN_DATASET.into(), + record_id: record_id.clone(), + ..Default::default() + }) + .await + .unwrap() + .into_inner() + .record + .unwrap(); + assert_eq!(fetched.record_id, record_id); + assert_catalog_projection(&fetched, &digest, &review.bundle.publisher_fingerprint); + assert_eq!( + fetched.expires_at, 0, + "the provider requests no TTL, so retention is the pool policy rather than an expiry" + ); + + // A real host restart: a fresh broker over a pool reopened from the same data folder. The + // persisted pool sequence resumes instead of restarting at zero. + let restarted_broker = Arc::new(DataBroker::new()); + assert_eq!(restarted_broker.revision(), 0); + let restarted_pool = Arc::new(DurableSharedPool::new(paths.data_dir())); + let restarted = ResourceApi::new( + api.providers.clone(), + api.library.clone(), + api.storage.clone(), + api.files.clone(), + api.network.clone(), + api.notifications.clone(), + api.jobs.clone(), + api.intents.clone(), + api.saves.clone(), + api.fingerprints.clone(), + api.leases.clone(), + api.processes.clone(), + ) + .with_shared_data(restarted_broker.clone(), api.shared_policies.clone()) + .with_shared_pool(restarted_pool); + let (mut restarted_rpc, restarted_server) = local_resource_client(Arc::new(restarted)).await; + let relisted = restarted_rpc + .data_list(DataListRequest { + page: Some(PageRequest { + context: Some(consumer_context.clone()), + page_size: 10, + ..Default::default() + }), + dataset_id: DOLPHIN_DATASET.into(), + ..Default::default() + }) + .await + .unwrap() + .into_inner(); + assert_eq!(relisted.records.len(), 1, "{relisted:?}"); + assert_eq!(relisted.records[0].record_id, record_id); + assert!( + relisted.revision >= 1, + "the restarted broker resumes the persisted pool revision: {}", + relisted.revision + ); + assert_catalog_projection( + &relisted.records[0], + &digest, + &review.bundle.publisher_fingerprint, + ); + let refetched = restarted_rpc + .data_get(DataGetRequest { + context: Some(consumer_context.clone()), + dataset_id: DOLPHIN_DATASET.into(), + record_id: record_id.clone(), + ..Default::default() + }) + .await + .unwrap() + .into_inner() + .record + .unwrap(); + assert_catalog_projection(&refetched, &digest, &review.bundle.publisher_fingerprint); + + // Revoking the reviewed policy fences the read and an open watch while Dolphin stays stopped. + use futures_util::StreamExt as _; + let mut watch = restarted_rpc + .data_watch(DataWatchRequest { + context: Some(consumer_context.clone()), + dataset_id: DOLPHIN_DATASET.into(), + after_revision: relisted.revision, + ..Default::default() + }) + .await + .unwrap() + .into_inner(); + let policy = api.shared_policies.recipient_snapshot(&recipient).unwrap(); + assert_eq!(policy.source_recipient_policies.len(), 1); + api.shared_policies + .replace_recipient_policies( + &recipient, + policy.revision, + ActivationReadGrant::default(), + vec![], + ) + .unwrap(); + let error = tokio::time::timeout(Duration::from_secs(7), watch.next()) + .await + .expect("revocation wakes the open watch") + .expect("the watch reports the fencing") + .unwrap_err(); + assert_eq!(error.code(), tonic::Code::FailedPrecondition); + let error = restarted_rpc + .data_get(DataGetRequest { + context: Some(consumer_context.clone()), + dataset_id: DOLPHIN_DATASET.into(), + record_id, + ..Default::default() + }) + .await + .unwrap_err(); + assert_eq!(error.code(), tonic::Code::NotFound); + let fenced = restarted_rpc + .data_list(DataListRequest { + page: Some(PageRequest { + context: Some(consumer_context), + page_size: 10, + ..Default::default() + }), + dataset_id: DOLPHIN_DATASET.into(), + ..Default::default() + }) + .await + .unwrap() + .into_inner(); + assert!( + fenced.records.is_empty(), + "revocation fences the durable list: {fenced:?}" + ); + + consumer_server.abort(); + restarted_server.abort(); + host.shutdown().await; + server.shutdown().await; +} diff --git a/crates/app/src/plugin_host/runtime_access.rs b/crates/app/src/plugin_host/runtime_access.rs new file mode 100644 index 000000000..d0a0fc676 --- /dev/null +++ b/crates/app/src/plugin_host/runtime_access.rs @@ -0,0 +1,740 @@ +//! Host-owned approval of one exact emulator executable. +//! +//! A plugin never names a path. It asks [`RuntimesRequestAccess`](crate::plugin_host::resources) +//! with text hints; the host matches its own installed-program inventory, shows a picker, valides +//! the program the user chose and records a durable [`RuntimeApproval`]. The runtime record points +//! at the approval, and every launch rechecks the approval's ownership, identity, size and +//! digest. None of the refusal messages or logs carries a path. +//! +//! The executable is a single file, not an approved folder: this approval grants no file access +//! and no traversal beside the program. + +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex}; + +use async_trait::async_trait; +use gamenode_platform::plugin_files::{self, Reserved}; +use gamenode_platform::plugin_storage::RuntimeApproval; +use serde::Serialize; +use sha2::{Digest, Sha256}; +use tokio::sync::oneshot; +use tonic::Status; + +/// The most a suggested executable may be; larger files are refused instead of hashed. +pub const MAX_EXECUTABLE_BYTES: u64 = 8 * 1024 * 1024 * 1024; +/// The most suggestions the picker shows for one request. +pub const MAX_SUGGESTIONS: usize = 32; +/// The largest text hint, in bytes. +const MAX_HINT_BYTES: usize = 256; +const MAX_HINTS: usize = 32; + +/// One host-owned installed program. Only the official PackageKit provider contributes entries +/// today; a third-party provider's records never become candidates. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct InstalledProgram { + pub display_name: String, + pub executable: String, + pub desktop_file: String, + pub package_id: String, + pub package_manager: String, +} + +/// A program the picker offers, with the facts the user reviews before approving it. +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct RuntimeExecutableCandidate { + pub display_name: String, + pub package_manager: String, + pub package_id: String, + /// The package version when the package id carries one; empty otherwise. + pub version: String, + /// The exact path that would be approved. + pub path: String, +} + +/// The text hints an extension declared. They are matched against host inventory and are never +/// paths. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct RuntimeHints { + pub executable_names: Vec, + pub desktop_ids: Vec, +} + +impl RuntimeHints { + pub fn validate(&self) -> bool { + let valid = |value: &str| { + !value.is_empty() + && value.len() <= MAX_HINT_BYTES + && !value + .chars() + .any(|character| character.is_control() || matches!(character, '/' | '\\')) + }; + self.executable_names.len() + self.desktop_ids.len() <= MAX_HINTS + && self + .executable_names + .iter() + .chain(&self.desktop_ids) + .all(|hint| valid(hint)) + } + + pub fn is_empty(&self) -> bool { + self.executable_names.is_empty() && self.desktop_ids.is_empty() + } +} + +/// What the host asks the user to choose. The candidate paths are host-owned and intentionally +/// shown; nothing else in the request is a path. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct RuntimeAccessRequest { + pub plugin_id: String, + pub publisher_fingerprint: String, + pub runtime_name: String, + pub runtime_version: String, + pub platform: String, + pub supported_formats: Vec, + pub hints: RuntimeHints, + pub candidates: Vec, +} + +/// Plain event data for the runtime picker. Paths are shown because the user approves one exact +/// program; they never travel back to the plugin or into logs. +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct RuntimeSelectionPrompt { + pub id: String, + pub plugin_id: String, + pub publisher_fingerprint: String, + pub runtime_name: String, + pub runtime_version: String, + pub platform: String, + pub supported_formats: Vec, + pub hints: Vec, + pub candidates: Vec, +} + +/// The user's side of the runtime approval. The host calls it off the UI thread and a call that +/// takes longer than [`APPROVAL_TIMEOUT`](super::files::APPROVAL_TIMEOUT) counts as declined. +#[async_trait] +pub trait RuntimeApprover: Send + Sync { + /// Lets the user choose one executable. `None` is a refusal. + async fn choose_executable( + &self, + request: RuntimeAccessRequest, + ) -> Result, Status>; +} + +/// The window event that opens the runtime picker. +pub const RUNTIME_SELECT_EVENT: &str = "plugin:runtime-approval-select"; +/// The window event that closes a runtime prompt that was withdrawn or timed out. +pub const RUNTIME_CLOSED_EVENT: &str = "plugin:runtime-approval-closed"; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum RuntimeApprovalSignal { + Select(RuntimeSelectionPrompt), + Closed(String), +} + +pub type RuntimeApprovalEmit = Arc bool + Send + Sync>; + +struct ForgetRuntimePrompt<'a> { + bridge: &'a RuntimeApprovalBridge, + id: String, +} + +impl Drop for ForgetRuntimePrompt<'_> { + fn drop(&mut self) { + let removed = self + .bridge + .waiting + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .remove(&self.id) + .is_some(); + if removed { + (self.bridge.emit)(RuntimeApprovalSignal::Closed(self.id.clone())); + } + } +} + +/// Bridges runtime approval requests to the React window without making the host wait on the UI +/// thread. The call site owns the timeout. +pub struct RuntimeApprovalBridge { + emit: RuntimeApprovalEmit, + waiting: Mutex>>>, +} + +impl RuntimeApprovalBridge { + pub fn new(emit: RuntimeApprovalEmit) -> Self { + Self { + emit, + waiting: Mutex::default(), + } + } + + fn id() -> Result { + let mut bytes = [0_u8; 16]; + getrandom::fill(&mut bytes).map_err(|_| Status::internal("no source of randomness"))?; + Ok(bytes.iter().map(|byte| format!("{byte:02x}")).collect()) + } + + /// Answers a pending runtime prompt. A repeated or unknown answer is ignored. + pub fn answer(&self, id: &str, selected: Option) -> bool { + let sender = self + .waiting + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .remove(id); + sender.is_some_and(|sender| sender.send(selected).is_ok()) + } + + async fn choose(&self, request: RuntimeAccessRequest) -> Result, Status> { + let id = Self::id()?; + let (send, receive) = oneshot::channel(); + self.waiting + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .insert(id.clone(), send); + let _forget = ForgetRuntimePrompt { + bridge: self, + id: id.clone(), + }; + let mut hints = request.hints.executable_names.clone(); + hints.extend(request.hints.desktop_ids.iter().cloned()); + let shown = (self.emit)(RuntimeApprovalSignal::Select(RuntimeSelectionPrompt { + id, + plugin_id: request.plugin_id, + publisher_fingerprint: request.publisher_fingerprint, + runtime_name: request.runtime_name, + runtime_version: request.runtime_version, + platform: request.platform, + supported_formats: request.supported_formats, + hints, + candidates: request.candidates, + })); + if !shown { + return Err(Status::unavailable("there is no window to ask the user in")); + } + receive + .await + .map_err(|_| Status::unavailable("the runtime selection was closed")) + } +} + +#[async_trait] +impl RuntimeApprover for RuntimeApprovalBridge { + async fn choose_executable( + &self, + request: RuntimeAccessRequest, + ) -> Result, Status> { + Ok(self.choose(request).await?.map(PathBuf::from)) + } +} + +/// A validated executable the host may approve. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct InspectedExecutable { + /// The canonical, valid-Unicode path stored in the approval. + pub path: String, + pub volume: u64, + pub node: u64, + pub size: u64, + /// Lowercase hexadecimal SHA-256. + pub digest: String, +} + +/// Extracts the picker inventory from stored library entries. Only the official PackageKit +/// provider contributes; a third-party provider's record never becomes a candidate, even when its +/// fields contain something named `executable`. +pub fn installed_programs_from_entries( + entries: &[gamenode_core::library::StoredEntry], +) -> Vec { + entries + .iter() + .filter(|entry| entry.installed && entry.provider == "packagekit") + .filter_map(|entry| { + let executable = entry.fields.get("executable")?.trim(); + if executable.is_empty() { + return None; + } + Some(InstalledProgram { + display_name: entry + .name + .clone() + .filter(|name| !name.trim().is_empty()) + .unwrap_or_else(|| entry.store_id.clone()), + executable: executable.to_owned(), + desktop_file: entry + .fields + .get("desktop_file") + .map(|value| value.trim().to_owned()) + .unwrap_or_default(), + package_id: entry + .fields + .get("package_id") + .map(|value| value.trim().to_owned()) + .unwrap_or_default(), + package_manager: entry + .fields + .get("package_manager") + .map(|value| value.trim().to_owned()) + .unwrap_or_default(), + }) + }) + .collect() +} + +/// Matches host inventory against the extension's hints. Vendored package ids never contribute: +/// callers pass only entries from the official inventory reader. +pub fn suggestions( + programs: &[InstalledProgram], + hints: &RuntimeHints, +) -> Vec { + if hints.is_empty() { + return Vec::new(); + } + let mut by_path: BTreeMap = BTreeMap::new(); + for program in programs { + if !valid_inventory_path(&program.executable) { + continue; + } + let executable = Path::new(&program.executable); + let executable_name = executable + .file_name() + .map(|name| name.to_string_lossy().into_owned()) + .unwrap_or_default(); + let executable_stem = executable + .file_stem() + .map(|name| name.to_string_lossy().into_owned()) + .unwrap_or_default(); + let desktop = Path::new(&program.desktop_file); + let desktop_name = desktop + .file_name() + .map(|name| name.to_string_lossy().into_owned()) + .unwrap_or_default(); + let desktop_stem = desktop + .file_stem() + .map(|name| name.to_string_lossy().into_owned()) + .unwrap_or_default(); + + let executable_match = hints.executable_names.iter().any(|hint| { + component_matches(hint, &executable_name) || component_matches(hint, &executable_stem) + }); + let desktop_match = hints.desktop_ids.iter().any(|hint| { + component_matches(hint, &desktop_name) || component_matches(hint, &desktop_stem) + }); + if !executable_match && !desktop_match { + continue; + } + let display_name = program + .display_name + .trim() + .chars() + .take(256) + .collect::(); + let display_name = if display_name.is_empty() { + executable_stem.clone() + } else { + display_name + }; + let candidate = RuntimeExecutableCandidate { + display_name, + package_manager: plain_inventory_text(&program.package_manager), + package_id: plain_inventory_text(&program.package_id), + version: package_version(&program.package_id), + path: program.executable.trim().to_owned(), + }; + by_path + .entry(candidate.path.clone()) + .and_modify(|(existing, _)| *existing |= executable_match) + .or_insert((executable_match, candidate)); + } + let mut candidates: Vec<_> = by_path.into_values().collect(); + candidates.sort_by(|(left_exact, left), (right_exact, right)| { + right_exact + .cmp(left_exact) + .then_with(|| { + left.display_name + .to_lowercase() + .cmp(&right.display_name.to_lowercase()) + }) + .then_with(|| left.path.cmp(&right.path)) + }); + candidates + .into_iter() + .take(MAX_SUGGESTIONS) + .map(|(_, candidate)| candidate) + .collect() +} + +fn component_matches(hint: &str, component: &str) -> bool { + let hint = hint.trim(); + !hint.is_empty() && component.eq_ignore_ascii_case(hint) +} + +fn plain_inventory_text(value: &str) -> String { + value + .trim() + .chars() + .filter(|character| !character.is_control()) + .take(256) + .collect() +} + +/// `name;version;arch;repository` from PackageKit, or just a package name. +fn package_version(package_id: &str) -> String { + package_id + .split(';') + .nth(1) + .map(plain_inventory_text) + .unwrap_or_default() +} + +fn valid_inventory_path(path: &str) -> bool { + !path.trim().is_empty() + && path.len() <= 4096 + && !path + .chars() + .any(|character| character == '\0' || character.is_control()) +} + +/// Validates a path the user chose and records what will be approved. +/// +/// Blocking: it canonicalizes and hashes the file. The final component may not be a link; a +/// linked parent is resolved by the user's choice, and the stored canonical path is what is +/// rechecked later. +pub fn inspect_executable( + chosen: &Path, + reserved: &Reserved, +) -> Result { + let link_metadata = std::fs::symlink_metadata(chosen) + .map_err(|_| Status::failed_precondition("the selected program does not exist"))?; + if link_metadata.file_type().is_symlink() { + return Err(Status::permission_denied( + "the selected program may not be a link", + )); + } + if !link_metadata.is_file() { + return Err(Status::failed_precondition( + "the selected program is not a regular file", + )); + } + let canonical = std::fs::canonicalize(chosen) + .map_err(|_| Status::failed_precondition("the selected program does not exist"))?; + let metadata = std::fs::metadata(&canonical) + .map_err(|_| Status::failed_precondition("the selected program does not exist"))?; + if !metadata.is_file() { + return Err(Status::failed_precondition( + "the selected program is not a regular file", + )); + } + if reserved.is_reserved(&canonical) { + return Err(Status::permission_denied( + "that program cannot be approved for a plugin", + )); + } + if !is_executable(&canonical, &metadata) { + return Err(Status::failed_precondition( + "the selected program is not executable", + )); + } + if metadata.len() > MAX_EXECUTABLE_BYTES { + return Err(Status::resource_exhausted( + "the selected program is too large to approve", + )); + } + let identity = plugin_files::identity_of(&canonical) + .map_err(|_| Status::failed_precondition("the selected program cannot be inspected"))?; + let digest = hash_file(&canonical) + .map_err(|_| Status::failed_precondition("the selected program cannot be read"))?; + let path = canonical + .to_str() + .ok_or_else(|| { + Status::failed_precondition("the selected program path is not valid Unicode") + })? + .to_owned(); + Ok(InspectedExecutable { + path, + volume: identity.volume, + node: identity.node, + size: metadata.len(), + digest, + }) +} + +/// Rechecks a durable approval before it is reused or launched. Any changed identity, size or +/// digest invalidates it; the caller must not fall back to another path. +/// +/// Blocking: it hashes the file. +pub fn validate_approval( + approval: &RuntimeApproval, + reserved: &Reserved, +) -> Result { + if approval.revoked_at.is_some() { + return Err(Status::failed_precondition( + "the approved program is no longer approved", + )); + } + if approval.path.is_empty() || approval.digest.len() != 64 { + return Err(Status::failed_precondition( + "the approved program is unavailable; request access again", + )); + } + let path = Path::new(&approval.path); + let link_metadata = std::fs::symlink_metadata(path) + .map_err(|_| Status::failed_precondition("the approved program changed or is missing"))?; + if link_metadata.file_type().is_symlink() || !link_metadata.is_file() { + return Err(Status::failed_precondition( + "the approved program changed; request access again", + )); + } + let canonical = std::fs::canonicalize(path) + .map_err(|_| Status::failed_precondition("the approved program changed or is missing"))?; + if canonical != path { + return Err(Status::failed_precondition( + "the approved program changed; request access again", + )); + } + if reserved.is_reserved(&canonical) { + return Err(Status::permission_denied( + "the approved program cannot be started for a plugin", + )); + } + let metadata = std::fs::metadata(&canonical) + .map_err(|_| Status::failed_precondition("the approved program changed or is missing"))?; + if !metadata.is_file() || !is_executable(&canonical, &metadata) { + return Err(Status::failed_precondition( + "the approved program changed; request access again", + )); + } + if metadata.len() != approval.size { + return Err(Status::failed_precondition( + "the approved program changed; request access again", + )); + } + let identity = plugin_files::identity_of(&canonical) + .map_err(|_| Status::failed_precondition("the approved program cannot be inspected"))?; + if identity.volume != approval.volume || identity.node != approval.node { + return Err(Status::failed_precondition( + "the approved program changed; request access again", + )); + } + let digest = hash_file(&canonical) + .map_err(|_| Status::failed_precondition("the approved program cannot be read"))?; + if !digest.eq_ignore_ascii_case(&approval.digest) { + return Err(Status::failed_precondition( + "the approved program changed; request access again", + )); + } + Ok(approval.path.clone()) +} + +fn hash_file(path: &Path) -> std::io::Result { + use std::io::Read; + let mut file = std::fs::File::open(path)?; + let mut hasher = Sha256::new(); + let mut buffer = vec![0_u8; 1024 * 1024]; + loop { + let read = file.read(&mut buffer)?; + if read == 0 { + break; + } + hasher.update(&buffer[..read]); + } + Ok(hasher + .finalize() + .iter() + .map(|byte| format!("{byte:02x}")) + .collect()) +} + +#[cfg(unix)] +fn is_executable(path: &Path, metadata: &std::fs::Metadata) -> bool { + use std::os::unix::fs::PermissionsExt; + path.is_file() && metadata.permissions().mode() & 0o111 != 0 +} + +#[cfg(windows)] +fn is_executable(path: &Path, metadata: &std::fs::Metadata) -> bool { + path.extension() + .and_then(|extension| extension.to_str()) + .is_some_and(|extension| { + metadata.is_file() && matches!(extension.to_ascii_lowercase().as_str(), "exe" | "com") + }) +} + +#[cfg(not(any(unix, windows)))] +fn is_executable(_path: &Path, metadata: &std::fs::Metadata) -> bool { + metadata.is_file() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn program(id: &str, name: &str, executable: &str, desktop: &str) -> InstalledProgram { + InstalledProgram { + display_name: name.into(), + executable: executable.into(), + desktop_file: desktop.into(), + package_id: id.into(), + package_manager: "pacman".into(), + } + } + + #[test] + fn hints_match_executable_base_names_and_desktop_ids_without_duplicates() { + let programs = vec![ + program( + "dolphin-emu;2503-1;x86_64;extra", + "Dolphin Emulator", + "/usr/bin/dolphin-emu", + "/usr/share/applications/dolphin-emu.desktop", + ), + program( + "dolphin-emu;2503-1;x86_64;extra", + "Dolphin Emulator (duplicate path)", + "/usr/bin/dolphin-emu", + "/usr/share/applications/dolphin-emu.desktop", + ), + program( + "unrelated;1;x86_64;extra", + "Unrelated", + "/usr/bin/unrelated", + "/usr/share/applications/unrelated.desktop", + ), + ]; + let suggestions = suggestions( + &programs, + &RuntimeHints { + executable_names: vec!["dolphin-emu".into()], + desktop_ids: vec!["dolphin-emu.desktop".into()], + }, + ); + assert_eq!(suggestions.len(), 1); + assert_eq!(suggestions[0].display_name, "Dolphin Emulator"); + assert_eq!(suggestions[0].path, "/usr/bin/dolphin-emu"); + assert_eq!(suggestions[0].version, "2503-1"); + assert_eq!(suggestions[0].package_manager, "pacman"); + } + + #[test] + fn desktop_id_hint_matches_and_empty_inventory_yields_no_candidates() { + let programs = vec![program( + "dolphin-emu;2503-1;x86_64;extra", + "Dolphin Emulator", + "/usr/bin/dolphin-emu", + "/usr/share/applications/dolphin-emu.desktop", + )]; + let by_desktop = suggestions( + &programs, + &RuntimeHints { + executable_names: Vec::new(), + desktop_ids: vec!["dolphin-emu".into()], + }, + ); + assert_eq!(by_desktop.len(), 1); + assert!( + suggestions( + &[], + &RuntimeHints { + executable_names: vec!["dolphin-emu".into()], + desktop_ids: Vec::new(), + } + ) + .is_empty() + ); + assert!(suggestions(&programs, &RuntimeHints::default()).is_empty()); + } + + #[test] + fn only_official_packagekit_entries_become_inventory() { + let entry = |provider: &str, executable: &str| gamenode_core::library::StoredEntry { + key: format!("{provider}:dolphin"), + provider: provider.into(), + store_id: "dolphin".into(), + name: Some("Dolphin Emulator".into()), + install_dir: "/usr/bin".into(), + fields: BTreeMap::from([ + ("executable".into(), executable.into()), + ( + "desktop_file".into(), + "/usr/share/applications/dolphin.desktop".into(), + ), + ("package_id".into(), "dolphin;1;x86_64;extra".into()), + ("package_manager".into(), "pacman".into()), + ]), + installed: true, + target: None, + owned: false, + shared: false, + first_seen: 0, + last_seen: 0, + }; + let inventory = installed_programs_from_entries(&[ + entry("packagekit", "/usr/bin/dolphin-emu"), + entry("third-party", "/tmp/malicious"), + ]); + assert_eq!(inventory.len(), 1); + assert_eq!(inventory[0].executable, "/usr/bin/dolphin-emu"); + assert_eq!(inventory[0].package_manager, "pacman"); + } + + #[cfg(unix)] + #[test] + fn approval_rejects_directories_links_and_non_executables() { + use std::os::unix::fs::PermissionsExt; + + let temp = tempfile::tempdir().unwrap(); + let directory = temp.path().join("folder"); + std::fs::create_dir(&directory).unwrap(); + assert!(inspect_executable(&directory, &Reserved::default()).is_err()); + + let plain = temp.path().join("plain"); + std::fs::write(&plain, b"data").unwrap(); + std::fs::set_permissions(&plain, std::fs::Permissions::from_mode(0o644)).unwrap(); + assert!(inspect_executable(&plain, &Reserved::default()).is_err()); + + let executable = temp.path().join("emulator"); + std::fs::write(&executable, b"data").unwrap(); + std::fs::set_permissions(&executable, std::fs::Permissions::from_mode(0o755)).unwrap(); + assert!(inspect_executable(&executable, &Reserved::default()).is_ok()); + + let link = temp.path().join("emulator-link"); + std::os::unix::fs::symlink(&executable, &link).unwrap(); + assert_eq!( + inspect_executable(&link, &Reserved::default()) + .unwrap_err() + .code(), + tonic::Code::PermissionDenied + ); + + let reserved = Reserved::new(std::slice::from_ref(&executable)); + assert!(inspect_executable(&executable, &reserved).is_err()); + } + + #[test] + fn hints_reject_paths_and_controls() { + assert!( + !RuntimeHints { + executable_names: vec!["/usr/bin/dolphin-emu".into()], + desktop_ids: Vec::new(), + } + .validate() + ); + assert!( + !RuntimeHints { + executable_names: vec!["dolphin\u{0}emu".into()], + desktop_ids: Vec::new(), + } + .validate() + ); + assert!( + RuntimeHints { + executable_names: vec!["dolphin-emu".into()], + desktop_ids: vec!["dolphin-emu.desktop".into()], + } + .validate() + ); + } +} diff --git a/crates/app/src/plugin_host/runtime_approvals.rs b/crates/app/src/plugin_host/runtime_approvals.rs new file mode 100644 index 000000000..e52209416 --- /dev/null +++ b/crates/app/src/plugin_host/runtime_approvals.rs @@ -0,0 +1,232 @@ +//! Host-owned settings for approved runtime executables. +use std::sync::Arc; + +use serde::Serialize; + +use super::profile::PluginProfiles; +use super::storage::PluginStorage; + +/// One active runtime executable approval as the settings list shows it. The volume and node +/// identity and the digest stay in the host. +#[derive(Clone, Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PluginRuntimeApproval { + /// The owned runtime this approval belongs to. + pub runtime_id: String, + /// The canonical executable location the user approved. + pub path: String, + /// Unix seconds. + pub approved_at: i64, +} + +/// Reads and revokes runtime executable approvals for one plugin in the active account profile. +pub struct PluginRuntimeApprovals { + storage: Arc, + profiles: Arc, +} + +impl PluginRuntimeApprovals { + pub fn new(storage: Arc, profiles: Arc) -> Self { + Self { storage, profiles } + } + + fn identity( + &self, + plugin_id: &str, + publisher: &str, + ) -> Result { + self.profiles + .resolver(plugin_id, publisher, None) + .map_err(|error| error.message().to_owned()) + } + + /// Lists the active approvals of this plugin, publisher and account profile. A revoked + /// approval is never shown; the next Play asks for a fresh program instead. + pub async fn list( + &self, + plugin_id: &str, + publisher: &str, + ) -> Result, String> { + let resolver = self.identity(plugin_id, publisher)?; + let epoch = self.profiles.epoch(); + let approvals = self + .storage + .run_for_host(&resolver, epoch, |namespace| namespace.runtime_approvals()) + .await + .map_err(|error| error.message().to_owned())?; + Ok(approvals + .into_iter() + .filter(|approval| approval.revoked_at.is_none()) + .map(|approval| PluginRuntimeApproval { + runtime_id: approval.runtime_id, + path: approval.path, + approved_at: approval.approved_at, + }) + .collect()) + } + + /// Revokes one active approval of this plugin, publisher and account profile. A runtime + /// another identity owns is never touched. Returns whether this call revoked it. + pub async fn revoke( + &self, + plugin_id: &str, + publisher: &str, + runtime_id: &str, + ) -> Result { + let resolver = self.identity(plugin_id, publisher)?; + let epoch = self.profiles.epoch(); + let runtime_id = runtime_id.to_owned(); + self.storage + .run_for_host(&resolver, epoch, move |namespace| { + let Some(approval) = namespace.runtime_approval_for(&runtime_id)? else { + return Ok(false); + }; + if approval.revoked_at.is_some() { + return Ok(false); + } + namespace.revoke_runtime_approval(&runtime_id) + }) + .await + .map_err(|error| error.message().to_owned()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::plugin_host::library::CommitGuard; + use crate::plugin_host::runtime_access::validate_approval; + use gamenode_platform::plugin_files::Reserved; + use gamenode_platform::plugin_storage::RuntimeApproval; + + fn approval(runtime_id: &str, path: &str, approved_at: i64) -> RuntimeApproval { + RuntimeApproval { + id: format!("{runtime_id}-approval"), + runtime_id: runtime_id.into(), + path: path.into(), + volume: 1, + node: 2, + size: 3, + digest: "ab".repeat(32), + approved_at, + revoked_at: None, + } + } + + async fn save( + storage: &PluginStorage, + profiles: &PluginProfiles, + plugin_id: &str, + publisher: &str, + approval: &RuntimeApproval, + ) { + let resolver = profiles.resolver(plugin_id, publisher, None).unwrap(); + let guard: CommitGuard = Box::new(|| Ok(())); + let approval = approval.clone(); + storage + .run_for_host(&resolver, profiles.epoch(), move |namespace| { + namespace.save_runtime_approval(&approval, &guard) + }) + .await + .unwrap(); + } + + #[tokio::test] + async fn lists_only_this_plugins_active_approvals_and_revokes_once() { + let temp = tempfile::tempdir().unwrap(); + let storage = Arc::new(PluginStorage::new(temp.path())); + let profiles = Arc::new(PluginProfiles::default()); + profiles.update(Some("account"), true); + let publisher = "ab".repeat(32); + let extension = "dev.richmont.gamenode.dolphin-emu-launch"; + + let active = approval("runtime-1", "/usr/bin/dolphin-emu", 100); + let mut revoked = approval("runtime-2", "/usr/bin/old-dolphin", 50); + save(&storage, &profiles, extension, &publisher, &active).await; + revoked.revoked_at = Some(200); + save(&storage, &profiles, extension, &publisher, &revoked).await; + let resolver = profiles.resolver(extension, &publisher, None).unwrap(); + + let service = PluginRuntimeApprovals::new(storage.clone(), profiles.clone()); + let listed = service.list(extension, &publisher).await.unwrap(); + assert_eq!(listed.len(), 1); + assert_eq!(listed[0].runtime_id, "runtime-1"); + assert_eq!(listed[0].path, "/usr/bin/dolphin-emu"); + assert_eq!(listed[0].approved_at, 100); + + // Another plugin, publisher or profile sees nothing of this namespace. + assert!( + service + .list("dev.richmont.gamenode.dolphin-emu", &publisher) + .await + .unwrap() + .is_empty() + ); + assert!( + service + .list(extension, &"cd".repeat(32)) + .await + .unwrap() + .is_empty() + ); + assert!( + !service + .revoke(extension, &"cd".repeat(32), "runtime-1") + .await + .unwrap() + ); + assert!( + !service + .revoke("dev.richmont.gamenode.dolphin-emu", &publisher, "runtime-1") + .await + .unwrap() + ); + + assert!( + service + .revoke(extension, &publisher, "runtime-1") + .await + .unwrap() + ); + assert!( + !service + .revoke(extension, &publisher, "runtime-1") + .await + .unwrap() + ); + assert!( + service + .list(extension, &publisher) + .await + .unwrap() + .is_empty() + ); + + // The runtime record no longer launches through the revoked approval. + let stored = storage + .run_for_host(&resolver, profiles.epoch(), |namespace| { + namespace.runtime_approval_for("runtime-1") + }) + .await + .unwrap() + .unwrap(); + assert!(stored.revoked_at.is_some()); + assert!(validate_approval(&stored, &Reserved::default()).is_err()); + + // A profile switch moves the service to the new profile's empty namespace. + profiles.update(Some("other-account"), true); + assert!( + service + .list(extension, &publisher) + .await + .unwrap() + .is_empty() + ); + assert!( + !service + .revoke(extension, &publisher, "runtime-1") + .await + .unwrap() + ); + } +} diff --git a/crates/app/src/plugin_host/saves.rs b/crates/app/src/plugin_host/saves.rs new file mode 100644 index 000000000..6432f12e0 --- /dev/null +++ b/crates/app/src/plugin_host/saves.rs @@ -0,0 +1,372 @@ +//! Save profiles contributed by plugins (task 13.1, design section 12). +//! +//! A save profile says where one runtime keeps a game's saves: a name, one to eight folders, rules +//! that narrow what counts as a save inside each folder, and an optional runtime and format. It +//! belongs to the plugin that made it and lives in that plugin's own store for the active account +//! profile, beside the folder approvals it points to. +//! +//! A profile is *configuration*. It carries no path and grants no access: each folder is a folder +//! the user already approved for the same plugin and installation (task 6.2), named by the +//! approval's id; the rules only narrow inside it, so a profile can never reach further than the +//! approvals do, and revoking an approval deactivates the folders that rest on it. Reading, +//! backing up and restoring stay separate operations with their own permissions. +//! +//! This module holds what needs no I/O: the bounds, the checks of what a plugin sends, how a +//! profile is stored, and the provisional port through which another plugin's profile can be +//! granted. The service is in `resources/saves.rs`. + +use std::sync::{Arc, Mutex}; + +use gamenode_plugin_protocol::prost_types::{self, Struct, Value, value::Kind}; +use serde::{Deserialize, Serialize}; +use serde_json::Value as Json; +use tonic::Status; + +use super::notifications::is_plain_line; + +/// Profiles one plugin may keep for one installation. +pub const MAX_PROFILES_PER_INSTALLATION: usize = 16; +/// Profiles one plugin may keep in all. +pub const MAX_PROFILES_PER_PLUGIN: usize = 256; +/// Folders in one profile. +pub const MAX_DIRECTORIES: usize = 8; +/// Rules for one folder. +pub const MAX_PATTERNS: usize = 16; +/// The longest rule, in bytes. +pub const MAX_PATTERN_BYTES: usize = 256; +/// The longest profile or folder name, in bytes. +pub const MAX_NAME_BYTES: usize = 120; +/// The longest runtime or format id, in bytes. +pub const MAX_ID_BYTES: usize = 128; +/// The most descriptive metadata, as JSON. +pub const MAX_METADATA_BYTES: usize = 8 * 1024; +/// How deep descriptive metadata may nest. +pub const MAX_METADATA_DEPTH: usize = 4; +/// How many keys and list items descriptive metadata may hold in all. +pub const MAX_METADATA_ITEMS: usize = 64; + +/// What a foreign profile grant allows. +pub mod access { + pub const READ: u8 = 1; + pub const UPDATE: u8 = 2; + pub const DELETE: u8 = 4; +} + +fn refuse(message: impl Into) -> Status { + Status::invalid_argument(message.into()) +} + +/// A folder of a profile as stored: the approval it rests on and the directory below its root. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Directory { + pub approval_id: String, + /// Plain names below the approval's root; empty means the root itself. + pub path: Vec, + pub display_name: String, + pub naming_patterns: Vec, +} + +pub fn directories_json(directories: &[Directory]) -> String { + serde_json::to_string(directories).unwrap_or_else(|_| "[]".into()) +} + +pub fn directories_from_json(text: &str) -> Vec { + serde_json::from_str(text).unwrap_or_default() +} + +/// A profile or folder name: trimmed, one line of plain text, 1 to 120 bytes. +pub fn check_name(label: &str, text: &str) -> Result { + let text = text.trim(); + if text.is_empty() || text.len() > MAX_NAME_BYTES || !is_plain_line(text) { + return Err(refuse(format!( + "{label} is required: one line of plain text, at most {MAX_NAME_BYTES} bytes" + ))); + } + Ok(text.to_owned()) +} + +/// A folder's display name, which may be empty. +pub fn check_display_name(text: &str) -> Result { + if text.trim().is_empty() { + return Ok(String::new()); + } + check_name("display_name", text) +} + +/// A runtime or format id: letters, digits, `.`, `_` and `-`, at most 128 bytes, or empty. +pub fn check_identifier(label: &str, text: &str) -> Result { + if text.len() > MAX_ID_BYTES + || !text + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b"._-".contains(&b)) + { + return Err(refuse(format!( + "{label} may hold letters, digits, '.', '_' and '-', at most {MAX_ID_BYTES} bytes" + ))); + } + Ok(text.to_owned()) +} + +/// A naming rule: a relative glob inside the folder, `/`-separated, `*` and `?` inside a name and +/// `**` as a whole name for any depth. A leading `!` makes it an exclusion. +pub fn check_pattern(text: &str) -> Result { + let bad = || { + refuse(format!( + "a naming pattern is a relative path of at most {MAX_PATTERN_BYTES} bytes, optionally \ + starting with '!' to exclude, with '*', '?' and '**' as the only wildcards" + )) + }; + if text.len() > MAX_PATTERN_BYTES { + return Err(bad()); + } + let body = text.strip_prefix('!').unwrap_or(text); + if body.is_empty() || body.starts_with('/') || body.ends_with('/') { + return Err(bad()); + } + for name in body.split('/') { + let forbidden = |c: char| c.is_control() || matches!(c, '\\' | ':' | '[' | ']' | '{' | '}'); + if name.is_empty() + || name == "." + || name == ".." + || name.chars().any(forbidden) + || (name.contains("**") && name != "**") + { + return Err(bad()); + } + } + Ok(text.to_owned()) +} + +fn segment_matches(pattern: &[char], name: &[char]) -> bool { + match pattern.split_first() { + None => name.is_empty(), + Some(('*', rest)) => (0..=name.len()).any(|skip| segment_matches(rest, &name[skip..])), + Some(('?', rest)) => !name.is_empty() && segment_matches(rest, &name[1..]), + Some((c, rest)) => name.first() == Some(c) && segment_matches(rest, &name[1..]), + } +} + +fn path_matches(pattern: &[&str], path: &[String]) -> bool { + match pattern.split_first() { + None => path.is_empty(), + Some((&"**", rest)) => (0..=path.len()).any(|skip| path_matches(rest, &path[skip..])), + Some((segment, rest)) => path.split_first().is_some_and(|(name, below)| { + let (segment, name): (Vec, Vec) = + (segment.chars().collect(), name.chars().collect()); + segment_matches(&segment, &name) && path_matches(rest, below) + }), + } +} + +/// Whether the file at `relative` (below the profile's folder) is one the folder's rules select. +/// A rule matches the whole relative path, from the folder, so `*.sav` means the files of the +/// folder itself and `**/*.sav` those at any depth. With no inclusion rule everything is +/// selected; an exclusion (`!rule`) always wins. +pub fn selected(patterns: &[String], relative: &[String]) -> bool { + let matches = |pattern: &str| { + let segments: Vec<&str> = pattern.split('/').collect(); + path_matches(&segments, relative) + }; + let mut included = patterns.iter().all(|p| p.starts_with('!')); + for pattern in patterns { + match pattern.strip_prefix('!') { + Some(exclusion) if matches(exclusion) => return false, + Some(_) => {} + None => included |= matches(pattern), + } + } + included +} + +/// Checks the rules of one folder. +pub fn check_patterns(patterns: &[String]) -> Result, Status> { + if patterns.len() > MAX_PATTERNS { + return Err(refuse(format!( + "a folder takes at most {MAX_PATTERNS} naming patterns" + ))); + } + let mut seen = std::collections::HashSet::new(); + patterns + .iter() + .map(|pattern| { + let pattern = check_pattern(pattern)?; + seen.insert(pattern.clone()) + .then_some(pattern) + .ok_or_else(|| refuse("a naming pattern is listed twice")) + }) + .collect() +} + +fn json_of(value: &Value, depth: usize, items: &mut usize) -> Result { + let too_deep = || refuse("descriptive metadata nests too deeply"); + if depth > MAX_METADATA_DEPTH { + return Err(too_deep()); + } + Ok(match value.kind.as_ref() { + None | Some(Kind::NullValue(_)) => Json::Null, + Some(Kind::BoolValue(flag)) => Json::Bool(*flag), + Some(Kind::StringValue(text)) => { + if text.chars().any(char::is_control) { + return Err(refuse("descriptive metadata holds a control character")); + } + Json::String(text.clone()) + } + Some(Kind::NumberValue(number)) => serde_json::Number::from_f64(*number) + .map(Json::Number) + .ok_or_else(|| refuse("descriptive metadata holds a number that is not finite"))?, + Some(Kind::StructValue(inner)) => Json::Object(object_of(inner, depth + 1, items)?), + Some(Kind::ListValue(list)) => Json::Array( + list.values + .iter() + .map(|value| { + *items += 1; + if *items > MAX_METADATA_ITEMS { + return Err(refuse("descriptive metadata holds too many items")); + } + json_of(value, depth + 1, items) + }) + .collect::>()?, + ), + }) +} + +fn object_of( + object: &Struct, + depth: usize, + items: &mut usize, +) -> Result, Status> { + let mut map = serde_json::Map::new(); + for (key, value) in &object.fields { + *items += 1; + if *items > MAX_METADATA_ITEMS { + return Err(refuse("descriptive metadata holds too many items")); + } + if key.is_empty() || key.len() > MAX_ID_BYTES || key.chars().any(char::is_control) { + return Err(refuse( + "a descriptive metadata key is 1 to 128 bytes of plain text", + )); + } + map.insert(key.clone(), json_of(value, depth, items)?); + } + Ok(map) +} + +/// Checks descriptive metadata (bounded depth, items and size) and returns it as stored JSON. +/// Structural validation of extension schemas is task 12.6; until then these bounds apply. +pub fn check_metadata(metadata: Option<&Struct>) -> Result { + let Some(metadata) = metadata else { + return Ok("{}".into()); + }; + let mut items = 0; + let object = object_of(metadata, 1, &mut items)?; + let text = serde_json::to_string(&Json::Object(object)).unwrap_or_else(|_| "{}".into()); + if text.len() > MAX_METADATA_BYTES { + return Err(refuse(format!( + "descriptive metadata is larger than {MAX_METADATA_BYTES} bytes" + ))); + } + Ok(text) +} + +fn value_of(json: &Json) -> Value { + Value { + kind: Some(match json { + Json::Null => Kind::NullValue(0), + Json::Bool(flag) => Kind::BoolValue(*flag), + Json::Number(number) => Kind::NumberValue(number.as_f64().unwrap_or_default()), + Json::String(text) => Kind::StringValue(text.clone()), + Json::Array(list) => Kind::ListValue(prost_types::ListValue { + values: list.iter().map(value_of).collect(), + }), + Json::Object(map) => Kind::StructValue(struct_of(map)), + }), + } +} + +fn struct_of(map: &serde_json::Map) -> Struct { + Struct { + fields: map + .iter() + .map(|(key, value)| (key.clone(), value_of(value))) + .collect(), + } +} + +/// Descriptive metadata as it was stored, for a reply. +pub fn metadata_struct(text: &str) -> Option { + match serde_json::from_str::(text) { + Ok(Json::Object(map)) if !map.is_empty() => Some(struct_of(&map)), + _ => None, + } +} + +/// A new profile id. It is the host's: the request has no way to choose one. +pub fn new_profile_id() -> Result { + let mut bytes = [0_u8; 16]; + getrandom::fill(&mut bytes).map_err(|_| Status::internal("no source of randomness"))?; + Ok(format!( + "profile-{}", + bytes.iter().map(|b| format!("{b:02x}")).collect::() + )) +} + +/// Another plugin's profile that the user allowed this plugin to use, and how. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ForeignGrant { + pub creator_plugin_id: String, + pub creator_publisher: String, + pub profile_id: String, + /// A mix of [`access`] bits. + pub operations: u8, +} + +/// Where the grants for other plugins' profiles come from. **Provisional** (task 13.1): until the +/// shared data plane (section 12) and the permissions screen exist, the grants are whatever the +/// application connects here; with nothing connected no foreign profile can be reached. +pub trait ProfileGrants: Send + Sync { + /// The profiles of other plugins the user allowed `plugin_id` of `publisher` to use. + fn grants(&self, plugin_id: &str, publisher: &str) -> Vec; +} + +/// The profile grants the host holds. Shared by every plugin session. +#[derive(Default)] +pub struct SaveAccess { + grants: Mutex>>, +} + +impl SaveAccess { + /// Connects the source of foreign grants. Until it is set, a plugin reaches only its own + /// profiles. + pub fn set_grants(&self, grants: Arc) { + *self.grants.lock().unwrap_or_else(|p| p.into_inner()) = Some(grants); + } + + /// The grant that lets `plugin_id` of `publisher` do `operation` to the profile `profile_id` + /// of another plugin, if any. + pub fn grant_for( + &self, + plugin_id: &str, + publisher: &str, + profile_id: &str, + operation: u8, + ) -> Option { + let source = self + .grants + .lock() + .unwrap_or_else(|p| p.into_inner()) + .clone()?; + source + .grants(plugin_id, publisher) + .into_iter() + .find(|grant| { + grant.profile_id == profile_id + && grant.operations & operation == operation + // A plugin's own profiles are never reached through a foreign grant. + && !(grant.creator_plugin_id == plugin_id + && grant.creator_publisher == publisher) + }) + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/app/src/plugin_host/saves/tests.rs b/crates/app/src/plugin_host/saves/tests.rs new file mode 100644 index 000000000..4b6af454a --- /dev/null +++ b/crates/app/src/plugin_host/saves/tests.rs @@ -0,0 +1,322 @@ +//! What a plugin may put in a save profile (task 13.1), without a plugin session. The service is +//! tested over the real socket in `resources/tests/saves.rs`. + +use std::collections::BTreeMap; + +use super::*; + +fn string(text: &str) -> Value { + Value { + kind: Some(Kind::StringValue(text.into())), + } +} + +fn object(fields: &[(&str, Value)]) -> Value { + Value { + kind: Some(Kind::StructValue(Struct { + fields: fields + .iter() + .map(|(key, value)| ((*key).to_owned(), value.clone())) + .collect::>(), + })), + } +} + +#[test] +fn names_are_one_line_of_plain_text() { + assert_eq!( + check_name("name", " Dolphin card A ").unwrap(), + "Dolphin card A" + ); + for bad in [ + "", + " ", + "line\nbreak", + "bell\u{7}", + "evil\u{202E}gnp", + &"x".repeat(121), + ] { + assert_eq!( + check_name("name", bad).unwrap_err().code(), + tonic::Code::InvalidArgument, + "{bad:?}" + ); + } + assert_eq!(check_display_name(" ").unwrap(), ""); + assert!(check_display_name("a\nb").is_err()); +} + +#[test] +fn runtime_and_format_ids_are_plain_identifiers() { + assert_eq!( + check_identifier("runtime_id", "org.dolphin-emu_5").unwrap(), + "org.dolphin-emu_5" + ); + assert_eq!(check_identifier("format_id", "").unwrap(), ""); + for bad in ["has space", "slash/inside", "ünï", &"x".repeat(129)] { + assert!(check_identifier("runtime_id", bad).is_err(), "{bad:?}"); + } +} + +#[test] +fn a_naming_pattern_is_a_relative_glob_that_can_exclude() { + for good in [ + "*.sav", + "GC/USA/*.gci", + "**", + "saves/**/slot?.sav", + "!cache/**", + "!*.tmp", + "Mario Kart (USA).srm", + ] { + assert_eq!(check_pattern(good).unwrap(), good, "{good}"); + } + for bad in [ + "", + "!", + "/etc/passwd", + "C:/Users/x", + "..", + "a/../b", + "./a", + "a//b", + "a/", + "a\\b", + "a**b", + "[ab].sav", + "{a,b}.sav", + "tab\there", + &"x".repeat(257), + ] { + assert_eq!( + check_pattern(bad).unwrap_err().code(), + tonic::Code::InvalidArgument, + "{bad:?}" + ); + } +} + +#[test] +fn a_folder_takes_a_bounded_list_of_distinct_patterns() { + let many: Vec = (0..MAX_PATTERNS).map(|n| format!("*.s{n}")).collect(); + assert_eq!(check_patterns(&many).unwrap().len(), MAX_PATTERNS); + let too_many: Vec = (0..=MAX_PATTERNS).map(|n| format!("*.s{n}")).collect(); + assert!(check_patterns(&too_many).is_err()); + assert!(check_patterns(&["*.sav".into(), "*.sav".into()]).is_err()); + assert!(check_patterns(&[]).unwrap().is_empty()); +} + +#[test] +fn descriptive_metadata_is_bounded_and_round_trips() { + assert_eq!(check_metadata(None).unwrap(), "{}"); + let metadata = Struct { + fields: BTreeMap::from([ + ("region".to_owned(), string("USA")), + ( + "core".to_owned(), + object(&[ + ("name", string("dolphin")), + ( + "version", + Value { + kind: Some(Kind::NumberValue(5.0)), + }, + ), + ]), + ), + ]), + }; + let stored = check_metadata(Some(&metadata)).unwrap(); + assert_eq!(metadata_struct(&stored).unwrap(), metadata); + assert_eq!(metadata_struct("{}"), None); + assert_eq!(metadata_struct("not json"), None); + + // Too deep. + let mut nested = string("leaf"); + for _ in 0..MAX_METADATA_DEPTH + 1 { + nested = object(&[("k", nested)]); + } + let Some(Kind::StructValue(deep)) = nested.kind else { + unreachable!() + }; + assert!(check_metadata(Some(&deep)).is_err()); + // Too many items. + let wide = Struct { + fields: (0..=MAX_METADATA_ITEMS) + .map(|n| (format!("k{n}"), string("v"))) + .collect(), + }; + assert!(check_metadata(Some(&wide)).is_err()); + // Too large, a bad key, a control character, a number that is not finite. + let big = Struct { + fields: BTreeMap::from([("k".to_owned(), string(&"x".repeat(MAX_METADATA_BYTES)))]), + }; + assert!(check_metadata(Some(&big)).is_err()); + for fields in [ + BTreeMap::from([(String::new(), string("v"))]), + BTreeMap::from([("k".to_owned(), string("a\u{7}b"))]), + BTreeMap::from([( + "k".to_owned(), + Value { + kind: Some(Kind::NumberValue(f64::NAN)), + }, + )]), + ] { + assert!(check_metadata(Some(&Struct { fields })).is_err()); + } +} + +#[test] +fn directories_survive_storage_and_garbage_is_no_directories() { + let directories = vec![Directory { + approval_id: "a1".into(), + path: vec!["GC".into(), "USA".into()], + display_name: "Card A".into(), + naming_patterns: vec!["*.gci".into(), "!cache/**".into()], + }]; + assert_eq!( + directories_from_json(&directories_json(&directories)), + directories + ); + assert!(directories_from_json("garbage").is_empty()); +} + +struct Fixed(Vec); + +impl ProfileGrants for Fixed { + fn grants(&self, plugin_id: &str, publisher: &str) -> Vec { + assert_eq!((plugin_id, publisher), ("org.reader", "pub-r")); + self.0.clone() + } +} + +fn grant(profile: &str, operations: u8) -> ForeignGrant { + ForeignGrant { + creator_plugin_id: "org.maker".into(), + creator_publisher: "pub-m".into(), + profile_id: profile.into(), + operations, + } +} + +#[test] +fn a_foreign_grant_covers_one_profile_and_only_the_operations_given() { + let access = SaveAccess::default(); + // Nothing connected: nothing reachable. + assert!( + access + .grant_for("org.reader", "pub-r", "p1", access::READ) + .is_none() + ); + + access.set_grants(Arc::new(Fixed(vec![grant( + "p1", + access::READ | access::UPDATE, + )]))); + assert!( + access + .grant_for("org.reader", "pub-r", "p1", access::READ) + .is_some() + ); + assert!( + access + .grant_for("org.reader", "pub-r", "p1", access::UPDATE) + .is_some() + ); + assert!( + access + .grant_for("org.reader", "pub-r", "p1", access::DELETE) + .is_none() + ); + assert!( + access + .grant_for("org.reader", "pub-r", "p1", access::READ | access::DELETE) + .is_none() + ); + assert!( + access + .grant_for("org.reader", "pub-r", "p2", access::READ) + .is_none() + ); +} + +#[test] +fn a_grant_naming_the_plugin_itself_is_not_a_foreign_grant() { + struct Own; + impl ProfileGrants for Own { + fn grants(&self, plugin_id: &str, publisher: &str) -> Vec { + vec![ForeignGrant { + creator_plugin_id: plugin_id.into(), + creator_publisher: publisher.into(), + profile_id: "p1".into(), + operations: access::READ, + }] + } + } + let access = SaveAccess::default(); + access.set_grants(Arc::new(Own)); + assert!( + access + .grant_for("org.reader", "pub-r", "p1", access::READ) + .is_none() + ); +} + +#[test] +fn profile_ids_are_host_made_and_never_repeat() { + let first = new_profile_id().unwrap(); + assert!(first.starts_with("profile-") && first.len() == 40); + assert_ne!(first, new_profile_id().unwrap()); +} + +fn rel(path: &str) -> Vec { + path.split('/').map(str::to_owned).collect() +} + +#[test] +fn rules_match_the_whole_path_from_the_profile_folder() { + let only = |rules: &[&str], path: &str| { + selected( + &rules.iter().map(|r| (*r).to_owned()).collect::>(), + &rel(path), + ) + }; + // No rule selects everything. + assert!(only(&[], "anything/at/all.bin")); + // A rule is anchored: `*.sav` is the folder's own files, `**/*.sav` any depth. + assert!(only(&["*.sav"], "slot1.sav")); + assert!(!only(&["*.sav"], "states/slot1.sav")); + assert!(only(&["**/*.sav"], "slot1.sav")); + assert!(only(&["**/*.sav"], "a/b/c/slot1.sav")); + assert!(only(&["GC/**/*.gci"], "GC/USA/card.gci")); + assert!(only(&["GC/**/*.gci"], "GC/card.gci")); + assert!(!only(&["GC/**/*.gci"], "EU/card.gci")); + assert!(only(&["slot?.sav"], "slot1.sav")); + assert!(!only(&["slot?.sav"], "slot10.sav")); + assert!(only(&["Mario*"], "Mario Kart.srm")); + assert!(!only(&["Mario*"], "Luigi.srm")); + // Several inclusions are alternatives. + assert!(only(&["*.sav", "*.srm"], "x.srm")); + assert!(!only(&["*.sav", "*.srm"], "x.bin")); +} + +#[test] +fn an_exclusion_always_wins_and_alone_it_selects_everything_else() { + let only = |rules: &[&str], path: &str| { + selected( + &rules.iter().map(|r| (*r).to_owned()).collect::>(), + &rel(path), + ) + }; + assert!(!only(&["**", "!cache/**"], "cache/tmp.bin")); + assert!(only(&["**", "!cache/**"], "saves/a.sav")); + assert!(!only(&["!*.tmp"], "x.tmp")); + assert!(only(&["!*.tmp"], "x.sav")); + assert!( + only(&["!*.tmp"], "deep/x.tmp"), + "an exclusion is anchored too" + ); + // An exclusion beats an inclusion that also matches. + assert!(!only(&["*.sav", "!slot1.sav"], "slot1.sav")); + assert!(only(&["*.sav", "!slot1.sav"], "slot2.sav")); +} diff --git a/crates/app/src/plugin_host/services.rs b/crates/app/src/plugin_host/services.rs index 919d6cff9..a572180fc 100644 --- a/crates/app/src/plugin_host/services.rs +++ b/crates/app/src/plugin_host/services.rs @@ -4,6 +4,7 @@ use super::{ login::LoginBroker, + namespace::{NamespaceOwner, SecretSlot}, provider::{HostServices, Lease}, }; use gamenode_core::{ @@ -12,6 +13,7 @@ use gamenode_core::{ ports::{CredentialError, CredentialStore}, }; use gamenode_plugin_protocol::{login::LoginPolicy, models, proto::*}; +use serde::Deserialize; use std::sync::{Arc, Mutex}; use tonic::Status; @@ -43,7 +45,9 @@ struct Persistence { pub struct ProviderServices { context: ProviderContext, credentials: Option>, + external_credentials: Option>, accounts: Mutex>, + external_accounts: Option>, identity: Arc>>, login: Option>, login_policy: Option>, @@ -61,6 +65,112 @@ pub trait AccountPersistence: Send + Sync { fn clear(&self, provider: &str) -> Result<(), Status>; } +/// Blocking account persistence for a third-party provider. The owner is derived from the +/// authenticated plugin, publisher and profile on every request; implementations must use it as +/// part of their storage key and must not route these records through Core's official accounts. +pub trait ExternalAccountPersistence: Send + Sync { + fn load( + &self, + owner: &NamespaceOwner, + provider: &str, + ) -> Result, Status>; + fn save( + &self, + owner: &NamespaceOwner, + account: models::StoreAccount, + clear_ownership: bool, + ) -> Result<(), Status>; + fn clear(&self, owner: &NamespaceOwner, provider: &str) -> Result<(), Status>; +} + +/// Host-owned adapter that opens one already-resolved third-party credential slot. The service +/// invokes it only inside the blocking storage worker; plugin requests never choose a slot. +pub trait ExternalCredentialStoreFactory: Send + Sync { + fn open( + &self, + slot: gamenode_platform::credentials::CredentialSlot, + ) -> Arc; +} + +struct PlatformExternalCredentialStoreFactory(gamenode_platform::paths::DataPaths); + +impl ExternalCredentialStoreFactory for PlatformExternalCredentialStoreFactory { + fn open( + &self, + slot: gamenode_platform::credentials::CredentialSlot, + ) -> Arc { + gamenode_platform::credentials::open_store(&self.0, slot) + } +} + +/// Signed third-party login metadata. It deliberately names a host probe instead of carrying +/// JavaScript that would be evaluated inside the privileged login WebView. +#[derive(Clone, Debug, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ExternalLoginPolicy { + pub start_url: String, + #[serde(default)] + pub cookie_urls: Vec, + pub probe_origin: String, + pub title: String, + pub allowed_hosts: Vec, + #[serde(default)] + pub cookie_names: Vec, + pub probe_id: ExternalPageProbe, + pub width: u32, + pub height: u32, + pub timeout_seconds: u64, +} + +#[derive(Clone, Copy, Debug, Deserialize)] +pub enum ExternalPageProbe { + #[serde(rename = "oauth_authorization_code")] + OAuthAuthorizationCode, +} + +impl ExternalLoginPolicy { + fn into_host_policy(self) -> Result { + let probe_script = match self.probe_id { + ExternalPageProbe::OAuthAuthorizationCode => { + "(() => { const code = new URL(window.location.href).searchParams.get('code'); return code ? { authorization_code: code } : null; })()" + } + }; + let policy = LoginPolicy { + start_url: self.start_url, + cookie_urls: self.cookie_urls, + probe_origin: self.probe_origin, + title: self.title, + allowed_hosts: self.allowed_hosts, + cookie_names: self.cookie_names, + probe_script: probe_script.into(), + width: self.width, + height: self.height, + timeout_seconds: self.timeout_seconds, + }; + policy + .validate() + .map_err(|_| Status::failed_precondition("invalid external login policy"))?; + Ok(policy) + } +} + +fn external_credential_slot(slot: &SecretSlot) -> gamenode_platform::credentials::CredentialSlot { + use gamenode_platform::credentials::{CredentialAlias, CredentialSlot}; + + let suffix = slot + .key() + .iter() + .map(|byte| format!("{byte:02x}")) + .collect::(); + CredentialSlot::provider( + "third-party", + Some(CredentialAlias { + keyring_account: format!("third-party.{suffix}"), + private_file: format!("third-party-{suffix}.secret"), + }), + ) +} + pub struct LibraryAccounts(pub Arc); impl AccountPersistence for LibraryAccounts { fn load(&self, provider: &str) -> Result, Status> { @@ -197,7 +307,9 @@ impl ProviderServices { Ok(Self { context, credentials, + external_credentials: None, accounts: Mutex::new(Arc::new(LibraryAccounts(library))), + external_accounts: None, identity: Arc::new(Mutex::new(None)), login, login_policy: login_policy.map(Arc::new), @@ -208,6 +320,45 @@ impl ProviderServices { }) } + /// Compose services for a managed third-party provider. Its account adapter is separate from + /// Core's official account table, and each secret is opened from a host-derived namespace + /// slot inside the blocking storage worker. The login descriptor cannot supply probe code. + pub fn new_external( + context: ProviderContext, + paths: gamenode_platform::paths::DataPaths, + library: Arc, + accounts: Arc, + login: Option>, + login_policy: Option, + ) -> Result { + Self::new_external_with_credentials( + context, + Arc::new(PlatformExternalCredentialStoreFactory(paths)), + library, + accounts, + login, + login_policy, + ) + } + + /// Variant for a host-owned credential backend, also used by deterministic service fixtures. + pub fn new_external_with_credentials( + context: ProviderContext, + credentials: Arc, + library: Arc, + accounts: Arc, + login: Option>, + login_policy: Option, + ) -> Result { + let login_policy = login_policy + .map(ExternalLoginPolicy::into_host_policy) + .transpose()?; + let mut services = Self::new(context, None, library, login, login_policy)?; + services.external_credentials = Some(credentials); + services.external_accounts = Some(accounts); + Ok(services) + } + pub fn status(&self) -> Option { lock(&self.status).clone() } @@ -240,7 +391,7 @@ impl ProviderServices { fn scope(&self, lease: &Lease) -> Result<(), Status> { lease.check()?; if lease.context.provider_id != self.context.provider_id { - return Err(Status::permission_denied("provider service scope denied")); + return Err(lease.deny_scope()); } Ok(()) } @@ -272,27 +423,60 @@ impl HostServices for ProviderServices { .try_into() .map_err(|_| Status::invalid_argument("invalid account identity"))?; if validated.provider != provider { - return Err(Status::permission_denied("account scope denied")); + return Err( + lease.deny_scope_for(gamenode_plugin_protocol::capability::ACCOUNT_PUBLISH) + ); } } - let accounts = lock(&self.accounts).clone(); + let external_accounts = self.external_accounts.clone(); + let accounts = external_accounts + .is_none() + .then(|| lock(&self.accounts).clone()); + let external_owner = if external_accounts.is_some() { + Some( + lease + .namespace()? + .account_owner() + .map_err(|_| Status::failed_precondition("account namespace unavailable"))?, + ) + } else { + None + }; let identity = self.identity.clone(); let authority = lease.clone(); let persistence = self.persistence.clone(); let read = matches!(action, account_request::Action::Read(true)); lease .storage(move || { + let load = |provider: &str| match (&external_accounts, &external_owner, &accounts) { + (Some(store), Some(owner), _) => store.load(owner, provider), + (None, None, Some(store)) => store.load(provider), + _ => Err(Status::unavailable("account storage unavailable")), + }; + let save = |account, clear_ownership| match ( + &external_accounts, + &external_owner, + &accounts, + ) { + (Some(store), Some(owner), _) => store.save(owner, account, clear_ownership), + (None, None, Some(store)) => store.save(account, clear_ownership), + _ => Err(Status::unavailable("account storage unavailable")), + }; + let clear = |provider: &str| match (&external_accounts, &external_owner, &accounts) + { + (Some(store), Some(owner), _) => store.clear(owner, provider), + (None, None, Some(store)) => store.clear(provider), + _ => Err(Status::unavailable("account storage unavailable")), + }; let mut reply = AccountReply { account: None, accepted: true, }; let result = match action { - account_request::Action::Read(true) => { - accounts.load(&provider).map(|account| { - *lock(&identity) = account.as_ref().map(|a| a.account_id.clone()); - reply.account = account.map(Into::into); - }) - } + account_request::Action::Read(true) => load(&provider).map(|account| { + *lock(&identity) = account.as_ref().map(|a| a.account_id.clone()); + reply.account = account.map(Into::into); + }), account_request::Action::Save(account) => { // A plugin may save before it ever reads, so an empty // cache cannot be treated as "no previous account": @@ -300,8 +484,7 @@ impl HostServices for ProviderServices { // source for deciding whether identity changed. let known = match lock(&identity).clone() { Some(id) => Ok(Some(id)), - None => accounts - .load(&provider) + None => load(&provider) .map(|account| account.map(|account| account.account_id)), }; match known { @@ -310,7 +493,7 @@ impl HostServices for ProviderServices { known.as_ref().is_some_and(|id| id != &account.account_id); authority.accept_identity(changed)?; *lock(&identity) = Some(account.account_id.clone()); - accounts.save( + save( account.try_into().map_err(|_| { Status::invalid_argument("invalid account identity") })?, @@ -321,7 +504,7 @@ impl HostServices for ProviderServices { } } account_request::Action::Clear(true) => { - let result = accounts.clear(&provider); + let result = clear(&provider); if result.is_ok() { *lock(&identity) = None; } @@ -338,17 +521,15 @@ impl HostServices for ProviderServices { async fn secret(&self, lease: Lease, request: SecretRequest) -> Result { self.scope(&lease)?; - if request.key != "session" { - return Err(Status::permission_denied("secret scope denied")); - } let operation = SecretOperation::try_from(request.operation) .map_err(|_| Status::invalid_argument("invalid secret operation"))?; - lease.require(match operation { + let permission = match operation { SecretOperation::Read => gamenode_plugin_protocol::capability::SECRET_READ, SecretOperation::Write => gamenode_plugin_protocol::capability::SECRET_WRITE, SecretOperation::Delete => gamenode_plugin_protocol::capability::SECRET_DELETE, _ => return Err(Status::invalid_argument("invalid secret operation")), - })?; + }; + lease.require(permission)?; let value = request .value .map(|value| { @@ -366,14 +547,35 @@ impl HostServices for ProviderServices { { return Err(Status::invalid_argument("invalid secret operation")); } - let store = self - .credentials - .clone() - .ok_or_else(|| Status::unavailable("secret storage unavailable"))?; + let store = self.credentials.clone(); + let external_factory = self.external_credentials.clone(); + let external_slot = if external_factory.is_some() { + Some( + lease + .namespace()? + .secret_slot(&request.key) + .map_err(|_| Status::invalid_argument("invalid logical secret key"))?, + ) + } else { + if request.key != "session" { + return Err(lease.deny_scope_for(permission)); + } + None + }; + if store.is_none() && external_factory.is_none() { + return Err(Status::unavailable("secret storage unavailable")); + } let persistence = self.persistence.clone(); let authority = lease.clone(); lease .storage(move || { + let store = match (store, external_factory, external_slot) { + (Some(store), None, None) => store, + (None, Some(factory), Some(slot)) => { + factory.open(external_credential_slot(&slot)) + } + _ => return Err(Status::unavailable("secret storage unavailable")), + }; use secret_reply::Outcome; let outcome = match operation { SecretOperation::Read => store.load().map(|value| { @@ -408,6 +610,11 @@ impl HostServices for ProviderServices { async fn login(&self, lease: Lease, request: LoginRequest) -> Result { self.scope(&lease)?; + if self.external_credentials.is_some() { + // Do not allow a trusted descriptor service to be attached to an official or + // unauthenticated registration by accident. + lease.namespace()?; + } let broker = self .login .as_ref() @@ -435,7 +642,7 @@ impl HostServices for ProviderServices { .as_ref() .is_some_and(|uri| Some(uri) != self.actions.install_uri.as_ref()) { - return Err(Status::permission_denied("provider action scope denied")); + return Err(lease.deny_scope()); } Ok(ActionReply { accepted: true }) } diff --git a/crates/app/src/plugin_host/services/tests.rs b/crates/app/src/plugin_host/services/tests.rs index 00b04314d..cdc2f11f2 100644 --- a/crates/app/src/plugin_host/services/tests.rs +++ b/crates/app/src/plugin_host/services/tests.rs @@ -6,8 +6,85 @@ use crate::plugin_host::{ use gamenode_platform::db::SqliteSettingsStore; use gamenode_plugin_protocol::capability as cap; use gamenode_plugin_sdk::{HostClient, Launch, Session}; +use std::collections::BTreeMap; use std::sync::atomic::{AtomicBool, Ordering}; +#[test] +fn external_secret_slots_are_namespace_bound_and_cannot_select_core_or_steam_aliases() { + use crate::plugin_host::{grants::PluginIdentity, namespace::ExternalNamespaceResolver}; + use gamenode_platform::credentials::{CredentialAlias, CredentialSlot}; + + let resolver = |plugin: &str, publisher: &str, profile: &str| { + ExternalNamespaceResolver::new( + PluginIdentity { + plugin_id: plugin.into(), + publisher_fingerprint: publisher.into(), + profile_id: profile.into(), + }, + Some("provider.example".into()), + 1, + ) + .unwrap() + }; + let slot = resolver("org.example.plugin", "publisher-a", "account-a") + .secret_slot("session") + .unwrap(); + let alias = external_credential_slot(&slot); + let other_plugin = external_credential_slot( + &resolver("org.example.other", "publisher-a", "account-a") + .secret_slot("session") + .unwrap(), + ); + let other_profile = external_credential_slot( + &resolver("org.example.plugin", "publisher-a", "account-b") + .secret_slot("session") + .unwrap(), + ); + let core = CredentialSlot::Session; + let steam = CredentialSlot::provider( + "steam", + Some(CredentialAlias { + keyring_account: "steam".into(), + private_file: "steam-token".into(), + }), + ); + + assert_ne!(alias, other_plugin); + assert_ne!(alias, other_profile); + assert_ne!(alias.keyring_account(), core.keyring_account()); + assert_ne!(alias.keyring_account(), steam.keyring_account()); + assert_ne!( + alias.private_file(&gamenode_platform::paths::DataPaths::at("/unused")), + steam.private_file(&gamenode_platform::paths::DataPaths::at("/unused")) + ); +} + +#[test] +fn external_login_metadata_accepts_only_host_defined_probe_ids() { + let json = r#"{ + "start_url":"https://login.example.test/authorize", + "probe_origin":"https://login.example.test/", + "title":"Example sign in", + "allowed_hosts":["example.test"], + "probe_id":"oauth_authorization_code", + "width":640, + "height":720, + "timeout_seconds":300 + }"#; + let policy: ExternalLoginPolicy = serde_json::from_str(json).unwrap(); + let host_policy = policy.into_host_policy().unwrap(); + assert!(host_policy.probe_script.contains("authorization_code")); + assert!(!host_policy.probe_script.contains("example.test")); + + let with_script = json.replace( + "\"probe_id\":\"oauth_authorization_code\",", + "\"probe_id\":\"oauth_authorization_code\",\"probe_script\":\"alert(1)\",", + ); + assert!(serde_json::from_str::(&with_script).is_err()); + let unknown_probe = json.replace("oauth_authorization_code", "publisher_script"); + assert!(serde_json::from_str::(&unknown_probe).is_err()); +} + struct FakeCredentials { value: Mutex>, fail_read: AtomicBool, @@ -23,6 +100,12 @@ impl FakeCredentials { fail_delete: false.into(), }) } + + fn empty() -> Arc { + let store = Self::new(); + *lock(&store.value) = None; + store + } } impl CredentialStore for FakeCredentials { fn method(&self) -> StorageMethod { @@ -53,6 +136,56 @@ impl CredentialStore for FakeCredentials { } } +#[derive(Default)] +struct FakeExternalCredentialStores(Mutex>>); + +impl ExternalCredentialStoreFactory for FakeExternalCredentialStores { + fn open( + &self, + slot: gamenode_platform::credentials::CredentialSlot, + ) -> Arc { + let mut stores = lock(&self.0); + stores + .entry(slot.keyring_account().to_owned()) + .or_insert_with(FakeCredentials::empty) + .clone() + } +} + +#[derive(Default)] +struct FakeExternalAccounts(Mutex, String), models::StoreAccount>>); + +impl ExternalAccountPersistence for FakeExternalAccounts { + fn load( + &self, + owner: &crate::plugin_host::namespace::NamespaceOwner, + provider: &str, + ) -> Result, Status> { + Ok(lock(&self.0) + .get(&(owner.key().to_vec(), provider.to_owned())) + .cloned()) + } + + fn save( + &self, + owner: &crate::plugin_host::namespace::NamespaceOwner, + account: models::StoreAccount, + _clear_ownership: bool, + ) -> Result<(), Status> { + lock(&self.0).insert((owner.key().to_vec(), account.provider.clone()), account); + Ok(()) + } + + fn clear( + &self, + owner: &crate::plugin_host::namespace::NamespaceOwner, + provider: &str, + ) -> Result<(), Status> { + lock(&self.0).remove(&(owner.key().to_vec(), provider.to_owned())); + Ok(()) + } +} + struct Harness { api: ProviderApi, client: Session, @@ -95,10 +228,19 @@ impl Harness { let root = PluginApi::default(); let api = root.providers.clone(); api.register(Registration { + declared_developer: "Fixture developer".into(), + package_digest: Vec::new(), provider_id: "steam".into(), plugin_id: "fixture.steam".into(), + kind: crate::plugin_host::provider::RegistrationKind::Provider, + origin: crate::plugin_host::provider::RegistrationOrigin::Official, capabilities: cap::ALL.iter().map(|c| (*c).into()).collect(), shared_catalog: false, + playtime: crate::plugin_host::package::PlaytimeCapabilities { + identifies_gameplay: true, + identifies_pauses: true, + without_pause_detection: Default::default(), + }, services: services.clone(), }) .unwrap(); @@ -145,15 +287,125 @@ impl Harness { } } + async fn third_party( + plugin_id: &str, + account_id: &str, + credentials: Arc, + accounts: Arc, + ) -> Self { + let temp = tempfile::tempdir().unwrap(); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(temp.path(), std::fs::Permissions::from_mode(0o700)).unwrap(); + } + let library: Arc = Arc::new( + SqliteSettingsStore::open(&temp.path().join("library.db")) + .unwrap() + .library_store(), + ); + let services = Arc::new( + ProviderServices::new_external_with_credentials( + ProviderContext { + provider_id: "fixture-provider".into(), + platform: std::env::consts::OS.into(), + manifest_toml: "id = \"fixture-provider\"\nname = \"Fixture\"\nplatforms = [\"linux\"]\nsource = \"fixture\"\n[scan]\nnative = \"fixture\"\n".into(), + granted_capabilities: cap::ALL.iter().map(|capability| (*capability).into()).collect(), + ..Default::default() + }, + credentials, + library.clone(), + accounts, + None, + None, + ) + .unwrap(), + ); + let root = PluginApi::default(); + let api = root.providers.clone(); + api.profiles().update(Some(account_id), true); + api.register(Registration { + declared_developer: "Fixture developer".into(), + package_digest: Vec::new(), + provider_id: "fixture-provider".into(), + plugin_id: plugin_id.into(), + kind: crate::plugin_host::provider::RegistrationKind::Provider, + origin: crate::plugin_host::provider::RegistrationOrigin::ThirdParty { + publisher_fingerprint: "ab".repeat(32), + }, + capabilities: cap::ALL + .iter() + .map(|capability| (*capability).into()) + .collect(), + shared_catalog: false, + playtime: Default::default(), + services: services.clone(), + }) + .unwrap(); + let launch = api.begin_launch("fixture-provider").unwrap(); + let credential = launch + .credential + .as_bytes() + .as_chunks::<2>() + .0 + .iter() + .map(|chunk| u8::from_str_radix(std::str::from_utf8(chunk).unwrap(), 16).unwrap()) + .collect(); + #[cfg(target_os = "linux")] + let server = PluginApiServer::start( + &tokio::runtime::Handle::current(), + temp.path().join("plugins.sock"), + root, + ) + .unwrap(); + #[cfg(windows)] + let server = + PluginApiServer::start_windows(&tokio::runtime::Handle::current(), root).unwrap(); + let client = Session::open( + Launch { + endpoint: server.endpoint().to_owned(), + credential, + operation_id: "launch".into(), + }, + plugin_id, + "fixture-provider", + "1.0", + cap::ALL, + ) + .await + .unwrap(); + launch.ready.await.unwrap(); + Self { + api, + client, + services, + library, + _server: server, + _temp: temp, + } + } + async fn operation( &mut self, kind: ProviderOperation, ) -> ( HostClient, tokio::task::JoinHandle>, + ) { + self.operation_for("steam", kind).await + } + + async fn operation_for( + &mut self, + provider: &str, + kind: ProviderOperation, + ) -> ( + HostClient, + tokio::task::JoinHandle>, ) { let api = self.api.clone(); - let pending = tokio::spawn(async move { api.execute("steam", kind).await }); + let provider = provider.to_owned(); + let pending = tokio::spawn(async move { api.execute(&provider, kind).await }); loop { let command = self.client.commands.message().await.unwrap().unwrap(); if command.operation == ProviderOperation::Acknowledge as i32 { @@ -165,6 +417,101 @@ impl Harness { } } +#[tokio::test] +async fn third_party_account_and_secret_slots_persist_only_for_their_plugin_profile() { + let credentials = Arc::new(FakeExternalCredentialStores::default()); + let accounts = Arc::new(FakeExternalAccounts::default()); + let mut first = Harness::third_party( + "org.example.plugin", + "account-a", + credentials.clone(), + accounts.clone(), + ) + .await; + let (client, pending) = first + .operation_for("fixture-provider", ProviderOperation::Check) + .await; + client + .account_save(models::StoreAccount { + provider: "fixture-provider".into(), + account_id: "store-account".into(), + account_name: Some("Player".into()), + ..Default::default() + }) + .await + .unwrap(); + for (key, value) in [ + ("session", "external-session"), + ("refresh", "external-refresh"), + ] { + client + .secret( + SecretOperation::Write, + key, + Some(&models::SessionCredential::new(value).unwrap()), + ) + .await + .unwrap(); + } + client.finish(completed()).await.unwrap(); + pending.await.unwrap().unwrap(); + + let mut same_identity = Harness::third_party( + "org.example.plugin", + "account-a", + credentials.clone(), + accounts.clone(), + ) + .await; + let (client, pending) = same_identity + .operation_for("fixture-provider", ProviderOperation::Check) + .await; + assert_eq!( + client.account_load().await.unwrap().unwrap().account_id, + "store-account" + ); + for (key, expected) in [ + ("session", "external-session"), + ("refresh", "external-refresh"), + ] { + assert_eq!( + client + .secret(SecretOperation::Read, key, None) + .await + .unwrap() + .outcome, + Some(secret_reply::Outcome::Value(expected.as_bytes().to_vec())) + ); + } + client.finish(completed()).await.unwrap(); + pending.await.unwrap().unwrap(); + + for (plugin_id, profile_id) in [ + ("org.example.other", "account-a"), + ("org.example.plugin", "account-b"), + ] { + let mut foreign = + Harness::third_party(plugin_id, profile_id, credentials.clone(), accounts.clone()) + .await; + let (client, pending) = foreign + .operation_for("fixture-provider", ProviderOperation::Check) + .await; + assert_eq!(client.account_load().await.unwrap(), None); + for key in ["session", "refresh"] { + assert_eq!( + client + .secret(SecretOperation::Read, key, None) + .await + .unwrap() + .outcome, + Some(secret_reply::Outcome::Absent(true)) + ); + } + client.finish(completed()).await.unwrap(); + pending.await.unwrap().unwrap(); + } +} + fn completed() -> OperationResult { OperationResult { disposition: OperationDisposition::Completed as i32, diff --git a/crates/app/src/plugin_host/shared_data.rs b/crates/app/src/plugin_host/shared_data.rs new file mode 100644 index 000000000..37ac6a523 --- /dev/null +++ b/crates/app/src/plugin_host/shared_data.rs @@ -0,0 +1,2436 @@ +//! Shared-data query and subscription broker for domain and Data projections. +//! +//! This module is the authorization and projection boundary behind the single Data RPC API. The +//! caller must resolve [`PluginIdentity`] from the authenticated session before invoking it. +//! Record identity and provenance are host-owned; plugin payloads are either bounded dataset +//! fields or opaque bytes. The broker is wired into `ResourceHost` and shares its policy index +//! with domain projections. +//! +//! Session-retained rows live here; durable rows stay in the host's public pool. A read merges +//! both under the same owner/grant checks and field projections, in one stable receipt order, and +//! a durable publication advances the broker revision so lists and watches share a handoff. + +use super::grants::PluginIdentity; +use super::sharing_policy::{ + AccessDecision, AccessRequest, AccessScope, Authorizer, Delivery, SharingClass, +}; +use gamenode_plugin_protocol::proto::{CommonDataCategory, CommonDataSelector}; +use serde_json::{Map, Value}; +use std::collections::{BTreeSet, HashMap, HashSet, VecDeque}; +use std::sync::{Arc, Mutex, MutexGuard, Weak}; +use thiserror::Error; + +pub const MAX_RECORD_BYTES: usize = 1024 * 1024; +pub const MAX_RECORDS: usize = 16_384; +pub const MAX_RETAINED_BYTES: usize = 64 * 1024 * 1024; +pub const MAX_PAGE_SIZE: usize = 256; +pub const MAX_SUBSCRIPTION_QUEUE: usize = 128; +pub const MAX_TTL_SECONDS: u64 = 30 * 24 * 60 * 60; +pub const MAX_RESOURCE_ID_BYTES: usize = 256; +pub const MAX_OBSERVATION_ID_BYTES: usize = 256; +const MAX_FIELD_DEPTH: usize = 32; +const MAX_FIELD_ITEMS: usize = 4096; +const MAX_FIELD_KEY_BYTES: usize = 256; + +const RESERVED_FIELDS: &[&str] = &[ + "source", + "owner", + "owner_plugin_id", + "plugin_id", + "publisher", + "publisher_fingerprint", + "profile_id", + "provenance", + "record_id", + "dataset_id", + "schema_id", + "schema_version", + "revision", + "published_at", + "expires_at", + "creator", + "permissions", + "scope", + "executable", + "executable_handle", + "argv", + "cwd", + "path", + "launch_target", + "operation", + "command", + "grant", + "permission", +]; + +/// A host-resolved publication. `owner` must come from the authenticated producer session, and +/// callers must validate publication permission before calling [`DataBroker::publish`]. +#[derive(Clone, Debug)] +pub struct Publication { + pub owner: PluginIdentity, + pub dataset_id: String, + pub category: Option, + pub class: SharingClass, + pub schema_id: String, + pub schema_version: u32, + pub fields: Map, + /// Optional schema payload. A record carries either structured fields or opaque bytes. + pub opaque_payload: Vec, + /// Producer observation metadata. Sequence streams are scoped to the authenticated owner, + /// dataset and resource, never to plugin-supplied identity fields. + pub resource_id: String, + pub observed_at: i64, + pub sequence: u64, + pub source_observation_id: String, + /// Host session that owns this session-retained record; absent only for host-fed projections. + pub session_id: Option, + /// Identity details resolved from the signed package and active authenticated session. + pub publisher: Option, + pub expires_at: Option, +} + +#[derive(Clone, Debug, Default)] +pub struct PublisherMetadata { + pub declared_developer: String, + pub origin: String, + pub package_version: String, + pub package_digest: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct PublicationReceipt { + pub record_id: String, + pub revision: u64, + pub duplicate: bool, +} + +/// Snapshot of one record returned only to host code for mutation of its authenticated owner +/// resource. RPC readers must use the projected query APIs below. +#[derive(Clone, Debug)] +pub struct OwnedRecord { + pub fields: Map, + pub revision: u64, + pub sequence: u64, + pub source_observation_id: String, + pub observed_at: i64, +} + +/// Provenance is kept outside the plugin field map and only extended by the host. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Provenance { + pub source: PluginIdentity, + pub forwarded_by: Vec, + pub declared_developer: String, + pub origin: String, + pub package_version: String, + pub package_digest: Vec, + pub source_record_ids: Vec, +} + +#[derive(Clone, Debug)] +struct StoredRecord { + record_id: String, + owner: PluginIdentity, + dataset_id: String, + category: Option, + class: SharingClass, + schema_id: String, + schema_version: u32, + fields: Map, + opaque_payload: Vec, + resource_id: String, + observed_at: i64, + received_at: i64, + sequence: u64, + source_observation_id: String, + session_id: Option, + published_at: i64, + expires_at: Option, + revision: u64, + /// Broker revision at which this row entered the in-memory state, used only to fence live + /// subscriptions. A durable row gets the revision of its dispatch, not of its first insert. + position: u64, + /// Host-owned durable pool row rather than a session-retained record. + durable: bool, + provenance: Provenance, + bytes: usize, +} + +/// A durable pool record loaded by the storage worker, ready for the same authorization and +/// projection path as a session record. Only host code builds one; a plugin RPC never does. +#[derive(Clone, Debug)] +pub(crate) struct DurableRecord { + pub record_id: String, + pub owner: PluginIdentity, + pub dataset_id: String, + pub category: Option, + pub class: SharingClass, + pub schema_id: String, + pub schema_version: u32, + pub fields: Map, + pub opaque_payload: Vec, + pub resource_id: String, + pub observed_at: i64, + pub received_at: i64, + pub published_at: i64, + pub sequence: u64, + pub source_observation_id: String, + pub expires_at: Option, + pub revision: u64, + /// Persisted pool sequence of the write that produced this row. The broker uses it as the + /// floor for its own revision so a publication accepted before the first read still lands + /// above a sequence persisted by an earlier host run. + pub pool_revision: u64, + pub provenance: Provenance, +} + +impl From for StoredRecord { + fn from(record: DurableRecord) -> Self { + Self { + record_id: record.record_id, + owner: record.owner, + dataset_id: record.dataset_id, + category: record.category, + class: record.class, + schema_id: record.schema_id, + schema_version: record.schema_version, + fields: record.fields, + opaque_payload: record.opaque_payload, + resource_id: record.resource_id, + observed_at: record.observed_at, + received_at: record.received_at, + sequence: record.sequence, + source_observation_id: record.source_observation_id, + session_id: None, + published_at: record.published_at, + expires_at: record.expires_at, + revision: record.revision, + position: 0, + durable: true, + provenance: record.provenance, + bytes: 0, + } + } +} + +/// A projected result. Its fields and provenance are private so an RPC adapter cannot accept a +/// plugin-constructed projection as an onward-publication proof. +#[derive(Clone, Debug, PartialEq)] +pub struct ProjectedRecord { + record_id: String, + dataset_id: String, + category: Option, + schema_id: String, + schema_version: u32, + fields: Map, + opaque_payload: Vec, + resource_id: String, + observed_at: i64, + received_at: i64, + sequence: u64, + source_observation_id: String, + published_at: i64, + revision: u64, + expires_at: Option, + provenance: Provenance, + recipient: PluginIdentity, + policy_revision: u64, + durable: bool, +} + +/// Host-only sharing metadata for settings review. This intentionally contains no payload values. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct SharedDataCatalogRecord { + pub owner: PluginIdentity, + pub record_id: String, + pub dataset_id: String, + pub class: SharingClass, + pub category: Option, + pub fields: BTreeSet, +} + +impl ProjectedRecord { + pub fn record_id(&self) -> &str { + &self.record_id + } + + pub fn dataset_id(&self) -> &str { + &self.dataset_id + } + + pub fn category(&self) -> Option { + self.category + } + + pub fn schema(&self) -> (&str, u32) { + (&self.schema_id, self.schema_version) + } + + pub fn fields(&self) -> &Map { + &self.fields + } + + pub fn revision(&self) -> u64 { + self.revision + } + + pub fn published_at(&self) -> i64 { + self.published_at + } + + pub fn provenance(&self) -> &Provenance { + &self.provenance + } + + pub fn opaque_payload(&self) -> &[u8] { + &self.opaque_payload + } + + pub fn resource_id(&self) -> &str { + &self.resource_id + } + + pub fn observed_at(&self) -> i64 { + self.observed_at + } + + pub fn received_at(&self) -> i64 { + self.received_at + } + + pub fn expires_at(&self) -> Option { + self.expires_at + } + + pub fn sequence(&self) -> u64 { + self.sequence + } + + pub fn source_observation_id(&self) -> &str { + &self.source_observation_id + } + + /// True when this projection came from the host-owned durable pool rather than the + /// session-retained broker. + pub fn is_durable(&self) -> bool { + self.durable + } +} + +#[derive(Clone, Debug, PartialEq)] +pub struct QueryResult { + pub records: Vec, + pub next_cursor: Option, + /// Broker-wide revision used to bind the next page and a subsequent watch. A durable + /// publication in this process advances it too, so both sources share one handoff revision. + pub revision: u64, +} + +/// Opaque in-process cursor bound to caller, query, data snapshot, and current policy revision. +/// A protocol adapter must encode it as a host-authenticated token before crossing RPC. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct QueryCursor { + caller: PluginIdentity, + dataset_id: String, + record_id: Option, + category: Option, + selector: QuerySelector, + delivery: Delivery, + snapshot_revision: u64, + /// Position of the last returned record in the merged order: `(received_at, record_id)`. + /// `None` starts a fresh page. The merged order is shared by session and durable rows. + after_received_at: i64, + after_record_id: Option, + policy_revision: u64, +} + +#[derive(Clone, Debug)] +pub struct QueryRequest { + pub caller: PluginIdentity, + pub dataset_id: String, + /// Optional exact record lookup. Used by Data.Get so owner reads select one record too. + pub record_id: Option, + pub category: Option, + /// `None` and an empty selector both mean owner-private records only. + pub selector: Option, + pub delivery: Delivery, + pub page_size: usize, + pub cursor: Option, +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +struct QuerySelector { + categories: BTreeSet, + record_ids: BTreeSet, +} + +impl QuerySelector { + fn decode(selector: Option<&CommonDataSelector>) -> Result { + let Some(selector) = selector else { + return Ok(Self::default()); + }; + if selector.categories.len() > 64 || selector.selected_record_ids.len() > 1000 { + return Err(BrokerError::InvalidSelector); + } + let mut decoded = Self::default(); + for raw in &selector.categories { + let category = + CommonDataCategory::try_from(*raw).map_err(|_| BrokerError::InvalidSelector)?; + if category == CommonDataCategory::Unspecified || !decoded.categories.insert(category) { + return Err(BrokerError::InvalidSelector); + } + } + for record_id in &selector.selected_record_ids { + if record_id.trim().is_empty() + || record_id.len() > 256 + || !decoded.record_ids.insert(record_id.clone()) + { + return Err(BrokerError::InvalidSelector); + } + } + Ok(decoded) + } + + fn scopes(&self, record: &StoredRecord) -> Vec { + // Category and selected-record grants are independent. If both are selected and the + // category grant denies, the record selector still gets its own authorization check. + let mut scopes = Vec::with_capacity(2); + if record.class == SharingClass::Common + && record + .category + .is_some_and(|category| self.categories.contains(&category)) + { + scopes.push(AccessScope::Category( + record.category.expect("checked above"), + )); + } + if self.record_ids.contains(&record.record_id) { + scopes.push(AccessScope::SelectedRecord(record.record_id.clone())); + } + if record.class != SharingClass::Common { + // A Data/domain request names its dataset explicitly. Sensitive/custom policies may + // authorize that exact dataset; a Common record never gets a dataset-wide shortcut. + scopes.push(AccessScope::Dataset(record.dataset_id.clone())); + } + scopes + } +} + +#[derive(Debug, Error, Clone, PartialEq, Eq)] +pub enum BrokerError { + #[error("publication identity or dataset is invalid")] + InvalidPublication, + #[error("publication sequence is duplicate or out of order; current sequence is {0}")] + SequenceConflict(u64), + #[error("publication payload contains a host-owned field")] + ReservedField, + #[error("publication exceeds the size limit")] + RecordTooLarge, + #[error("shared-data retention quota is exhausted")] + QuotaExceeded, + #[error("common-data selector is malformed")] + InvalidSelector, + #[error("cursor is stale or belongs to another query")] + StaleCursor, + #[error("current authorization changed while the query was running")] + AuthorizationChanged, + #[error("subscription cursor must match the current broker revision")] + StaleSubscription, + #[error("subscriber is not the authenticated recipient of this projection")] + WrongRecipient, + #[error("projection has expired")] + Expired, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SubscriptionEnd { + Revoked, + FellBehind, +} + +struct BrokerState { + revision: u64, + bytes: usize, + rows: VecDeque, + sequences: HashMap, + subscribers: Vec>>, +} + +#[derive(Clone, Debug, Hash, PartialEq, Eq)] +struct PublicationStream { + owner: String, + publisher_fingerprint: String, + profile: String, + dataset_id: String, + resource_id: String, +} + +#[derive(Clone, Debug)] +struct SequenceCursor { + sequence: u64, + record_id: String, + session_id: Option, +} + +struct SubscriptionState { + request: QueryRequest, + selector: QuerySelector, + authorizer: Arc, + policy_revision: u64, + after_revision: u64, + queue_capacity: usize, + queue: VecDeque, + ended: Option, + notify: Arc, +} + +/// Bounded in-memory broker. Persistent domain/telemetry stores can feed records here after +/// resolving the producer identity and before returning shared projections. +pub struct DataBroker { + state: Mutex, +} + +impl Default for DataBroker { + fn default() -> Self { + Self::new() + } +} + +impl DataBroker { + pub fn new() -> Self { + Self { + state: Mutex::new(BrokerState { + revision: 0, + bytes: 0, + rows: VecDeque::new(), + sequences: HashMap::new(), + subscribers: Vec::new(), + }), + } + } + + /// Stores a host-authenticated publication. The ID, revision, timestamp and provenance are + /// assigned by the broker; payload fields cannot overwrite them. + pub fn publish( + &self, + publication: Publication, + now: i64, + ) -> Result { + self.publish_inner(publication, now, false) + } + + /// Publishes the latest value for a resource stream, removing its previous retained value + /// atomically. This is for bounded current-state domains such as GamePresence; ordinary Data + /// observations continue to use append-only [`publish`](Self::publish). + pub fn publish_replacing( + &self, + publication: Publication, + now: i64, + ) -> Result { + self.publish_inner(publication, now, true) + } + + /// Returns the owner's current record for one host-scoped resource. This is for a host + /// service that atomically replaces a typed series; it is not a plugin-facing read path. + pub fn owner_resource( + &self, + owner: &PluginIdentity, + dataset_id: &str, + resource_id: &str, + now: i64, + ) -> Option { + let mut state = self.lock(); + prune_expired_locked(&mut state, now); + state + .rows + .iter() + .find(|record| { + &record.owner == owner + && record.dataset_id == dataset_id + && record.resource_id == resource_id + }) + .map(|record| OwnedRecord { + fields: record.fields.clone(), + revision: record.revision, + sequence: record.sequence, + source_observation_id: record.source_observation_id.clone(), + observed_at: record.observed_at, + }) + } + + /// Current broker revision, used to fence a host-owned composite cursor across pages. + pub fn revision(&self) -> u64 { + self.lock().revision + } + + /// Validates a publication exactly as a stored session publication, without storing it. + /// Durable publications use this so a record accepted by either mode follows the same + /// payload, provenance and expiry rules. + pub fn validate(publication: &Publication, now: i64) -> Result<(), BrokerError> { + validate_publication(publication, now) + } + + fn publish_inner( + &self, + publication: Publication, + now: i64, + replace_resource: bool, + ) -> Result { + let (record, subscribers) = { + let mut state = self.lock(); + if replace_resource { + validate_publication(&publication, now)?; + prune_expired_locked(&mut state, now); + if let Some(prior) = state.rows.iter().find(|record| { + record.owner == publication.owner + && record.dataset_id == publication.dataset_id + && record.resource_id == publication.resource_id + && record.source_observation_id == publication.source_observation_id + }) && same_observation(prior, &publication) + { + return Ok(PublicationReceipt { + record_id: prior.record_id.clone(), + revision: prior.revision, + duplicate: true, + }); + } + if publication.sequence > 0 { + let stream = PublicationStream { + owner: publication.owner.plugin_id.clone(), + publisher_fingerprint: publication.owner.publisher_fingerprint.clone(), + profile: publication.owner.profile_id.clone(), + dataset_id: publication.dataset_id.clone(), + resource_id: publication.resource_id.clone(), + }; + if let Some(cursor) = state.sequences.get(&stream) + && publication.sequence <= cursor.sequence + { + return Err(BrokerError::SequenceConflict(cursor.sequence)); + } + } + let replaced_bytes = state + .rows + .iter() + .filter(|record| { + record.owner == publication.owner + && record.dataset_id == publication.dataset_id + && record.resource_id == publication.resource_id + }) + .map(|record| record.bytes) + .sum::(); + let replaced_count = state + .rows + .iter() + .filter(|record| { + record.owner == publication.owner + && record.dataset_id == publication.dataset_id + && record.resource_id == publication.resource_id + }) + .count(); + let new_bytes = publication_bytes(&publication)?; + if new_bytes > MAX_RECORD_BYTES { + return Err(BrokerError::RecordTooLarge); + } + if state.rows.len().saturating_sub(replaced_count) >= MAX_RECORDS + || state + .bytes + .saturating_sub(replaced_bytes) + .saturating_add(new_bytes) + > MAX_RETAINED_BYTES + { + return Err(BrokerError::QuotaExceeded); + } + remove_resource_records( + &mut state, + &publication.owner, + &publication.dataset_id, + &publication.resource_id, + ); + } + let (record, duplicate) = Self::insert(&mut state, publication, None, now)?; + if duplicate { + return Ok(PublicationReceipt { + record_id: record.record_id, + revision: record.revision, + duplicate: true, + }); + } + let subscribers = state.subscribers.clone(); + (record, subscribers) + }; + self.dispatch(&record, subscribers, now); + Ok(PublicationReceipt { + record_id: record.record_id, + revision: record.revision, + duplicate: false, + }) + } + + /// Republishes only fields that the recipient actually received. Provenance remains source + /// attributed and the current authenticated publisher is appended by the host. + pub fn publish_onward( + &self, + publisher: &PluginIdentity, + projected: &ProjectedRecord, + authorizer: &dyn Authorizer, + now: i64, + ) -> Result { + if &projected.recipient != publisher { + return Err(BrokerError::WrongRecipient); + } + if authorizer.revision(publisher) != projected.policy_revision { + return Err(BrokerError::AuthorizationChanged); + } + if projected.expires_at.is_some_and(|expiry| expiry <= now) { + return Err(BrokerError::Expired); + } + let mut provenance = projected.provenance.clone(); + if provenance.forwarded_by.last() != Some(publisher) { + provenance.forwarded_by.push(publisher.clone()); + } + provenance + .source_record_ids + .push(projected.record_id.clone()); + let publication = Publication { + owner: publisher.clone(), + dataset_id: projected.dataset_id.clone(), + category: projected.category, + class: SharingClass::Custom, + schema_id: projected.schema_id.clone(), + schema_version: projected.schema_version, + fields: projected.fields.clone(), + opaque_payload: projected.opaque_payload.clone(), + resource_id: projected.resource_id.clone(), + observed_at: projected.observed_at, + sequence: projected.sequence, + source_observation_id: projected.source_observation_id.clone(), + session_id: None, + publisher: None, + expires_at: projected.expires_at, + }; + let (record, subscribers) = { + let mut state = self.lock(); + let (record, duplicate) = Self::insert(&mut state, publication, Some(provenance), now)?; + if duplicate { + return Ok(PublicationReceipt { + record_id: record.record_id, + revision: record.revision, + duplicate: true, + }); + } + let subscribers = state.subscribers.clone(); + (record, subscribers) + }; + self.dispatch(&record, subscribers, now); + Ok(PublicationReceipt { + record_id: record.record_id, + revision: record.revision, + duplicate: false, + }) + } + + /// Domain and Data aliases deliberately share the same authorization and projection path. + pub fn query_domain( + &self, + request: QueryRequest, + authorizer: &dyn Authorizer, + now: i64, + ) -> Result { + self.query_inner(request, None, Vec::new(), authorizer, now) + } + + pub fn query_data( + &self, + request: QueryRequest, + authorizer: &dyn Authorizer, + now: i64, + ) -> Result { + self.query_inner(request, None, Vec::new(), authorizer, now) + } + + /// Queries session-retained and durable records as one stable page. `durable` is the + /// host-loaded candidate set from the public pool; every row still passes the same owner or + /// grant authorization and field projection as a session row. + pub(crate) fn query_data_with_durable( + &self, + request: QueryRequest, + durable: Vec, + authorizer: &dyn Authorizer, + now: i64, + ) -> Result { + self.query_inner(request, None, durable, authorizer, now) + } + + /// Exact host-owned resource lookup through the same authorization/projection path as a + /// general query. Resource IDs are opaque to the broker and are distinct from record IDs. + pub fn query_data_resource( + &self, + request: QueryRequest, + resource_id: &str, + authorizer: &dyn Authorizer, + now: i64, + ) -> Result { + if resource_id.trim().is_empty() || resource_id.len() > MAX_RESOURCE_ID_BYTES { + return Err(BrokerError::InvalidPublication); + } + self.query_inner(request, Some(resource_id), Vec::new(), authorizer, now) + } + + fn query_inner( + &self, + request: QueryRequest, + resource_id: Option<&str>, + durable: Vec, + authorizer: &dyn Authorizer, + now: i64, + ) -> Result { + validate_query(&request)?; + if request.delivery == Delivery::Live { + return Err(BrokerError::InvalidPublication); + } + let selector = QuerySelector::decode(request.selector.as_ref())?; + let policy_revision = authorizer.revision(&request.caller); + let (snapshot_revision, after, rows) = { + let mut state = self.lock(); + prune_expired_locked(&mut state, now); + let snapshot = state.revision; + let after = match &request.cursor { + Some(cursor) => { + if cursor.caller != request.caller + || cursor.dataset_id != request.dataset_id + || cursor.record_id != request.record_id + || cursor.category != request.category + || cursor.selector != selector + || cursor.delivery != request.delivery + || cursor.snapshot_revision != snapshot + || cursor.policy_revision != policy_revision + { + return Err(BrokerError::StaleCursor); + } + cursor + .after_record_id + .clone() + .map(|record_id| (cursor.after_received_at, record_id)) + } + None => None, + }; + let mut rows = state + .rows + .iter() + .filter(|record| record_matches(record, &request, resource_id, now)) + .cloned() + .collect::>(); + // Durable rows are read by the storage worker; they are never retained here. + rows.extend( + durable + .into_iter() + .map(StoredRecord::from) + .filter(|record| record_matches(record, &request, resource_id, now)), + ); + // One stable order for both sources: receipt time, then the globally unique id. + rows.sort_by(|left, right| { + (left.received_at, left.record_id.as_str()) + .cmp(&(right.received_at, right.record_id.as_str())) + }); + (snapshot, after, rows) + }; + + let mut projected = Vec::new(); + for record in rows { + let position = (record.received_at, record.record_id.clone()); + if after.as_ref().is_some_and(|after| &position <= after) { + continue; + } + if let Some(result) = project_for_query( + &request.caller, + &selector, + &record, + request.delivery, + policy_revision, + authorizer, + )? { + projected.push((position, result)); + } + } + if authorizer.revision(&request.caller) != policy_revision { + return Err(BrokerError::AuthorizationChanged); + } + + let page_size = request.page_size.clamp(1, MAX_PAGE_SIZE); + let mut records = Vec::with_capacity(page_size); + let mut last = None; + let mut has_more = false; + for (position, record) in projected { + if records.len() == page_size { + has_more = true; + break; + } + last = Some(position); + records.push(record); + } + let next_cursor = has_more.then(|| { + let (after_received_at, after_record_id) = last.unwrap_or((0, String::new())); + QueryCursor { + caller: request.caller.clone(), + dataset_id: request.dataset_id.clone(), + record_id: request.record_id.clone(), + category: request.category, + selector, + delivery: request.delivery, + snapshot_revision, + after_received_at, + after_record_id: Some(after_record_id), + policy_revision, + } + }); + Ok(QueryResult { + records, + next_cursor, + revision: snapshot_revision, + }) + } + + /// Opens a live subscription from the exact current broker revision. `after_revision == 0` + /// starts live-only at the current snapshot; nonzero stale/future positions are fenced. + pub fn subscribe( + &self, + request: QueryRequest, + after_revision: u64, + queue_capacity: usize, + authorizer: Arc, + ) -> Result { + validate_query(&request)?; + let selector = QuerySelector::decode(request.selector.as_ref())?; + let policy_revision = authorizer.revision(&request.caller); + let mut broker_state = self.lock(); + if after_revision != 0 && after_revision != broker_state.revision { + return Err(BrokerError::StaleSubscription); + } + let after_revision = broker_state.revision; + let mut request = request; + request.delivery = Delivery::Live; + request.cursor = None; + let inner = Arc::new(Mutex::new(SubscriptionState { + request, + selector, + authorizer: authorizer.clone(), + policy_revision, + after_revision, + queue_capacity: queue_capacity.clamp(1, MAX_SUBSCRIPTION_QUEUE), + queue: VecDeque::new(), + ended: None, + notify: Arc::new(tokio::sync::Notify::new()), + })); + broker_state.subscribers.push(Arc::downgrade(&inner)); + drop(broker_state); + Ok(Subscription { inner, authorizer }) + } + + /// Expire retained records and advance the revision fence if anything changed. + pub fn expire(&self, now: i64) -> usize { + let mut state = self.lock(); + prune_expired_locked(&mut state, now) + } + + /// Removes session-only publications before a disconnected producer can leave data behind. + /// Existing watches are fenced so no queued copy can outlive the producer session. + pub fn close_session(&self, session_id: &str) -> usize { + if session_id.is_empty() { + return 0; + } + let mut state = self.lock(); + let before = state.rows.len(); + let removed_bytes = state + .rows + .iter() + .filter(|record| record.session_id.as_deref() == Some(session_id)) + .map(|record| record.bytes) + .sum::(); + state + .rows + .retain(|record| record.session_id.as_deref() != Some(session_id)); + state.bytes = state.bytes.saturating_sub(removed_bytes); + state + .sequences + .retain(|_, cursor| cursor.session_id.as_deref() != Some(session_id)); + let removed = before - state.rows.len(); + if removed == 0 { + return 0; + } + state.revision = state.revision.saturating_add(1); + for subscriber in &state.subscribers { + if let Some(inner) = subscriber.upgrade() { + let mut subscription = lock(&inner); + subscription.queue.clear(); + subscription.ended = Some(SubscriptionEnd::FellBehind); + subscription.notify.notify_waiters(); + } + } + removed + } + + /// Records a durable publication already accepted by the storage worker. The row is not + /// retained here: the pool remains its source of truth and reads load it from there. The + /// broker revision still advances, so a `DataList` revision can hand off to `DataWatch` across + /// both sources, and current watchers receive the new revision as a published event. + /// + /// The position is lifted to the persisted pool sequence of the write. A host that restarted + /// with an empty broker therefore never dispatches a durable event below a sequence an earlier + /// run already published. + pub(crate) fn note_durable(&self, record: DurableRecord, now: i64) -> u64 { + let pool_revision = record.pool_revision; + let record = StoredRecord::from(record); + let (record, subscribers, position) = { + let mut state = self.lock(); + state.revision = state.revision.saturating_add(1).max(pool_revision); + let position = state.revision; + ( + StoredRecord { position, ..record }, + state.subscribers.clone(), + position, + ) + }; + self.dispatch(&record, subscribers, now); + position + } + + /// Raises the broker revision to a persisted durable-pool sequence and returns the revision + /// that lists and watches must use from now on. Called before a read or a subscription so a + /// restarted host resumes the durable handoff instead of restarting at zero; it only ever + /// moves forward, so a session publication that already advanced it is preserved. + pub fn observe_pool_revision(&self, revision: u64) -> u64 { + let mut state = self.lock(); + state.revision = state.revision.max(revision); + state.revision + } + + /// Returns only host-owned dataset and field names needed to review sharing. No plugin + /// values, paths, or opaque payload bytes leave the broker through this view. + pub fn sharing_catalog(&self, now: i64) -> Vec { + let mut state = self.lock(); + prune_expired_locked(&mut state, now); + state + .rows + .iter() + .map(|record| { + let mut fields = record.fields.keys().cloned().collect::>(); + if !record.opaque_payload.is_empty() { + fields.insert("opaque_payload".to_owned()); + } + SharedDataCatalogRecord { + owner: record.owner.clone(), + record_id: record.record_id.clone(), + dataset_id: record.dataset_id.clone(), + class: record.class, + category: record.category, + fields, + } + }) + .collect() + } + + fn insert( + state: &mut BrokerState, + publication: Publication, + onward: Option, + now: i64, + ) -> Result<(StoredRecord, bool), BrokerError> { + validate_publication(&publication, now)?; + prune_expired_locked(state, now); + let stream = (publication.sequence > 0).then(|| PublicationStream { + owner: publication.owner.plugin_id.clone(), + publisher_fingerprint: publication.owner.publisher_fingerprint.clone(), + profile: publication.owner.profile_id.clone(), + dataset_id: publication.dataset_id.clone(), + resource_id: publication.resource_id.clone(), + }); + if let Some(stream) = &stream { + let current_sequence = state.sequences.get(stream).map(|cursor| cursor.sequence); + let prior_observation = state.rows.iter().find(|record| { + record.owner.plugin_id == publication.owner.plugin_id + && record.owner.publisher_fingerprint == publication.owner.publisher_fingerprint + && record.owner.profile_id == publication.owner.profile_id + && record.dataset_id == publication.dataset_id + && record.resource_id == publication.resource_id + && record.source_observation_id == publication.source_observation_id + }); + if let Some(prior) = prior_observation { + if same_observation(prior, &publication) { + return Ok((prior.clone(), true)); + } + return Err(BrokerError::SequenceConflict( + current_sequence.unwrap_or(prior.sequence), + )); + } + if let Some(cursor) = state.sequences.get(stream) + && publication.sequence <= cursor.sequence + { + return Err(BrokerError::SequenceConflict(cursor.sequence)); + } + } + let bytes = + publication_bytes(&publication)?.saturating_add(provenance_bytes(onward.as_ref())); + if bytes > MAX_RECORD_BYTES { + return Err(BrokerError::RecordTooLarge); + } + if state.rows.len() >= MAX_RECORDS || state.bytes.saturating_add(bytes) > MAX_RETAINED_BYTES + { + return Err(BrokerError::QuotaExceeded); + } + state.revision = state.revision.saturating_add(1); + let revision = state.revision; + let owner = publication.owner; + let publisher = publication.publisher.clone().unwrap_or_default(); + let record = StoredRecord { + record_id: format!("shared-{revision:016x}"), + provenance: onward.unwrap_or_else(|| Provenance { + source: owner.clone(), + forwarded_by: Vec::new(), + declared_developer: publisher.declared_developer, + origin: publisher.origin, + package_version: publisher.package_version, + package_digest: publisher.package_digest, + source_record_ids: Vec::new(), + }), + owner, + dataset_id: publication.dataset_id, + category: publication.category, + class: publication.class, + schema_id: publication.schema_id, + schema_version: publication.schema_version, + fields: publication.fields, + opaque_payload: publication.opaque_payload, + resource_id: publication.resource_id, + observed_at: publication.observed_at, + received_at: now, + sequence: publication.sequence, + source_observation_id: publication.source_observation_id, + session_id: publication.session_id, + published_at: now, + expires_at: publication.expires_at, + revision, + position: revision, + durable: false, + bytes, + }; + state.bytes = state.bytes.saturating_add(bytes); + state.rows.push_back(record.clone()); + if let Some(stream) = stream { + state.sequences.insert( + stream, + SequenceCursor { + sequence: record.sequence, + record_id: record.record_id.clone(), + session_id: record.session_id.clone(), + }, + ); + } + Ok((record, false)) + } + + fn dispatch( + &self, + record: &StoredRecord, + subscribers: Vec>>, + now: i64, + ) { + for subscriber in subscribers { + let Some(inner) = subscriber.upgrade() else { + continue; + }; + let mut state = lock(&inner); + if state.ended.is_some() { + continue; + } + if record.position <= state.after_revision { + continue; + } + if state + .request + .category + .is_some_and(|category| record.category != Some(category)) + || state.request.dataset_id != record.dataset_id + || record.expires_at.is_some_and(|expiry| expiry <= now) + { + continue; + } + let request = state.request.clone(); + let selector = state.selector.clone(); + let initial_revision = state.policy_revision; + let authorizer = state.authorizer.clone(); + state.after_revision = record.position; + drop(state); + + if authorizer.revision(&request.caller) != initial_revision { + let mut state = lock(&inner); + state.queue.clear(); + state.ended = Some(SubscriptionEnd::Revoked); + // Wake a waiting stream so it observes revocation now, not at its next recheck. + state.notify.notify_waiters(); + continue; + } + let projected = project_for_query( + &request.caller, + &selector, + record, + Delivery::Live, + initial_revision, + authorizer.as_ref(), + ); + let mut state = lock(&inner); + match projected { + Err(_) => { + state.queue.clear(); + state.ended = Some(SubscriptionEnd::Revoked); + state.notify.notify_waiters(); + } + Ok(Some(projection)) => { + if state.queue.len() >= state.queue_capacity { + state.queue.clear(); + state.ended = Some(SubscriptionEnd::FellBehind); + state.notify.notify_waiters(); + } else { + state.queue.push_back(projection); + state.notify.notify_one(); + } + } + Ok(None) => {} + } + if state.ended.is_some() { + continue; + } + } + // Prune dead/closed handles without replacing the vector copied by another concurrent + // publisher or dropping subscriptions registered while this event was being projected. + self.lock().subscribers.retain(|subscriber| { + subscriber + .upgrade() + .is_some_and(|inner| lock(&inner).ended.is_none()) + }); + } + + fn lock(&self) -> MutexGuard<'_, BrokerState> { + lock(&self.state) + } +} + +/// One bounded live stream. Calling `next` rechecks the policy revision before releasing queued +/// projections, so revocation fences already-buffered events as well as future ones. +pub struct Subscription { + inner: Arc>, + authorizer: Arc, +} + +impl Subscription { + pub fn next(&self, now: i64) -> Result, SubscriptionEnd> { + let mut state = lock(&self.inner); + if self.authorizer.revision(&state.request.caller) != state.policy_revision { + state.queue.clear(); + state.ended = Some(SubscriptionEnd::Revoked); + } + if let Some(ended) = state.ended { + return Err(ended); + } + while state + .queue + .front() + .is_some_and(|record| record.expires_at.is_some_and(|expiry| expiry <= now)) + { + state.queue.pop_front(); + } + Ok(state.queue.pop_front()) + } + + pub fn is_ended(&self) -> Option { + lock(&self.inner).ended + } + + /// Waits for one event without blocking a worker thread. The caller should also recheck + /// provider-session grants on its existing periodic authorization interval. + pub async fn recv(&self, now: i64) -> Result, SubscriptionEnd> { + loop { + let notify = lock(&self.inner).notify.clone(); + let notified = notify.notified(); + if let Some(record) = self.next(now)? { + return Ok(Some(record)); + } + notified.await; + } + } +} + +fn project_for_query( + caller: &PluginIdentity, + selector: &QuerySelector, + record: &StoredRecord, + delivery: Delivery, + policy_revision: u64, + authorizer: &dyn Authorizer, +) -> Result, BrokerError> { + let mut available: BTreeSet = record.fields.keys().cloned().collect(); + if !record.opaque_payload.is_empty() { + available.insert("opaque_payload".to_owned()); + } + let scopes = if &record.owner == caller { + vec![AccessScope::Owner] + } else { + selector.scopes(record) + }; + if scopes.is_empty() { + return Ok(None); + } + let mut selected_decision = None; + for scope in scopes { + let decision = if scope == AccessScope::Owner { + AccessDecision { + allowed: true, + fields: available.clone(), + history: true, + live: true, + revision: policy_revision, + } + } else { + let request = AccessRequest { + recipient: caller, + source: &record.owner, + record_id: &record.record_id, + dataset_id: &record.dataset_id, + category: record.category, + scope, + class: record.class, + fields: &available, + delivery, + }; + authorizer.decide(&request) + }; + if decision.revision != policy_revision { + return Err(BrokerError::AuthorizationChanged); + } + let has_visible_field = available + .iter() + .any(|field| decision.fields.contains(field)); + if decision.allowed + && has_visible_field + && (delivery != Delivery::History || decision.history) + && (delivery != Delivery::Live || decision.live) + { + selected_decision = Some(decision); + break; + } + } + let Some(decision) = selected_decision else { + return Ok(None); + }; + let fields: Map = record + .fields + .iter() + .filter(|(key, _)| decision.fields.contains(*key)) + .map(|(key, value)| (key.clone(), value.clone())) + .collect(); + let opaque_payload = if decision.fields.contains("opaque_payload") { + record.opaque_payload.clone() + } else { + Vec::new() + }; + if fields.is_empty() && opaque_payload.is_empty() { + return Ok(None); + } + Ok(Some(ProjectedRecord { + record_id: record.record_id.clone(), + dataset_id: record.dataset_id.clone(), + category: record.category, + schema_id: record.schema_id.clone(), + schema_version: record.schema_version, + fields, + opaque_payload, + resource_id: record.resource_id.clone(), + observed_at: record.observed_at, + received_at: record.received_at, + sequence: record.sequence, + source_observation_id: record.source_observation_id.clone(), + published_at: record.published_at, + revision: record.revision, + expires_at: record.expires_at, + provenance: record.provenance.clone(), + recipient: caller.clone(), + policy_revision, + durable: record.durable, + })) +} + +fn validate_query(request: &QueryRequest) -> Result<(), BrokerError> { + if request.dataset_id.trim().is_empty() + || request.dataset_id.len() > 256 + || request.dataset_id.chars().any(char::is_control) + { + return Err(BrokerError::InvalidPublication); + } + Ok(()) +} + +/// The dataset, identity and expiry filters shared by session and durable candidates. +fn record_matches( + record: &StoredRecord, + request: &QueryRequest, + resource_id: Option<&str>, + now: i64, +) -> bool { + record.dataset_id == request.dataset_id + && request + .record_id + .as_ref() + .is_none_or(|record_id| &record.record_id == record_id) + && resource_id.is_none_or(|resource_id| { + record.resource_id == resource_id || record.record_id == resource_id + }) + && request + .category + .is_none_or(|category| record.category == Some(category)) + && record.expires_at.is_none_or(|expiry| expiry > now) +} + +fn retain_live_sequences(state: &mut BrokerState) { + let live_records: HashSet<&str> = state + .rows + .iter() + .map(|record| record.record_id.as_str()) + .collect(); + state + .sequences + .retain(|_, cursor| live_records.contains(cursor.record_id.as_str())); +} + +fn remove_resource_records( + state: &mut BrokerState, + owner: &PluginIdentity, + dataset_id: &str, + resource_id: &str, +) { + let before = state.rows.len(); + let mut removed_bytes = 0usize; + state.rows.retain(|record| { + let matches = &record.owner == owner + && record.dataset_id == dataset_id + && record.resource_id == resource_id; + if matches { + removed_bytes = removed_bytes.saturating_add(record.bytes); + } + !matches + }); + if state.rows.len() != before { + state.bytes = state.bytes.saturating_sub(removed_bytes); + state.revision = state.revision.saturating_add(1); + } +} + +fn prune_expired_locked(state: &mut BrokerState, now: i64) -> usize { + let before = state.rows.len(); + let expired_bytes = state + .rows + .iter() + .filter(|record| record.expires_at.is_some_and(|expiry| expiry <= now)) + .map(|record| record.bytes) + .sum::(); + state + .rows + .retain(|record| record.expires_at.is_none_or(|expiry| expiry > now)); + retain_live_sequences(state); + state.bytes = state.bytes.saturating_sub(expired_bytes); + let removed = before - state.rows.len(); + if removed > 0 { + state.revision = state.revision.saturating_add(1); + } + removed +} + +fn publication_bytes(publication: &Publication) -> Result { + let fields = serde_json::to_vec(&publication.fields) + .map_err(|_| BrokerError::InvalidPublication)? + .len(); + let mut bytes = fields + .saturating_add(publication.opaque_payload.len()) + .saturating_add(publication.owner.plugin_id.len()) + .saturating_add(publication.owner.publisher_fingerprint.len()) + .saturating_add(publication.owner.profile_id.len()) + .saturating_add(publication.dataset_id.len()) + .saturating_add(publication.schema_id.len()) + .saturating_add(publication.resource_id.len()) + .saturating_add(publication.source_observation_id.len()) + .saturating_add(128); // Protobuf tags, timestamps, counters, enum and host record ID. + if let Some(session_id) = &publication.session_id { + bytes = bytes.saturating_add(session_id.len()); + } + if let Some(publisher) = &publication.publisher { + bytes = bytes + .saturating_add(publisher.declared_developer.len()) + .saturating_add(publisher.origin.len()) + .saturating_add(publisher.package_version.len()) + .saturating_add(publisher.package_digest.len()); + } + Ok(bytes) +} + +fn provenance_bytes(provenance: Option<&Provenance>) -> usize { + let Some(provenance) = provenance else { + return 0; + }; + let identity_bytes = |identity: &PluginIdentity| { + identity + .plugin_id + .len() + .saturating_add(identity.publisher_fingerprint.len()) + .saturating_add(identity.profile_id.len()) + }; + provenance + .forwarded_by + .iter() + .map(identity_bytes) + .chain(provenance.source_record_ids.iter().map(String::len)) + .fold( + provenance + .source + .plugin_id + .len() + .saturating_add(provenance.source.publisher_fingerprint.len()) + .saturating_add(provenance.source.profile_id.len()) + .saturating_add(provenance.declared_developer.len()) + .saturating_add(provenance.origin.len()) + .saturating_add(provenance.package_version.len()) + .saturating_add(provenance.package_digest.len()), + usize::saturating_add, + ) +} + +fn same_observation(record: &StoredRecord, publication: &Publication) -> bool { + record.owner == publication.owner + && record.dataset_id == publication.dataset_id + && record.schema_id == publication.schema_id + && record.schema_version == publication.schema_version + && record.fields == publication.fields + && record.opaque_payload == publication.opaque_payload + && record.resource_id == publication.resource_id + && record.observed_at == publication.observed_at + && record.sequence == publication.sequence + && record.source_observation_id == publication.source_observation_id +} + +fn validate_publication(publication: &Publication, now: i64) -> Result<(), BrokerError> { + let structured = !publication.fields.is_empty(); + let opaque = !publication.opaque_payload.is_empty(); + if publication.owner.validate().is_err() + || publication.dataset_id.trim().is_empty() + || publication.dataset_id.len() > 256 + || publication.dataset_id.chars().any(char::is_control) + || publication.schema_id.trim().is_empty() + || publication.schema_id.len() > 256 + || publication.schema_id.chars().any(char::is_control) + || publication.schema_version == 0 + || (publication.publisher.is_some() + && !publication + .schema_id + .starts_with(&format!("{}.", publication.dataset_id)) + && publication.schema_id != publication.dataset_id) + || now <= 0 + || publication.expires_at.is_some_and(|expiry| expiry <= now) + || publication + .expires_at + .is_some_and(|expiry| expiry.saturating_sub(now) > MAX_TTL_SECONDS as i64) + || (structured == opaque) + || (publication.class == SharingClass::Common && publication.category.is_none()) + { + return Err(BrokerError::InvalidPublication); + } + if publication.publisher.is_some() && publication.sequence == 0 { + return Err(BrokerError::InvalidPublication); + } + if publication + .fields + .keys() + .any(|key| RESERVED_FIELDS.contains(&key.as_str())) + { + return Err(BrokerError::ReservedField); + } + if publication.sequence > 0 + && (publication.resource_id.trim().is_empty() + || publication.resource_id.len() > MAX_RESOURCE_ID_BYTES + || publication.resource_id.chars().any(char::is_control) + || publication.source_observation_id.trim().is_empty() + || publication.source_observation_id.len() > MAX_OBSERVATION_ID_BYTES + || publication + .source_observation_id + .chars() + .any(char::is_control) + || publication.observed_at < 0) + { + return Err(BrokerError::InvalidPublication); + } + if let Some(session_id) = &publication.session_id + && (session_id.trim().is_empty() + || session_id.len() > 128 + || session_id.chars().any(char::is_control)) + { + return Err(BrokerError::InvalidPublication); + } + if let Some(publisher) = &publication.publisher + && (publisher.package_digest.len() != 32 + || publisher.declared_developer.trim().is_empty() + || publisher.declared_developer.len() > 256 + || publisher.origin.trim().is_empty() + || publisher.origin.len() > 512 + || publisher.package_version.trim().is_empty() + || publisher.package_version.len() > 128) + { + return Err(BrokerError::InvalidPublication); + } + let mut item_count = 0; + validate_field_object(&publication.fields, 1, &mut item_count)?; + let bytes = publication_bytes(publication)?; + if bytes > MAX_RECORD_BYTES { + return Err(BrokerError::RecordTooLarge); + } + Ok(()) +} + +fn validate_field_object( + fields: &Map, + depth: usize, + item_count: &mut usize, +) -> Result<(), BrokerError> { + if depth > MAX_FIELD_DEPTH { + return Err(BrokerError::InvalidPublication); + } + for (key, value) in fields { + *item_count += 1; + if *item_count > MAX_FIELD_ITEMS + || key.is_empty() + || key.len() > MAX_FIELD_KEY_BYTES + || key.chars().any(char::is_control) + { + return Err(BrokerError::InvalidPublication); + } + validate_field_value(value, depth + 1, item_count)?; + } + Ok(()) +} + +fn validate_field_value( + value: &Value, + depth: usize, + item_count: &mut usize, +) -> Result<(), BrokerError> { + if depth > MAX_FIELD_DEPTH { + return Err(BrokerError::InvalidPublication); + } + match value { + Value::Object(fields) => validate_field_object(fields, depth, item_count), + Value::Array(values) => { + for child in values { + *item_count += 1; + if *item_count > MAX_FIELD_ITEMS { + return Err(BrokerError::InvalidPublication); + } + validate_field_value(child, depth + 1, item_count)?; + } + Ok(()) + } + Value::Number(number) if number.as_f64().is_none_or(|number| !number.is_finite()) => { + Err(BrokerError::InvalidPublication) + } + _ => Ok(()), + } +} + +fn lock(mutex: &Mutex) -> MutexGuard<'_, T> { + mutex + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::{AtomicU64, Ordering}; + + struct TestAuthorizer { + revision: AtomicU64, + categories: BTreeSet, + record_ids: BTreeSet, + classes: BTreeSet, + fields: BTreeSet, + history: bool, + live: bool, + } + + impl TestAuthorizer { + fn new( + categories: impl IntoIterator, + record_ids: impl IntoIterator, + classes: impl IntoIterator, + fields: impl IntoIterator, + history: bool, + live: bool, + ) -> Self { + Self { + revision: AtomicU64::new(1), + categories: categories.into_iter().collect(), + record_ids: record_ids.into_iter().collect(), + classes: classes.into_iter().collect(), + fields: fields.into_iter().collect(), + history, + live, + } + } + } + + impl Authorizer for TestAuthorizer { + fn revision(&self, _recipient: &PluginIdentity) -> u64 { + self.revision.load(Ordering::SeqCst) + } + + fn decide(&self, request: &AccessRequest<'_>) -> AccessDecision { + let scope_allowed = match &request.scope { + AccessScope::Owner => false, + AccessScope::Category(category) => { + request.class == SharingClass::Common && self.categories.contains(category) + } + AccessScope::SelectedRecord(record_id) => { + request.class == SharingClass::Common && self.record_ids.contains(record_id) + } + AccessScope::Dataset(_) => false, + }; + let fields = request + .fields + .intersection(&self.fields) + .cloned() + .collect::>(); + let allowed = + scope_allowed && self.classes.contains(&request.class) && !fields.is_empty(); + AccessDecision { + allowed, + fields, + history: allowed && self.history, + live: allowed && self.live, + revision: self.revision(request.recipient), + } + } + } + + fn identity(id: &str) -> PluginIdentity { + PluginIdentity { + plugin_id: format!("org.example.{id}"), + publisher_fingerprint: format!("SHA256:{id}"), + profile_id: "profile-main".into(), + } + } + + fn publication(owner: &PluginIdentity, fields: &[(&str, Value)]) -> Publication { + Publication { + owner: owner.clone(), + dataset_id: "performance.v1".into(), + category: Some(CommonDataCategory::GamePerformanceHistory), + class: SharingClass::Common, + schema_id: "org.example.performance.v1".into(), + schema_version: 1, + fields: fields + .iter() + .map(|(key, value)| ((*key).to_owned(), value.clone())) + .collect(), + opaque_payload: Vec::new(), + resource_id: String::new(), + observed_at: 0, + sequence: 0, + source_observation_id: String::new(), + session_id: None, + publisher: None, + expires_at: None, + } + } + + #[test] + fn replacing_resource_keeps_only_the_current_record_and_sequence_is_monotonic() { + let broker = DataBroker::new(); + let owner = identity("publisher"); + let mut first = publication(&owner, &[("state", Value::String("playing".into()))]); + first.dataset_id = "game.presence.v1".into(); + first.class = SharingClass::Sensitive; + first.category = None; + first.schema_id = "game.presence.v1".into(); + first.resource_id = "game:1/session:a".into(); + first.sequence = 1; + first.source_observation_id = "presence-1".into(); + first.expires_at = Some(500); + broker.publish_replacing(first.clone(), 100).unwrap(); + + let mut latest = first.clone(); + latest.fields = [("state".into(), Value::String("menu".into()))] + .into_iter() + .collect(); + latest.sequence = 2; + latest.source_observation_id = "presence-2".into(); + broker.publish_replacing(latest, 101).unwrap(); + + let result = broker + .query_data( + QueryRequest { + caller: owner.clone(), + dataset_id: "game.presence.v1".into(), + record_id: None, + category: None, + selector: None, + delivery: Delivery::History, + page_size: 10, + cursor: None, + }, + &TestAuthorizer::new( + [], + [], + [SharingClass::Sensitive], + ["state".into()], + true, + true, + ), + 102, + ) + .unwrap(); + assert_eq!(result.records.len(), 1); + assert_eq!(result.records[0].sequence(), 2); + assert_eq!(result.records[0].fields()["state"], "menu"); + + let mut stale = first; + stale.sequence = 2; + stale.source_observation_id = "stale".into(); + assert!(matches!( + broker.publish_replacing(stale, 103), + Err(BrokerError::SequenceConflict(2)) + )); + } + + fn sequenced_publication( + owner: &PluginIdentity, + sequence: u64, + observation_id: &str, + session_id: &str, + fields: &[(&str, Value)], + ) -> Publication { + let mut publication = publication(owner, fields); + publication.dataset_id = "org.example.metrics.v1".into(); + publication.schema_id = "org.example.metrics.v1".into(); + publication.resource_id = "runtime-main".into(); + publication.observed_at = 1_700_000_000; + publication.sequence = sequence; + publication.source_observation_id = observation_id.into(); + publication.session_id = Some(session_id.into()); + publication.publisher = Some(PublisherMetadata { + declared_developer: "Example Developer".into(), + origin: "signed-package".into(), + package_version: "1.2.3".into(), + package_digest: vec![7; 32], + }); + publication + } + + fn selector( + categories: &[CommonDataCategory], + record_ids: &[String], + ) -> Option { + Some(CommonDataSelector { + categories: categories.iter().map(|category| *category as i32).collect(), + selected_record_ids: record_ids.to_vec(), + }) + } + + fn request( + caller: &PluginIdentity, + selector: Option, + delivery: Delivery, + page_size: usize, + cursor: Option, + ) -> QueryRequest { + QueryRequest { + caller: caller.clone(), + dataset_id: "performance.v1".into(), + record_id: None, + category: Some(CommonDataCategory::GamePerformanceHistory), + selector, + delivery, + page_size, + cursor, + } + } + + fn authorizer( + categories: impl IntoIterator, + record_ids: impl IntoIterator, + classes: impl IntoIterator, + fields: impl IntoIterator, + history: bool, + live: bool, + ) -> Arc { + Arc::new(TestAuthorizer::new( + categories, record_ids, classes, fields, history, live, + )) + } + + #[test] + fn denied_common_query_keeps_owner_private_records_available() { + let broker = DataBroker::new(); + let consumer = identity("consumer"); + let producer = identity("producer"); + broker + .publish( + publication(&consumer, &[("fps", serde_json::json!(60))]), + 100, + ) + .unwrap(); + broker + .publish( + publication(&producer, &[("fps", serde_json::json!(120))]), + 100, + ) + .unwrap(); + let authorizer = authorizer( + [], + [], + [SharingClass::Common], + ["fps".to_owned()], + true, + true, + ); + + let result = broker + .query_data( + request( + &consumer, + selector(&[CommonDataCategory::GamePerformanceHistory], &[]), + Delivery::Query, + 10, + None, + ), + authorizer.as_ref(), + 101, + ) + .unwrap(); + assert_eq!(result.records.len(), 1); + assert_eq!( + result.records[0].fields().get("fps"), + Some(&serde_json::json!(60)) + ); + assert_eq!(result.records[0].provenance().source, consumer); + } + + #[test] + fn category_and_selected_record_grants_are_independent_and_aliases_share_projection() { + let broker = DataBroker::new(); + let producer = identity("producer"); + let consumer = identity("consumer"); + let receipt = broker + .publish( + publication( + &producer, + &[ + ("fps", serde_json::json!(60)), + ("device_id", serde_json::json!("secret")), + ], + ), + 100, + ) + .unwrap(); + // Category is selected but denied. The independently selected record grant still allows + // this exact record, and the field mask is enforced through both public aliases. + let authorizer = authorizer( + [], + [receipt.record_id.clone()], + [SharingClass::Common], + ["fps".to_owned()], + true, + true, + ); + let selected = selector( + &[CommonDataCategory::GamePerformanceHistory], + &[receipt.record_id], + ); + let domain = broker + .query_domain( + request(&consumer, selected.clone(), Delivery::History, 10, None), + authorizer.as_ref(), + 101, + ) + .unwrap(); + let data = broker + .query_data( + request(&consumer, selected, Delivery::History, 10, None), + authorizer.as_ref(), + 101, + ) + .unwrap(); + for result in [&domain, &data] { + assert_eq!(result.records.len(), 1); + assert_eq!(result.records[0].fields().len(), 1); + assert!(result.records[0].fields().contains_key("fps")); + assert!(!result.records[0].fields().contains_key("device_id")); + } + } + + #[test] + fn cursor_is_fenced_by_new_publications_and_policy_revision() { + let broker = DataBroker::new(); + let producer = identity("producer"); + let consumer = identity("consumer"); + for fps in [60, 61] { + broker + .publish( + publication(&producer, &[("fps", serde_json::json!(fps))]), + 100, + ) + .unwrap(); + } + let authorizer = authorizer( + [CommonDataCategory::GamePerformanceHistory], + [], + [SharingClass::Common], + ["fps".to_owned()], + true, + true, + ); + let first = broker + .query_data( + request( + &consumer, + selector(&[CommonDataCategory::GamePerformanceHistory], &[]), + Delivery::History, + 1, + None, + ), + authorizer.as_ref(), + 101, + ) + .unwrap(); + let cursor = first.next_cursor.unwrap(); + broker + .publish( + publication(&producer, &[("fps", serde_json::json!(62))]), + 102, + ) + .unwrap(); + assert_eq!( + broker.query_data( + request( + &consumer, + selector(&[CommonDataCategory::GamePerformanceHistory], &[]), + Delivery::History, + 1, + Some(cursor), + ), + authorizer.as_ref(), + 103, + ), + Err(BrokerError::StaleCursor) + ); + } + + #[test] + fn revoked_subscription_discards_queued_events_and_is_fenced() { + let broker = DataBroker::new(); + let producer = identity("producer"); + let consumer = identity("consumer"); + broker + .publish( + publication(&producer, &[("fps", serde_json::json!(60))]), + 100, + ) + .unwrap(); + let authorizer = authorizer( + [CommonDataCategory::GamePerformanceHistory], + [], + [SharingClass::Common], + ["fps".to_owned()], + true, + true, + ); + let current_revision = broker.lock().revision; + let subscription = broker + .subscribe( + request( + &consumer, + selector(&[CommonDataCategory::GamePerformanceHistory], &[]), + Delivery::Live, + 10, + None, + ), + current_revision, + 4, + authorizer.clone(), + ) + .unwrap(); + broker + .publish( + publication(&producer, &[("fps", serde_json::json!(61))]), + 101, + ) + .unwrap(); + assert!(subscription.next(101).unwrap().is_some()); + broker + .publish( + publication(&producer, &[("fps", serde_json::json!(62))]), + 102, + ) + .unwrap(); + authorizer.revision.fetch_add(1, Ordering::SeqCst); + assert_eq!(subscription.next(103), Err(SubscriptionEnd::Revoked)); + assert_eq!(subscription.is_ended(), Some(SubscriptionEnd::Revoked)); + } + + #[test] + fn bounded_live_queue_closes_instead_of_dropping_or_growing() { + let broker = DataBroker::new(); + let producer = identity("producer"); + let consumer = identity("consumer"); + let authorizer = authorizer( + [CommonDataCategory::GamePerformanceHistory], + [], + [SharingClass::Common], + ["fps".to_owned()], + true, + true, + ); + let subscription = broker + .subscribe( + request( + &consumer, + selector(&[CommonDataCategory::GamePerformanceHistory], &[]), + Delivery::Live, + 10, + None, + ), + 0, + 1, + authorizer, + ) + .unwrap(); + for fps in [60, 61] { + broker + .publish( + publication(&producer, &[("fps", serde_json::json!(fps))]), + 100, + ) + .unwrap(); + } + assert_eq!(subscription.is_ended(), Some(SubscriptionEnd::FellBehind)); + assert_eq!(subscription.next(101), Err(SubscriptionEnd::FellBehind)); + } + + #[test] + fn onward_publication_keeps_filtered_fields_and_source_provenance_without_common_expansion() { + let broker = DataBroker::new(); + let producer = identity("producer"); + let consumer = identity("consumer"); + let next_consumer = identity("next-consumer"); + let receipt = broker + .publish( + publication( + &producer, + &[ + ("fps", serde_json::json!(60)), + ("device_id", serde_json::json!("secret")), + ], + ), + 100, + ) + .unwrap(); + let auth = authorizer( + [CommonDataCategory::GamePerformanceHistory], + [], + [SharingClass::Common], + ["fps".to_owned()], + true, + true, + ); + let projected = broker + .query_data( + request( + &consumer, + selector(&[CommonDataCategory::GamePerformanceHistory], &[]), + Delivery::Query, + 10, + None, + ), + auth.as_ref(), + 101, + ) + .unwrap() + .records + .into_iter() + .find(|record| record.record_id() == receipt.record_id) + .unwrap(); + assert_eq!(projected.fields().len(), 1); + let onward_receipt = broker + .publish_onward(&consumer, &projected, auth.as_ref(), 102) + .unwrap(); + { + let state = broker.lock(); + let onward = state.rows.back().unwrap(); + assert_eq!(onward.owner, consumer); + assert_eq!(onward.class, SharingClass::Custom); + assert_eq!(onward.provenance.source, producer); + assert_eq!(onward.provenance.forwarded_by, vec![identity("consumer")]); + assert_eq!(onward.fields.len(), 1); + assert!(onward.fields.contains_key("fps")); + assert!(!onward.fields.contains_key("device_id")); + } + // A broad Common category grant does not reveal the forwarded Custom record. + let next_auth = authorizer( + [CommonDataCategory::GamePerformanceHistory], + [], + [SharingClass::Common], + ["fps".to_owned()], + true, + true, + ); + let result = broker + .query_data( + request( + &next_consumer, + selector(&[CommonDataCategory::GamePerformanceHistory], &[]), + Delivery::Query, + 10, + None, + ), + next_auth.as_ref(), + 103, + ) + .unwrap(); + assert!( + result + .records + .iter() + .all(|record| record.record_id() != onward_receipt.record_id) + ); + } + + #[test] + fn host_authority_fields_and_common_records_without_category_are_refused() { + let broker = DataBroker::new(); + let producer = identity("producer"); + let mut forged = publication(&producer, &[("fps", serde_json::json!(60))]); + forged.fields.insert( + "provenance".into(), + serde_json::json!({"source":"attacker"}), + ); + assert_eq!(broker.publish(forged, 100), Err(BrokerError::ReservedField)); + + let mut uncategorized = publication(&producer, &[("fps", serde_json::json!(60))]); + uncategorized.category = None; + assert_eq!( + broker.publish(uncategorized, 100), + Err(BrokerError::InvalidPublication) + ); + } + + #[test] + fn sequenced_publications_are_idempotent_and_reject_out_of_order_observations() { + let broker = DataBroker::new(); + let producer = identity("producer"); + let first = sequenced_publication( + &producer, + 4, + "observation-4", + "session-producer", + &[("fps", serde_json::json!(60))], + ); + let receipt = broker.publish(first.clone(), 1_700_000_001).unwrap(); + assert!(!receipt.duplicate); + + let duplicate = broker.publish(first, 1_700_000_002).unwrap(); + assert!(duplicate.duplicate); + assert_eq!(duplicate.record_id, receipt.record_id); + assert_eq!(duplicate.revision, receipt.revision); + + let conflict = sequenced_publication( + &producer, + 4, + "different-observation", + "session-producer", + &[("fps", serde_json::json!(61))], + ); + assert_eq!( + broker.publish(conflict, 1_700_000_003), + Err(BrokerError::SequenceConflict(4)) + ); + + let next = sequenced_publication( + &producer, + 5, + "observation-5", + "session-producer", + &[("fps", serde_json::json!(62))], + ); + assert!(!broker.publish(next, 1_700_000_004).unwrap().duplicate); + + let out_of_order = sequenced_publication( + &producer, + 3, + "observation-3", + "session-producer", + &[("fps", serde_json::json!(59))], + ); + assert_eq!( + broker.publish(out_of_order, 1_700_000_005), + Err(BrokerError::SequenceConflict(5)) + ); + } + + #[test] + fn closing_a_publisher_session_removes_records_and_fences_watches() { + let broker = DataBroker::new(); + let producer = identity("producer"); + let receipt = broker + .publish( + sequenced_publication( + &producer, + 1, + "observation-1", + "session-producer", + &[("fps", serde_json::json!(60))], + ), + 1_700_000_001, + ) + .unwrap(); + let authorizer: Arc = + authorizer([], [], [], Vec::::new(), false, false); + let watch = broker + .subscribe( + request( + &producer, + selector(&[CommonDataCategory::GamePerformanceHistory], &[]), + Delivery::Live, + 10, + None, + ), + 0, + 10, + authorizer, + ) + .unwrap(); + + assert_eq!(broker.close_session("session-producer"), 1); + assert_eq!(watch.is_ended(), Some(SubscriptionEnd::FellBehind)); + assert_eq!(broker.close_session("session-producer"), 0); + assert_eq!(broker.expire(1_700_000_002), 0); + assert!(receipt.revision < 3); + } + + #[test] + fn publication_structural_budgets_apply_at_the_broker_boundary() { + let broker = DataBroker::new(); + let producer = identity("producer"); + + let mut too_deep = serde_json::json!("leaf"); + for _ in 0..=MAX_FIELD_DEPTH { + too_deep = serde_json::json!({"nested": too_deep}); + } + let deep = publication(&producer, &[("value", too_deep)]); + assert_eq!( + broker.publish(deep, 100), + Err(BrokerError::InvalidPublication) + ); + + let too_many_items = serde_json::json!({ + "values": vec![serde_json::Value::Null; MAX_FIELD_ITEMS], + }); + let oversized_shape = publication(&producer, &[("value", too_many_items)]); + assert_eq!( + broker.publish(oversized_shape, 100), + Err(BrokerError::InvalidPublication) + ); + + let invalid_key = publication(&producer, &[("bad\nkey", serde_json::json!(true))]); + assert_eq!( + broker.publish(invalid_key, 100), + Err(BrokerError::InvalidPublication) + ); + + let forged_execution = publication(&producer, &[("command", serde_json::json!("run"))]); + assert_eq!( + broker.publish(forged_execution, 100), + Err(BrokerError::ReservedField) + ); + } + + fn durable_row(owner: &PluginIdentity, record_id: &str, pool_revision: u64) -> DurableRecord { + DurableRecord { + record_id: record_id.into(), + owner: owner.clone(), + dataset_id: "org.example.metrics.v1".into(), + category: None, + class: SharingClass::Custom, + schema_id: "org.example.metrics.v1".into(), + schema_version: 1, + fields: [("fps".to_owned(), serde_json::json!(60))] + .into_iter() + .collect(), + opaque_payload: Vec::new(), + resource_id: String::new(), + observed_at: 1_700_000_000, + received_at: 1_700_000_000, + published_at: 1_700_000_000, + sequence: 0, + source_observation_id: String::new(), + expires_at: None, + revision: 1, + pool_revision, + provenance: Provenance { + source: owner.clone(), + forwarded_by: Vec::new(), + declared_developer: String::new(), + origin: String::new(), + package_version: String::new(), + package_digest: Vec::new(), + source_record_ids: Vec::new(), + }, + } + } + + #[test] + fn a_restarted_broker_resumes_the_persisted_pool_revision_for_watches() { + let broker = DataBroker::new(); + let consumer = identity("consumer"); + assert_eq!(broker.revision(), 0, "a new broker starts empty"); + assert_eq!(broker.observe_pool_revision(7), 7); + // Only ever forward: a later list of an older page keeps the higher revision. + assert_eq!(broker.observe_pool_revision(3), 7); + + let request = request(&consumer, None, Delivery::Live, 10, None); + let authorizer: Arc = + authorizer([], [], [], Vec::::new(), false, false); + // The revision a post-restart list returned is a valid watch position. + broker + .subscribe(request.clone(), 7, 10, authorizer.clone()) + .unwrap(); + // A position older than the persisted sequence cannot silently resume. + assert!(matches!( + broker.subscribe(request, 6, 10, authorizer), + Err(BrokerError::StaleSubscription) + )); + } + + #[test] + fn a_durable_publication_never_dispatches_below_its_pool_revision() { + let broker = DataBroker::new(); + let producer = identity("producer"); + // A restarted host whose broker is still empty accepts a write the pool sequenced at 5. + assert_eq!( + broker.note_durable(durable_row(&producer, "durable-1", 5), 1_000), + 5 + ); + // Once ahead, the broker keeps its own monotonic order rather than moving backwards. + assert_eq!( + broker.note_durable(durable_row(&producer, "durable-2", 3), 1_001), + 6 + ); + assert_eq!(broker.revision(), 6); + assert_eq!( + broker.note_durable(durable_row(&producer, "durable-3", 9), 1_002), + 9 + ); + } +} diff --git a/crates/app/src/plugin_host/shared_pool.rs b/crates/app/src/plugin_host/shared_pool.rs new file mode 100644 index 000000000..2083f4f85 --- /dev/null +++ b/crates/app/src/plugin_host/shared_pool.rs @@ -0,0 +1,585 @@ +//! Host-owned worker for the durable public shared-data pool. +//! +//! A durable publication is written to the platform [`SharedDataStore`], never to the in-memory +//! broker. The store is opened lazily on the storage worker the first time a publication is +//! accepted, so a host that only sees session-only publications creates no file. Owner scopes, +//! provenance and the pool location come from the authenticated host context; a plugin RPC never +//! supplies or receives them. Every SQLite call runs on a blocking worker, never the UI thread. +//! +//! Reads go the other way: the worker loads the requested rows and hands them to the broker, +//! which applies the same owner/grant checks and field projections as a session record. A read +//! never creates the pool file; a host without one simply has no durable rows. + +use super::grants::PluginIdentity; +use super::shared_data::{DurableRecord, Provenance}; +use super::sharing_policy::SharingClass; +use gamenode_platform::plugin_shared_data::{ + ArchiveOutcome, MigrationOutcome, MigrationRevertOutcome, MigrationSource, OwnerScope, + OwnerUsage, PruneOutcome, RecordProvenance, RecordWrite, SharedDataError, SharedDataStore, + SharedRecord, WriteOutcome, +}; +use gamenode_plugin_protocol::proto::CommonDataCategory; +use serde_json::Map; +use std::path::PathBuf; +use std::sync::Arc; +use tonic::Status; + +/// The durable public pool. A disabled pool refuses durable publications and reads as empty; it +/// never downgrades a publication to session-only. +pub struct DurableSharedPool { + /// The application data folder the pool file lives in; absent when the host has none. + dir: Option, + store: Arc>>, +} + +impl Default for DurableSharedPool { + fn default() -> Self { + Self::disabled() + } +} + +impl DurableSharedPool { + /// A pool that refuses durable publications, for hosts and tests without a data folder. + pub fn disabled() -> Self { + Self { + dir: None, + store: Arc::default(), + } + } + + /// The application data folder holding the pool file. Host administration measures the file + /// here; no plugin reply ever carries this path. + pub(crate) fn data_dir(&self) -> Option<&std::path::Path> { + self.dir.as_deref() + } + + /// Durable records go below `dir` (the application data folder). + pub fn new(dir: impl Into) -> Self { + Self { + dir: Some(dir.into()), + store: Arc::default(), + } + } + + /// A host-assigned publication ready for the durable pool. Returns the accepted record as the + /// broker may project it, so a live watch can deliver the same publication. + pub(crate) async fn persist( + self: &Arc, + write: DurableWrite, + ) -> Result { + let dir = self.dir.clone().ok_or_else(|| { + Status::failed_precondition("durable shared data is unavailable on this host") + })?; + let mut store = self.store.clone().lock_owned().await; + tokio::task::spawn_blocking(move || { + if store.is_none() { + *store = Some(SharedDataStore::open(&dir).map_err(pool_status)?); + } + let store = store.as_mut().expect("the pool was just opened"); + let outcome = store.write( + write.owner, + RecordWrite { + dataset_id: &write.dataset_id, + category: None, + class: SharingClass::Custom.as_name(), + schema_id: &write.schema_id, + schema_version: write.schema_version, + fields_json: &write.fields_json, + opaque_payload: &write.opaque_payload, + resource_id: write.resource_id.as_deref(), + observed_at: write.observed_at, + sequence: write.sequence, + source_observation_id: &write.source_observation_id, + expires_at: write.expires_at, + now: write.now, + provenance: &write.provenance, + expected_revision: None, + }, + ) + .map_err(pool_status)?; + match outcome { + WriteOutcome::Stored(receipt) => durable_record(receipt.record), + WriteOutcome::Conflict { current_revision } => { + Err(Status::failed_precondition(format!( + "published shared record changed concurrently; current revision is {current_revision}" + ))) + } + WriteOutcome::OverQuota { .. } => Err(Status::resource_exhausted( + "shared-data retention quota is exhausted", + )), + } + }) + .await + .map_err(|_| Status::unavailable("the durable shared-data worker is unavailable"))? + } + + /// One durable record by host id across every producer. `None` when the pool has no such + /// unexpired record or this host never persisted one. + pub(crate) async fn get_any( + self: &Arc, + record_id: String, + now: i64, + ) -> Result, Status> { + let Some(Some(record)) = self + .read(move |store| store.get_any(&record_id, now)) + .await? + else { + return Ok(None); + }; + durable_record(record).map(Some) + } + + /// Every producer's unexpired records of one dataset in stable receipt order, together with + /// the persisted pool sequence the page was read at. Both come from one worker call, so a list + /// revision can seed the broker before the page is authorized and projected. + pub(crate) async fn list_dataset_any( + self: &Arc, + dataset_id: String, + now: i64, + ) -> Result<(Vec, u64), Status> { + let Some((records, pool_revision)) = self + .read(move |store| { + let records = store.list_dataset_any(&dataset_id, now)?; + Ok((records, store.pool_revision()?)) + }) + .await? + else { + return Ok((Vec::new(), 0)); + }; + let records = records + .into_iter() + .map(durable_record) + .collect::, _>>()?; + Ok((records, pool_revision)) + } + + /// The persisted pool sequence, or zero when this host never persisted a record. Reads never + /// create the pool file. + pub(crate) async fn pool_revision(self: &Arc) -> Result { + Ok(self.read(|store| store.pool_revision()).await?.unwrap_or(0)) + } + + /// Logical usage and effective retention limits of one producer, read on the storage worker. + /// `None` means this host never persisted a record; a read never creates the pool. + pub(crate) async fn usage( + self: &Arc, + owner: OwnerScope, + now: i64, + ) -> Result, Status> { + self.read(move |store| store.usage(&owner, now)).await + } + + /// Removes one producer's durable records and reports the bytes actually reclaimed. Another + /// owner's rows and the private plugin stores are untouched. `None` means this host never + /// persisted a record. + pub(crate) async fn delete_owner( + self: &Arc, + owner: OwnerScope, + now: i64, + ) -> Result, Status> { + self.mutate_opened(move |store| store.delete_owner(&owner, now)) + .await + } + + /// Expires and prunes one producer's records under its effective limits. User-protected and + /// archived rows stay. `None` means this host never persisted a record. + pub(crate) async fn prune_owner( + self: &Arc, + owner: OwnerScope, + now: i64, + ) -> Result, Status> { + self.mutate_opened(move |store| store.prune(&owner, now)) + .await + } + + /// One producer's live records and the counts a publisher migration cannot copy. `None` means + /// this host never persisted a record; a preview never creates the pool. + pub(crate) async fn migration_source( + self: &Arc, + owner: OwnerScope, + now: i64, + ) -> Result, Status> { + self.read(move |store| store.migration_source(&owner, now)) + .await + } + + /// Copies one old publisher identity's durable records to its re-trusted successor after a + /// reviewed confirmation. The source rows stay and the copies keep the original provenance. + /// `None` means this host never persisted a record. + pub(crate) async fn migrate_owner( + self: &Arc, + source: OwnerScope, + target: OwnerScope, + record_ids: Vec, + now: i64, + ) -> Result, Status> { + self.mutate_opened(move |store| store.migrate_records(&source, &target, &record_ids, now)) + .await + } + + /// Removes one migration's durable copies from the new publisher identity after a reviewed + /// rollback. `None` means this host never persisted a record. + pub(crate) async fn revert_migrated_owner( + self: &Arc, + target: OwnerScope, + source_publisher_fingerprint: String, + source_plugin_id: String, + now: i64, + ) -> Result, Status> { + self.mutate_opened(move |store| { + store.revert_migrated( + &target, + &source_publisher_fingerprint, + &source_plugin_id, + now, + ) + }) + .await + } + + /// Reclaims one producer's archived, unprotected records in a reviewed host cleanup. `None` + /// means this host never persisted a record. + pub(crate) async fn reclaim_archived_owner( + self: &Arc, + owner: OwnerScope, + ) -> Result, Status> { + self.mutate_opened(move |store| store.reclaim_archived_owner(&owner)) + .await + } + + /// Makes one producer's durable records inert for uninstall retention. `None` means this host + /// never persisted a record. Another owner's rows and the private plugin stores are untouched. + pub(crate) async fn archive_owner( + self: &Arc, + owner: OwnerScope, + now: i64, + ) -> Result, Status> { + self.mutate_opened(move |store| store.archive_owner(&owner, now)) + .await + } + + /// Restores one producer's archived records after an explicit host review. `None` means this + /// host never persisted a record. A plugin RPC can never reach this decision. + pub(crate) async fn reuse_archived_owner( + self: &Arc, + owner: OwnerScope, + now: i64, + ) -> Result, Status> { + self.mutate_opened(move |store| store.reuse_archived_owner(&owner, now)) + .await + } + + /// Runs one blocking mutation on the storage worker after opening an existing pool. An absent + /// pool is not created and answers `None`. + async fn mutate_opened(self: &Arc, mutate: F) -> Result, Status> + where + T: Send + 'static, + F: FnOnce(&mut SharedDataStore) -> Result + Send + 'static, + { + let Some(dir) = self.dir.clone() else { + return Ok(None); + }; + let mut store = self.store.clone().lock_owned().await; + tokio::task::spawn_blocking(move || { + if store.is_none() { + match SharedDataStore::open_existing(&dir).map_err(pool_status)? { + Some(opened) => *store = Some(opened), + None => return Ok(None), + } + } + let store = store.as_mut().expect("the pool is open"); + mutate(store).map(Some).map_err(pool_status) + }) + .await + .map_err(|_| Status::unavailable("the durable shared-data worker is unavailable"))? + } + + /// Runs one blocking pool read on the storage worker. `None` means this host has no pool + /// file; a read never creates one. + async fn read(self: &Arc, read: F) -> Result, Status> + where + T: Send + 'static, + F: FnOnce(&SharedDataStore) -> Result + Send + 'static, + { + let Some(dir) = self.dir.clone() else { + return Ok(None); + }; + let mut store = self.store.clone().lock_owned().await; + tokio::task::spawn_blocking(move || { + if store.is_none() { + match SharedDataStore::open_existing(&dir).map_err(pool_status)? { + Some(opened) => *store = Some(opened), + None => return Ok(None), + } + } + let store = store.as_ref().expect("the pool is open"); + read(store).map(Some).map_err(pool_status) + }) + .await + .map_err(|_| Status::unavailable("the durable shared-data worker is unavailable"))? + } +} + +/// One fully resolved durable publication. All values are owned so the write can leave this task. +pub(crate) struct DurableWrite { + pub owner: OwnerScope, + pub dataset_id: String, + pub schema_id: String, + pub schema_version: u32, + pub fields_json: String, + pub opaque_payload: Vec, + pub resource_id: Option, + pub observed_at: i64, + pub sequence: u64, + pub source_observation_id: String, + pub expires_at: Option, + pub now: i64, + pub provenance: RecordProvenance, +} + +/// Converts one stored row into the broker's durable input. A malformed row cannot come from this +/// host's publication path, so it fails closed instead of being silently skipped or exposed. +fn durable_record(record: SharedRecord) -> Result { + let class = SharingClass::from_name(&record.class) + .ok_or_else(|| Status::unavailable("the durable shared-data pool is unavailable"))?; + let fields = if record.fields_json.is_empty() { + Map::new() + } else { + serde_json::from_str(&record.fields_json) + .map_err(|_| Status::unavailable("the durable shared-data pool is unavailable"))? + }; + let source = PluginIdentity { + plugin_id: record.provenance.source_plugin_id, + publisher_fingerprint: record.provenance.source_publisher_fingerprint, + profile_id: record.provenance.source_profile_id, + }; + Ok(DurableRecord { + record_id: record.record_id, + owner: source.clone(), + dataset_id: record.dataset_id, + category: record + .category + .and_then(|category| CommonDataCategory::try_from(category).ok()), + class, + schema_id: record.schema_id, + schema_version: record.schema_version, + fields, + opaque_payload: record.opaque_payload, + resource_id: record.resource_id.unwrap_or_default(), + observed_at: record.observed_at, + received_at: record.received_at, + published_at: record.updated_at, + sequence: record.sequence, + source_observation_id: record.source_observation_id, + expires_at: record.expires_at, + revision: record.revision, + pool_revision: record.pool_revision, + provenance: Provenance { + source, + forwarded_by: Vec::new(), + declared_developer: record.provenance.declared_developer, + origin: record.provenance.origin, + package_version: record.provenance.package_version, + package_digest: record.provenance.package_digest, + source_record_ids: Vec::new(), + }, + }) +} + +/// Maps a store failure to a status without disclosing a path. +fn pool_status(error: SharedDataError) -> Status { + match error { + SharedDataError::RecordTooLarge => { + Status::resource_exhausted("publication exceeds the size limit") + } + SharedDataError::InvalidRecord => Status::invalid_argument("shared record is invalid"), + SharedDataError::InvalidOwner => { + Status::failed_precondition("shared-data owner scope is invalid") + } + SharedDataError::InvalidMigration => { + Status::failed_precondition("a publisher migration needs two different identities") + } + SharedDataError::StaleProfileEpoch => { + Status::failed_precondition("shared-data owner scope is stale") + } + SharedDataError::ArchivedRecordExists => Status::failed_precondition( + "archived shared data requires a host reuse review before it can be replaced", + ), + SharedDataError::Open(_) + | SharedDataError::Database(_) + | SharedDataError::NewerVersion + | SharedDataError::ForeignDatabase + | SharedDataError::MigrationFailed { .. } => { + Status::unavailable("the durable shared-data pool is unavailable") + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::fs; + + fn owner(byte: u8) -> OwnerScope { + OwnerScope::new([byte; 32], 1).unwrap() + } + + fn write(plugin: &str, resource: &str, fields_json: &str) -> DurableWrite { + DurableWrite { + owner: owner(if plugin == "producer" { 1 } else { 2 }), + dataset_id: "org.example.catalog".to_owned(), + schema_id: "org.example.catalog.v1".to_owned(), + schema_version: 1, + fields_json: fields_json.to_owned(), + opaque_payload: Vec::new(), + resource_id: Some(resource.to_owned()), + observed_at: 100, + sequence: 1, + source_observation_id: "observation-1".to_owned(), + expires_at: None, + now: 100, + provenance: RecordProvenance { + source_plugin_id: plugin.to_owned(), + source_publisher_fingerprint: format!("publisher-{plugin}"), + source_profile_id: "profile-1".to_owned(), + declared_developer: "Example Developer".to_owned(), + origin: "registry".to_owned(), + package_version: "1.2.3".to_owned(), + package_digest: vec![7; 32], + }, + } + } + + #[tokio::test] + async fn usage_and_deletion_are_owner_scoped_and_never_touch_private_files() { + let dir = tempfile::TempDir::new().unwrap(); + let pool = Arc::new(DurableSharedPool::new(dir.path())); + let producer = owner(1); + let other = owner(2); + let producer_record = pool + .persist(write("producer", "disc-1", r#"{"title":"Dolphin"}"#)) + .await + .unwrap(); + let other_record = pool + .persist(write("other", "disc-2", r#"{"title":"Other"}"#)) + .await + .unwrap(); + assert_ne!(producer_record.record_id, other_record.record_id); + + let usage = pool.usage(producer, 110).await.unwrap().unwrap(); + assert_eq!(usage.records, 1); + let expected_bytes = usage.logical_bytes; + assert!(expected_bytes > 0); + let other_usage = pool.usage(other, 110).await.unwrap().unwrap(); + assert_eq!(other_usage.records, 1); + let expected_other_bytes = other_usage.logical_bytes; + + // Representative private stores beside the public pool must survive the user cleanup. + let storage_dir = dir + .path() + .join("plugin-data") + .join("publisher") + .join("plugin"); + fs::create_dir_all(&storage_dir).unwrap(); + let storage_file = storage_dir.join("storage.sqlite3"); + let persistence_file = dir.path().join("plugin-persistence.sqlite3"); + fs::write(&storage_file, b"private-storage").unwrap(); + fs::write(&persistence_file, b"private-persistence").unwrap(); + + let deleted = pool.delete_owner(producer, 120).await.unwrap().unwrap(); + assert_eq!(deleted.removed_records, 1); + assert_eq!(deleted.reclaimed_bytes, expected_bytes); + assert_eq!(pool.usage(producer, 120).await.unwrap().unwrap().records, 0); + let remaining = pool.usage(other, 120).await.unwrap().unwrap(); + assert_eq!(remaining.records, 1); + assert_eq!(remaining.logical_bytes, expected_other_bytes); + assert_eq!(fs::read(&storage_file).unwrap(), b"private-storage"); + assert_eq!(fs::read(&persistence_file).unwrap(), b"private-persistence"); + assert_eq!( + pool.delete_owner(producer, 130) + .await + .unwrap() + .unwrap() + .removed_records, + 0 + ); + } + + #[tokio::test] + async fn archiving_and_reuse_are_owner_scoped_and_leave_private_files_alone() { + let dir = tempfile::TempDir::new().unwrap(); + let pool = Arc::new(DurableSharedPool::new(dir.path())); + let producer = owner(1); + let other = owner(2); + let producer_record = pool + .persist(write("producer", "disc-1", r#"{"title":"Dolphin"}"#)) + .await + .unwrap(); + pool.persist(write("other", "disc-2", r#"{"title":"Other"}"#)) + .await + .unwrap(); + + let storage_dir = dir + .path() + .join("plugin-data") + .join("publisher") + .join("plugin"); + fs::create_dir_all(&storage_dir).unwrap(); + let storage_file = storage_dir.join("storage.sqlite3"); + fs::write(&storage_file, b"private-storage").unwrap(); + + let live_before = pool.usage(producer, 110).await.unwrap().unwrap(); + assert_eq!(live_before.records, 1); + assert_eq!(live_before.archived_records, 0); + let archived = pool.archive_owner(producer, 120).await.unwrap().unwrap(); + assert_eq!(archived.records, 1); + assert!( + pool.get_any(producer_record.record_id.clone(), 120) + .await + .unwrap() + .is_none(), + "an archived row is not readable across owners" + ); + let usage = pool.usage(producer, 120).await.unwrap().unwrap(); + assert_eq!(usage.records, 0); + assert_eq!(usage.archived_records, 1); + assert_eq!(usage.archived_logical_bytes, live_before.logical_bytes); + let other_usage = pool.usage(other, 120).await.unwrap().unwrap(); + assert_eq!(other_usage.records, 1); + assert_eq!(other_usage.archived_records, 0); + + let error = pool + .persist(write("producer", "disc-1", r#"{"title":"Replacement"}"#)) + .await + .unwrap_err(); + assert_eq!(error.code(), tonic::Code::FailedPrecondition); + + let reused = pool + .reuse_archived_owner(producer, 130) + .await + .unwrap() + .unwrap(); + assert_eq!(reused.records, 1); + assert_eq!(pool.usage(producer, 130).await.unwrap().unwrap().records, 1); + let reused_record = pool + .get_any(producer_record.record_id, 130) + .await + .unwrap() + .unwrap(); + assert_eq!( + reused_record.fields.get("title"), + Some(&serde_json::Value::String("Dolphin".to_owned())) + ); + assert_eq!(fs::read(&storage_file).unwrap(), b"private-storage"); + assert_eq!(pool.usage(other, 130).await.unwrap().unwrap().records, 1); + } + + #[tokio::test] + async fn reading_usage_of_an_absent_pool_creates_nothing() { + let dir = tempfile::TempDir::new().unwrap(); + let pool = Arc::new(DurableSharedPool::new(dir.path())); + assert!(pool.usage(owner(1), 100).await.unwrap().is_none()); + assert!(pool.delete_owner(owner(1), 100).await.unwrap().is_none()); + assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 0); + } +} diff --git a/crates/app/src/plugin_host/shared_resources.rs b/crates/app/src/plugin_host/shared_resources.rs new file mode 100644 index 000000000..fa1544320 --- /dev/null +++ b/crates/app/src/plugin_host/shared_resources.rs @@ -0,0 +1,967 @@ +//! Shared emulator save resources: declarations, review scope and revision-bound consent. +//! +//! A save profile may declare that several library entries use one emulator backing folder (a +//! memory card, for example). The plugin proposes an alias and an approved folder handle; the host +//! resolves the canonical backing folder and the complete affected installation set. The host +//! refuses duplicate aliases, duplicate backing folders and nested or partially overlapping +//! resources, because separate lease keys would otherwise let one write bypass another. +//! +//! Consent lives beside the plugin's durable data, never in plugin RPC. It is bound to the exact +//! resolved declaration and the exact host-resolved affected set. Changing the backing folder, +//! runtime binding or affected set makes the stored decision stale; a use then asks for a fresh +//! review instead of widening itself. + +use std::collections::BTreeSet; +use std::path::Path; +use std::sync::Arc; + +use gamenode_platform::plugin_storage::{FileApproval, SaveProfileRow, operation}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use tonic::Status; + +use super::files::FileAccess; +use super::library::{LibraryFeed, Scope}; +use super::resource_leases::ResourceLeaseKey; +use super::saves; +use super::storage::{Namespace, PluginStorage}; +use gamenode_platform::plugin_storage::SharedResourceConsentRow; + +/// The most shared resources one profile may declare. +pub const MAX_SHARED_RESOURCES: usize = 8; +/// The longest resource alias, in bytes. +pub const MAX_RESOURCE_ID_BYTES: usize = 128; + +/// One library entry in a shared-resource scope. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AffectedEntry { + pub entry_key: String, + pub installation_id: String, + pub game_id: String, + pub name: String, +} + +/// A host-resolved declaration stored on a save profile. `backing_path` is host-only: it never +/// reaches a plugin reply or a foreign profile. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SharedResource { + pub resource_id: String, + pub approval_id: String, + pub path: Vec, + pub display_name: String, + pub backing_path: String, + /// The approved runtime whose executable identity the host inspects for external use. + pub runtime_id: String, +} + +pub fn resources_json(resources: &[SharedResource]) -> String { + serde_json::to_string(resources).unwrap_or_else(|_| "[]".into()) +} + +pub fn resources_from_json(text: &str) -> Vec { + serde_json::from_str(text).unwrap_or_default() +} + +fn refuse(message: impl Into) -> Status { + Status::invalid_argument(message.into()) +} + +fn unavailable(message: impl Into) -> Status { + Status::unavailable(message.into()) +} + +fn check_resource_id(text: &str) -> Result { + if text.is_empty() + || text.len() > MAX_RESOURCE_ID_BYTES + || !text + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || b"._-".contains(&byte)) + { + return Err(refuse(format!( + "resource_id is 1 to {MAX_RESOURCE_ID_BYTES} bytes of letters, digits, '.', '_' and '-'" + ))); + } + Ok(text.to_owned()) +} + +fn hash_part(digest: &mut Sha256, part: &[u8]) { + digest.update((part.len() as u64).to_be_bytes()); + digest.update(part); +} + +/// The host-canonical declaration fingerprint. It deliberately excludes display names and +/// profile revision: a rename does not invalidate consent, but a changed handle, backing folder or +/// runtime binding does. +pub fn declaration_fingerprint(resource: &SharedResource) -> String { + let mut digest = Sha256::new(); + digest.update(b"gamenode.shared-save-resource.declaration.v1\0"); + hash_part(&mut digest, resource.resource_id.as_bytes()); + hash_part(&mut digest, resource.approval_id.as_bytes()); + for component in &resource.path { + hash_part(&mut digest, component.as_bytes()); + } + digest.update([0]); + hash_part(&mut digest, resource.backing_path.as_bytes()); + hash_part(&mut digest, resource.runtime_id.as_bytes()); + hex(&digest.finalize()) +} + +/// The stable identity of an affected set: installation and GameNode game, never a display name. +pub fn scope_fingerprint(scope: &[AffectedEntry]) -> String { + let mut entries: Vec<(&str, &str)> = scope + .iter() + .map(|entry| (entry.installation_id.as_str(), entry.game_id.as_str())) + .collect(); + entries.sort(); + let mut digest = Sha256::new(); + digest.update(b"gamenode.shared-save-resource.scope.v1\0"); + for (installation, game) in entries { + hash_part(&mut digest, installation.as_bytes()); + hash_part(&mut digest, game.as_bytes()); + } + hex(&digest.finalize()) +} + +fn hex(bytes: &[u8]) -> String { + bytes.iter().map(|byte| format!("{byte:02x}")).collect() +} + +/// The complete current scope of a standing approval. Missing durable identities fail closed: a +/// review must name every affected game and installation. +pub fn scope_of(feed: &LibraryFeed, approval: &FileApproval) -> Result, Status> { + if approval.affected.is_empty() { + return Err(Status::failed_precondition( + "the shared resource has no resolved affected games", + )); + } + let mut scope = Vec::with_capacity(approval.affected.len()); + for key in &approval.affected { + let (_, entry) = feed.projected_entry(key).ok_or_else(|| { + unavailable("the affected game set is not fully resolved; try again later") + })?; + let name = entry + .display_name + .clone() + .unwrap_or_else(|| entry.name.clone()); + scope.push(AffectedEntry { + entry_key: key.clone(), + installation_id: entry.installation_id, + game_id: entry.game_id.map(|id| id.to_string()).unwrap_or_default(), + name, + }); + } + scope.sort_by(|a, b| a.entry_key.cmp(&b.entry_key)); + Ok(scope) +} + +/// The canonical absolute folder below an approval. Symlinks are resolved once; a missing folder +/// fails closed. +pub fn backing_path(approval: &FileApproval, path: &[String]) -> Result { + let root = std::fs::canonicalize(&approval.root) + .map_err(|_| Status::failed_precondition("the approved backing folder changed"))?; + let mut target = root.clone(); + for component in path { + if !gamenode_platform::plugin_files::valid_component(component) { + return Err(Status::permission_denied( + "the shared resource path is not a plain relative path", + )); + } + target.push(component); + } + let canonical = std::fs::canonicalize(&target) + .map_err(|_| Status::failed_precondition("the approved backing folder is unavailable"))?; + if !canonical.starts_with(&root) || !canonical.is_dir() { + return Err(Status::permission_denied( + "the shared resource is outside its approved folder", + )); + } + canonical + .to_str() + .map(str::to_owned) + .ok_or_else(|| Status::failed_precondition("the approved path is not valid Unicode")) +} + +fn overlaps(left: &str, right: &str) -> bool { + let (left, right) = (Path::new(left), Path::new(right)); + left.starts_with(right) || right.starts_with(left) +} + +/// Resolves a profile's proposed declarations against approvals in this plugin/profile namespace. +/// Runs on the namespace worker. +#[allow(clippy::too_many_arguments)] // Resolution inputs from the session, profile and declarations. +pub(crate) fn resolve_declarations( + files: &FileAccess, + feed: &LibraryFeed, + namespace: &mut Namespace<'_>, + session: &str, + profile_id: Option<&str>, + installation_id: &str, + runtime_id: &str, + declarations: &[gamenode_plugin_protocol::proto::SharedResourceDeclaration], + existing: &[SaveProfileRow], +) -> Result, Status> { + if declarations.is_empty() { + return Ok(Vec::new()); + } + if declarations.len() > MAX_SHARED_RESOURCES { + return Err(refuse(format!( + "a profile declares at most {MAX_SHARED_RESOURCES} shared resources" + ))); + } + if runtime_id.is_empty() { + return Err(Status::failed_precondition( + "a shared resource requires the profile's approved runtime binding", + )); + } + let (entry_key, _) = feed + .target( + &Scope { + own_provider: String::new(), + read_all: true, + provider_filter: None, + }, + installation_id, + ) + .ok_or_else(|| Status::failed_precondition("the profile installation is unavailable"))?; + + let mut resolved: Vec = Vec::with_capacity(declarations.len()); + for declaration in declarations { + let resource_id = check_resource_id(&declaration.resource_id)?; + if declaration.approved_resource_handle.is_empty() { + return Err(refuse( + "a shared resource requires an approved resource handle", + )); + } + let display_name = saves::check_display_name(&declaration.display_name)?; + let opened = files + .open_handle(session, &declaration.approved_resource_handle) + .ok_or_else(|| Status::not_found("file handle not found"))?; + // Re-derive the standing approval, including its complete affected set and volume. + let opened = super::resources::files::open_approval( + files, + feed, + namespace, + &opened.0, + opened.1, + operation::READ, + )?; + if opened.approval.kind == "library" { + return Err(Status::permission_denied( + "a shared resource needs an approved folder, not a library root", + )); + } + if !opened.approval.affected.iter().any(|key| key == &entry_key) { + return Err(Status::permission_denied( + "the approved folder does not affect this profile's installation", + )); + } + let entry = opened + .confined + .stat(&opened.path) + .map_err(super::resources::files::file_status)?; + if !entry.directory { + return Err(refuse("a shared resource must be an approved folder")); + } + let backing_path = backing_path(&opened.approval, &opened.path)?; + let resource = SharedResource { + resource_id, + approval_id: opened.approval.id, + path: opened.path, + display_name, + backing_path, + runtime_id: runtime_id.to_owned(), + }; + if resolved.iter().any(|other| { + other.resource_id == resource.resource_id + || other.backing_path == resource.backing_path + || overlaps(&other.backing_path, &resource.backing_path) + }) { + return Err(refuse( + "shared resources must have distinct aliases and non-overlapping backing folders", + )); + } + resolved.push(resource); + } + + for row in existing + .iter() + .filter(|row| Some(row.id.as_str()) != profile_id) + { + for other in resources_from_json(&row.shared_resources) { + for resource in &resolved { + if other.resource_id == resource.resource_id + && other.backing_path != resource.backing_path + { + return Err(refuse(format!( + "resource_id {:?} already names another backing folder", + resource.resource_id + ))); + } + if other.backing_path == resource.backing_path + && other.resource_id != resource.resource_id + { + return Err(refuse( + "a backing folder must keep the same resource_id in every profile", + )); + } + if overlaps(&other.backing_path, &resource.backing_path) { + return Err(refuse( + "shared resources must not overlap another profile's backing folder", + )); + } + } + } + } + Ok(resolved) +} + +/// Why a declaration's current state needs review. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ConsentState { + Pending, + Current, + Stale, +} + +impl ConsentState { + pub fn as_str(self) -> &'static str { + match self { + Self::Pending => "pending", + Self::Current => "current", + Self::Stale => "stale", + } + } + + pub fn proto(self) -> i32 { + match self { + Self::Pending => gamenode_plugin_protocol::proto::SharedResourceConsent::Pending as i32, + Self::Current => gamenode_plugin_protocol::proto::SharedResourceConsent::Current as i32, + Self::Stale => gamenode_plugin_protocol::proto::SharedResourceConsent::Stale as i32, + } + } +} + +/// A declaration together with the host-resolved state needed to review or use it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct PreparedSharedResource { + pub declaration: SharedResource, + pub scope: Vec, + pub consent: ConsentState, + pub lease_key: ResourceLeaseKey, +} + +/// Re-resolves one profile's stored declarations, requires a current consent for each and returns +/// the host-owned lease keys. This is the only path that may authorize use. +pub(crate) fn prepare_for_use( + files: &FileAccess, + feed: &LibraryFeed, + namespace: &mut Namespace<'_>, + profile: &SaveProfileRow, +) -> Result, Status> { + let declarations = resources_from_json(&profile.shared_resources); + if declarations.is_empty() { + return Ok(Vec::new()); + } + if profile.runtime_id.is_empty() { + return Err(Status::failed_precondition( + "the shared resource has no approved runtime binding", + )); + } + let mut prepared = Vec::with_capacity(declarations.len()); + for declaration in declarations { + if declaration.runtime_id != profile.runtime_id { + return Err(Status::failed_precondition( + "the shared resource runtime binding changed; ask the plugin to declare it again", + )); + } + let opened = super::resources::files::open_approval_inspect( + files, + feed, + namespace, + &declaration.approval_id, + declaration.path.clone(), + )? + .map_err(|_| Status::failed_precondition("the approved shared folder is unavailable"))?; + let current_backing = backing_path(&opened.approval, &opened.path)?; + if current_backing != declaration.backing_path { + return Err(Status::failed_precondition( + "the shared resource backing folder changed; review it again", + )); + } + let scope = scope_of(feed, &opened.approval)?; + let consent = namespace + .shared_resource_consent(&profile.id, &declaration.resource_id)? + .filter(|record| { + record.declaration == declaration_fingerprint(&declaration) + && record.scope == scope_fingerprint(&scope) + }) + .map(|_| ConsentState::Current) + .unwrap_or(ConsentState::Stale); + if consent != ConsentState::Current { + return Err(Status::failed_precondition(format!( + "shared resource {:?} needs the user's review", + declaration.resource_id + ))); + } + let lease_key = + ResourceLeaseKey::from_backing_identity(declaration.backing_path.as_bytes()) + .ok_or_else(|| unavailable("the shared resource identity cannot be determined"))?; + prepared.push(PreparedSharedResource { + declaration, + scope, + consent, + lease_key, + }); + } + Ok(prepared) +} + +/// A review item for the settings surface. It never contains a filesystem path. +#[derive(Clone, Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PluginSharedResourceReview { + pub plugin_id: String, + pub publisher_fingerprint: String, + pub profile_id: String, + pub profile_name: String, + pub game_id: String, + pub installation_id: String, + pub runtime_id: String, + pub resource_id: String, + pub display_name: String, + pub affected_games: Vec, + /// `pending`, `current` or `stale`. + pub consent: String, + /// True when the current approval or affected set can no longer be resolved. + pub unavailable: bool, +} + +#[derive(Clone, Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PluginSharedResourceGame { + pub installation_id: String, + pub game_id: String, + pub name: String, +} + +/// Host-side review and consent for one authenticated plugin in the active account profile. +pub struct PluginSharedResources { + storage: Arc, + profiles: Arc, + files: Arc, + feed: Arc, +} + +impl PluginSharedResources { + pub fn new( + storage: Arc, + profiles: Arc, + files: Arc, + feed: Arc, + ) -> Self { + Self { + storage, + profiles, + files, + feed, + } + } + + fn resolver( + &self, + plugin_id: &str, + publisher: &str, + ) -> Result { + self.profiles + .resolver(plugin_id, publisher, None) + .map_err(|error| error.message().to_owned()) + } + + /// Every declared shared resource in the plugin's profiles, with its current review state. + pub async fn list( + &self, + plugin_id: &str, + publisher: &str, + ) -> Result, String> { + let resolver = self.resolver(plugin_id, publisher)?; + let epoch = self.profiles.epoch(); + let files = self.files.clone(); + let feed = self.feed.clone(); + let owner = plugin_id.to_owned(); + let publisher_owned = publisher.to_owned(); + let mut reviews = self + .storage + .run_for_host(&resolver, epoch, move |namespace| { + let mut reviews = Vec::new(); + for profile in namespace.save_profiles()? { + let declarations = resources_from_json(&profile.shared_resources); + if declarations.is_empty() { + continue; + } + for declaration in declarations { + let record = namespace + .shared_resource_consent(&profile.id, &declaration.resource_id)?; + let opened = super::resources::files::open_approval_inspect( + &files, + &feed, + namespace, + &declaration.approval_id, + declaration.path.clone(), + ); + let (mut scope, unavailable) = match opened { + Ok(Ok(opened)) => match scope_of(&feed, &opened.approval) { + Ok(scope) => (scope, false), + Err(_) => (Vec::new(), true), + }, + _ => (Vec::new(), true), + }; + let consent = record + .filter(|record| { + record.declaration == declaration_fingerprint(&declaration) + }) + .map(|record| { + if unavailable || record.scope != scope_fingerprint(&scope) { + ConsentState::Stale + } else { + ConsentState::Current + } + }) + .unwrap_or(ConsentState::Pending); + scope.sort_by(|a, b| a.name.cmp(&b.name)); + reviews.push(PluginSharedResourceReview { + plugin_id: owner.clone(), + publisher_fingerprint: publisher_owned.clone(), + profile_id: profile.id.clone(), + profile_name: profile.name.clone(), + game_id: profile.game_id.clone(), + installation_id: profile.installation_id.clone(), + runtime_id: profile.runtime_id.clone(), + resource_id: declaration.resource_id.clone(), + display_name: declaration.display_name.clone(), + affected_games: scope + .into_iter() + .map(|entry| PluginSharedResourceGame { + installation_id: entry.installation_id, + game_id: entry.game_id, + name: entry.name, + }) + .collect(), + consent: consent.as_str().to_owned(), + unavailable, + }); + } + } + Ok(reviews) + }) + .await + .map_err(|error| error.message().to_owned())?; + reviews + .sort_by(|a, b| (&a.profile_id, &a.resource_id).cmp(&(&b.profile_id, &b.resource_id))); + Ok(reviews) + } + + /// Accepts the currently resolved declaration and scope. Any drift from the stored declaration + /// is refused: the plugin must save the declaration again before the user can review it. + pub async fn accept( + &self, + plugin_id: &str, + publisher: &str, + profile_id: &str, + resource_id: &str, + ) -> Result<(), String> { + let resolver = self.resolver(plugin_id, publisher)?; + let epoch = self.profiles.epoch(); + let files = self.files.clone(); + let feed = self.feed.clone(); + let profile_id = profile_id.to_owned(); + let resource_id = resource_id.to_owned(); + self.storage + .run_for_host(&resolver, epoch, move |namespace| { + let profile = namespace + .save_profile(&profile_id)? + .ok_or_else(|| Status::not_found("save profile not found"))?; + if profile.runtime_id.is_empty() { + return Err(Status::failed_precondition( + "a shared resource requires the profile's approved runtime binding", + )); + } + let declaration = resources_from_json(&profile.shared_resources) + .into_iter() + .find(|resource| resource.resource_id == resource_id) + .ok_or_else(|| Status::not_found("shared resource declaration not found"))?; + if declaration.runtime_id != profile.runtime_id { + return Err(Status::failed_precondition( + "the shared resource runtime binding changed", + )); + } + let opened = super::resources::files::open_approval_inspect( + &files, + &feed, + namespace, + &declaration.approval_id, + declaration.path.clone(), + )? + .map_err(|_| Status::failed_precondition("the approved shared folder is unavailable"))?; + let backing = backing_path(&opened.approval, &opened.path)?; + if backing != declaration.backing_path { + return Err(Status::failed_precondition( + "the shared resource backing folder changed; ask the plugin to declare it again", + )); + } + let scope = scope_of(&feed, &opened.approval)?; + namespace.put_shared_resource_consent(&SharedResourceConsentRow { + profile_id: profile.id.clone(), + resource_id: declaration.resource_id.clone(), + declaration: declaration_fingerprint(&declaration), + scope: scope_fingerprint(&scope), + profile_revision: profile.revision, + approved_at: namespace.now(), + }) + }) + .await + .map_err(|error| error.message().to_owned()) + } + + /// Forgets a decision; the next use asks again. + pub async fn revoke( + &self, + plugin_id: &str, + publisher: &str, + profile_id: &str, + resource_id: &str, + ) -> Result { + let resolver = self.resolver(plugin_id, publisher)?; + let epoch = self.profiles.epoch(); + let profile_id = profile_id.to_owned(); + let resource_id = resource_id.to_owned(); + self.storage + .run_for_host(&resolver, epoch, move |namespace| { + namespace.revoke_shared_resource_consent(&profile_id, &resource_id) + }) + .await + .map_err(|error| error.message().to_owned()) + } + + /// Test seam for the host-owned use path: revalidates every declaration and returns the + /// prepared resources or the same refusal a launch or backup would receive. + #[cfg(test)] + pub async fn prepared( + &self, + plugin_id: &str, + publisher: &str, + profile_id: &str, + ) -> Result, String> { + let resolver = self.resolver(plugin_id, publisher)?; + let epoch = self.profiles.epoch(); + let files = self.files.clone(); + let feed = self.feed.clone(); + let profile_id = profile_id.to_owned(); + self.storage + .run_for_host(&resolver, epoch, move |namespace| { + let profile = namespace + .save_profile(&profile_id)? + .ok_or_else(|| Status::not_found("save profile not found"))?; + prepare_for_use(&files, &feed, namespace, &profile) + }) + .await + .map_err(|error| error.message().to_owned()) + } +} + +/// The state a save-profile reply can show without re-opening the approval. It still catches a +/// changed declaration; `prepare_for_use` additionally checks the current affected set. +pub fn reply_state( + record: Option<&SharedResourceConsentRow>, + declaration: &SharedResource, +) -> ConsentState { + match record { + None => ConsentState::Pending, + Some(record) if record.declaration == declaration_fingerprint(declaration) => { + ConsentState::Current + } + Some(_) => ConsentState::Stale, + } +} + +/// A reply state that also compares the host-resolved affected set with the stored decision. +pub fn reply_state_with_scope( + record: Option<&SharedResourceConsentRow>, + declaration: &SharedResource, + scope: &[AffectedEntry], +) -> ConsentState { + match record { + None => ConsentState::Pending, + Some(record) + if record.declaration == declaration_fingerprint(declaration) + && record.scope == scope_fingerprint(scope) => + { + ConsentState::Current + } + Some(_) => ConsentState::Stale, + } +} + +/// The result of inspecting externally started processes for an approved runtime executable. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ExternalUse { + Idle, + Active, + /// The platform cannot list processes, or the listing failed. Callers fail closed. + Unknown, +} + +/// Host-side external-process check against one approved runtime executable identity. +#[derive(Clone)] +pub struct RuntimeUseCheck { + pub executable: String, + pub processes: Option>, +} + +impl RuntimeUseCheck { + pub fn inspect(&self) -> ExternalUse { + let Some(processes) = &self.processes else { + return ExternalUse::Unknown; + }; + let Ok(list) = processes.list() else { + return ExternalUse::Unknown; + }; + let approved = Path::new(&self.executable); + let active = list.iter().any(|process| { + let running = Path::new(&process.exe_path); + #[cfg(windows)] + { + // Windows paths compare case-insensitively. + running + .to_string_lossy() + .eq_ignore_ascii_case(&self.executable) + } + #[cfg(not(windows))] + { + running == approved + } + }); + if active { + ExternalUse::Active + } else { + ExternalUse::Idle + } + } +} + +/// The host-owned lease key for a canonical backing folder. +pub fn lease_key_for(backing: &str) -> Result { + ResourceLeaseKey::from_backing_identity(backing.as_bytes()) + .ok_or_else(|| unavailable("the shared resource identity cannot be determined")) +} + +/// Whether a set of prepared resources contains a duplicate lease key. Defensive: declaration +/// validation already rejects aliases and overlaps. +pub fn distinct_keys( + resources: &[PreparedSharedResource], +) -> Result, Status> { + let mut keys = BTreeSet::new(); + for resource in resources { + if !keys.insert(resource.lease_key) { + return Err(Status::failed_precondition( + "two shared resources resolve to one backing folder", + )); + } + } + Ok(keys.into_iter().collect()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn entry(installation: &str, game: &str, name: &str) -> AffectedEntry { + AffectedEntry { + entry_key: format!("key-{installation}"), + installation_id: installation.into(), + game_id: game.into(), + name: name.into(), + } + } + + fn declaration(backing: &str, runtime: &str) -> SharedResource { + SharedResource { + resource_id: "memory-card".into(), + approval_id: "approval-a".into(), + path: vec![], + display_name: "Memory card".into(), + backing_path: backing.into(), + runtime_id: runtime.into(), + } + } + + #[test] + fn scope_identity_ignores_order_names_and_display_only_changes() { + let one = entry("id-a", "1", "Card A"); + let two = entry("id-b", "2", "Card B"); + assert_eq!( + scope_fingerprint(&[one.clone(), two.clone()]), + scope_fingerprint(&[two, one]) + ); + let renamed = entry("id-a", "1", "Renamed"); + assert_eq!( + scope_fingerprint(&[renamed]), + scope_fingerprint(&[entry("id-a", "1", "Card A")]) + ); + assert_ne!( + scope_fingerprint(&[entry("id-a", "1", "Card A")]), + scope_fingerprint(&[entry("id-a", "9", "Card A")]) + ); + } + + #[test] + fn declaration_identity_changes_only_for_authority_changes() { + let original = declaration("/games/shared", "runtime-a"); + let renamed = SharedResource { + display_name: "Other name".into(), + ..original.clone() + }; + assert_eq!( + declaration_fingerprint(&original), + declaration_fingerprint(&renamed) + ); + for changed in [ + SharedResource { + backing_path: "/games/other".into(), + ..original.clone() + }, + SharedResource { + runtime_id: "runtime-b".into(), + ..original.clone() + }, + SharedResource { + approval_id: "approval-b".into(), + ..original.clone() + }, + ] { + assert_ne!( + declaration_fingerprint(&original), + declaration_fingerprint(&changed) + ); + } + } + + #[test] + fn nested_folders_overlap_and_siblings_do_not() { + assert!(overlaps("/games/shared", "/games/shared/card")); + assert!(overlaps("/games/shared/card", "/games/shared")); + assert!(!overlaps("/games/shared/one", "/games/shared/two")); + assert!(!overlaps("/games/one", "/games/two")); + } + + struct FakeProcesses(Vec); + + impl gamenode_core::ports::Processes for FakeProcesses { + fn list( + &self, + ) -> Result, gamenode_core::ports::ProcessError> + { + Ok(self.0.clone()) + } + + fn watch( + &self, + _: &gamenode_core::ports::ProcessInfo, + _: Box, + ) -> Result<(), gamenode_core::ports::ProcessError> { + Err(gamenode_core::ports::ProcessError::Unsupported) + } + } + + fn process(path: &str) -> gamenode_core::ports::ProcessInfo { + gamenode_core::ports::ProcessInfo { + pid: 7, + created_at: std::time::UNIX_EPOCH, + exe_path: path.into(), + parent: None, + } + } + + #[test] + fn external_use_fails_closed_without_inspection_and_matches_the_exact_identity() { + let idle = RuntimeUseCheck { + executable: "/emulators/dolphin".into(), + processes: Some(Arc::new(FakeProcesses(vec![process("/emulators/other")]))), + }; + assert_eq!(idle.inspect(), ExternalUse::Idle); + let active = RuntimeUseCheck { + executable: "/emulators/dolphin".into(), + processes: Some(Arc::new(FakeProcesses(vec![process("/emulators/dolphin")]))), + }; + assert_eq!(active.inspect(), ExternalUse::Active); + let unknown = RuntimeUseCheck { + executable: "/emulators/dolphin".into(), + processes: None, + }; + assert_eq!(unknown.inspect(), ExternalUse::Unknown); + } + + #[cfg(target_os = "linux")] + #[test] + fn external_use_sees_a_real_linux_runtime_and_returns_to_idle() { + use gamenode_core::drm_free::InstallationHost as _; + use std::process::{Command, Stdio}; + + // A private executable identity keeps the check independent of unrelated processes. + let dir = tempfile::tempdir().unwrap(); + let executable = dir.path().join("approved-runtime"); + std::fs::copy("/bin/sleep", &executable).unwrap(); + let registration = gamenode_platform::installations::LinuxInstallations + .inspect(executable.to_str().unwrap()) + .unwrap(); + let processes = Arc::new(gamenode_platform::processes::HostProcesses::new()); + let check = RuntimeUseCheck { + executable: registration.executable.clone(), + processes: Some(processes.clone()), + }; + assert_eq!(check.inspect(), ExternalUse::Idle, "nothing is running yet"); + + let mut child = Command::new(®istration.executable) + .arg("30") + .stdin(Stdio::null()) + .spawn() + .unwrap(); + // The child is visible in `/proc` only after it execs; a loaded runner can lose that race + // between `spawn` and the first scan. + let mut active = false; + for _ in 0..100 { + if check.inspect() == ExternalUse::Active { + active = true; + break; + } + std::thread::sleep(std::time::Duration::from_millis(50)); + } + if !active { + use gamenode_core::ports::Processes as _; + let listed = processes + .list() + .unwrap_or_default() + .into_iter() + .filter(|process| { + process.pid == child.id() || process.exe_path.contains("approved-runtime") + }) + .map(|process| (process.pid, process.exe_path)) + .collect::>(); + panic!( + "the real process was not observed as active: child={} approved={:?} listed={listed:?}", + child.id(), + registration.executable + ); + } + child.kill().unwrap(); + child.wait().unwrap(); + for _ in 0..100 { + if check.inspect() == ExternalUse::Idle { + return; + } + std::thread::sleep(std::time::Duration::from_millis(50)); + } + panic!("the real process exit was not observed"); + } +} diff --git a/crates/app/src/plugin_host/sharing_policy.rs b/crates/app/src/plugin_host/sharing_policy.rs new file mode 100644 index 000000000..152adf763 --- /dev/null +++ b/crates/app/src/plugin_host/sharing_policy.rs @@ -0,0 +1,1912 @@ +//! Host-side consent for cross-plugin data. +//! +//! Activation grants only authorize a later, explicit per-query selection. They do not +//! schedule or perform reads. Category and record grants are kept in separate sets so that a +//! selected record never expands into category-wide access. Sensitive and custom datasets use +//! a separate source-to-recipient rule with exact field names and independent history/live +//! switches. + +use std::{ + collections::{BTreeMap, BTreeSet}, + fs::{self, File, OpenOptions}, + io::{self, Read, Write}, + path::{Path, PathBuf}, + sync::atomic::{AtomicU64, Ordering}, + sync::{Arc, RwLock}, +}; + +use gamenode_plugin_protocol::{ + common_data::{self, AuthorizedSelection, SelectorError}, + proto::{CommonDataCategory, CommonDataSelector}, +}; +use serde::{Deserialize, Serialize}; +use thiserror::Error; + +use super::grants::{ + PluginIdentity, atomic_replace, ensure_private_dir, ensure_private_file, sync_dir, +}; + +const STORE_FILE: &str = "plugin-sharing-policies.json"; +const STORE_SCHEMA: u32 = 1; +const MAX_STORE_BYTES: u64 = 8 * 1024 * 1024; +const MAX_RECORD_ID_BYTES: usize = 256; +const MAX_DATASET_ID_BYTES: usize = 256; +const MAX_FIELD_BYTES: usize = 256; +const MAX_FIELDS_PER_POLICY: usize = 256; +const MAX_SELECTED_RECORDS_PER_RECIPIENT: usize = 1000; +const MAX_SOURCE_POLICIES_PER_RECIPIENT: usize = 1024; +static NEXT_TEMP_FILE: AtomicU64 = AtomicU64::new(1); + +/// An activation-time selection for one authenticated recipient. +/// +/// This object stores consent only. Call [`SharingPolicies::authorize_common_query`] for a +/// particular RPC, then fetch records using the returned selection. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct ActivationReadGrant { + categories: BTreeSet, + selected_record_ids: BTreeSet, +} + +impl ActivationReadGrant { + /// Construct the optional common-data grants the user selected while activating a plugin. + /// Empty sets are a valid default-deny grant. + pub fn new( + categories: impl IntoIterator, + selected_record_ids: impl IntoIterator, + ) -> Result { + let categories = categories.into_iter().collect::>(); + if categories.contains(&CommonDataCategory::Unspecified) { + return Err(SharingPolicyError::InvalidCategory); + } + let selected_record_ids = selected_record_ids.into_iter().collect::>(); + if selected_record_ids.len() > MAX_SELECTED_RECORDS_PER_RECIPIENT + || selected_record_ids + .iter() + .any(|id| !valid_plain_identifier(id, MAX_RECORD_ID_BYTES)) + { + return Err(SharingPolicyError::InvalidRecordId); + } + Ok(Self { + categories, + selected_record_ids, + }) + } + + pub fn categories(&self) -> &BTreeSet { + &self.categories + } + + pub fn selected_record_ids(&self) -> &BTreeSet { + &self.selected_record_ids + } +} + +/// Data classes used to select a common-data or source-recipient policy path. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum SharingClass { + Common, + Sensitive, + Custom, +} + +impl SharingClass { + /// The stable name stored in the durable pool. + pub fn as_name(self) -> &'static str { + match self { + Self::Common => "common", + Self::Sensitive => "sensitive", + Self::Custom => "custom", + } + } + + /// Decodes a stored name; an unknown value is not a record this host wrote. + pub fn from_name(name: &str) -> Option { + match name { + "common" => Some(Self::Common), + "sensitive" => Some(Self::Sensitive), + "custom" => Some(Self::Custom), + _ => None, + } + } +} + +/// Which delivery path is being authorized. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Delivery { + /// A direct query for the current value. + Query, + /// Reading retained historical values. + History, + /// Receiving future updates through a live subscription. + Live, +} + +/// An explicitly reviewed source-to-recipient rule for one dataset. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct SourceRecipientPolicy { + source: PluginIdentity, + recipient: PluginIdentity, + class: SharingClass, + dataset_id: String, + fields: BTreeSet, + history: bool, + live: bool, +} + +/// Host-owned view of all data-sharing choices for one authenticated recipient. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct RecipientSharingSnapshot { + pub revision: u64, + pub categories: BTreeSet, + pub selected_record_ids: BTreeSet, + pub source_recipient_policies: Vec, +} + +impl SourceRecipientPolicy { + pub fn new( + source: PluginIdentity, + recipient: PluginIdentity, + class: SharingClass, + dataset_id: String, + fields: impl IntoIterator, + history: bool, + live: bool, + ) -> Result { + validate_identity(&source)?; + validate_identity(&recipient)?; + if class == SharingClass::Common { + return Err(SharingPolicyError::InvalidPolicyClass); + } + if !valid_plain_identifier(&dataset_id, MAX_DATASET_ID_BYTES) { + return Err(SharingPolicyError::InvalidDatasetId); + } + let fields = fields.into_iter().collect::>(); + if fields.is_empty() || fields.len() > MAX_FIELDS_PER_POLICY { + return Err(SharingPolicyError::InvalidFields); + } + if fields.iter().any(|field| !valid_field_name(field)) { + return Err(SharingPolicyError::InvalidFields); + } + Ok(Self { + source, + recipient, + class, + dataset_id, + fields, + history, + live, + }) + } + + pub fn source(&self) -> &PluginIdentity { + &self.source + } + + pub fn recipient(&self) -> &PluginIdentity { + &self.recipient + } + + pub fn class(&self) -> SharingClass { + self.class + } + + pub fn dataset_id(&self) -> &str { + &self.dataset_id + } + + pub fn fields(&self) -> &BTreeSet { + &self.fields + } + + pub fn allows_history(&self) -> bool { + self.history + } + + pub fn allows_live(&self) -> bool { + self.live + } +} + +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] +struct IdentityKey { + plugin_id: String, + publisher_fingerprint: String, + profile_id: String, +} + +impl From<&PluginIdentity> for IdentityKey { + fn from(identity: &PluginIdentity) -> Self { + Self { + plugin_id: identity.plugin_id.clone(), + publisher_fingerprint: identity.publisher_fingerprint.clone(), + profile_id: identity.profile_id.clone(), + } + } +} + +fn identity_from_key(key: &IdentityKey) -> PluginIdentity { + PluginIdentity { + plugin_id: key.plugin_id.clone(), + publisher_fingerprint: key.publisher_fingerprint.clone(), + profile_id: key.profile_id.clone(), + } +} + +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] +struct PolicyKey { + source: IdentityKey, + recipient: IdentityKey, + class: SharingClass, + dataset_id: String, +} + +/// Host-owned policy index. Its optional path is always under a private directory; policy +/// changes are written atomically before becoming visible. Authorization has no query or +/// subscription side effects. +#[derive(Clone, Debug, Default)] +pub struct SharingPolicies { + activation: BTreeMap, + source_recipient: BTreeMap, + revisions: BTreeMap, + path: Option, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct PersistentStore { + schema: u32, + activation: Vec, + source_recipient: Vec, + revisions: Vec, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct PersistedActivationGrant { + recipient: PluginIdentity, + categories: Vec, + selected_record_ids: Vec, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct PersistedRevision { + recipient: PluginIdentity, + revision: u64, +} + +/// The exact scope that an authenticated Data/domain query selected. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum AccessScope { + /// Owner-private data; the broker must still enforce owner-specific API permissions. + Owner, + Category(CommonDataCategory), + SelectedRecord(String), + /// Explicit source dataset; valid only for Sensitive/Custom source-recipient policies. + Dataset(String), +} + +/// One candidate record's access check. `fields` contains field names, never values. +#[derive(Clone)] +pub struct AccessRequest<'a> { + pub recipient: &'a PluginIdentity, + pub source: &'a PluginIdentity, + pub record_id: &'a str, + pub dataset_id: &'a str, + pub category: Option, + pub scope: AccessScope, + pub class: SharingClass, + pub fields: &'a BTreeSet, + pub delivery: Delivery, +} + +/// The record projection that remains after current host policy has been evaluated. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct AccessDecision { + pub allowed: bool, + pub fields: BTreeSet, + pub history: bool, + pub live: bool, + pub revision: u64, +} + +/// Minimal policy interface used by the shared-data broker. +pub trait Authorizer: Send + Sync { + fn revision(&self, recipient: &PluginIdentity) -> u64; + fn decide(&self, request: &AccessRequest<'_>) -> AccessDecision; + + /// Category-wide common read for a domain catalog. Unlike [`Authorizer::decide`], it does not + /// need a source identity because every producer in the category is in scope. The returned + /// fields are only the projection names the recipient may read. + fn common_category( + &self, + _recipient: &PluginIdentity, + _category: CommonDataCategory, + _fields: &BTreeSet, + ) -> AccessDecision { + AccessDecision::default() + } +} + +/// Thread-safe handle for host services that need to share policy reads and serialize durable +/// policy mutations. The handle is cheap to clone and can be stored as `Arc`. +#[derive(Clone, Debug)] +pub struct SharedSharingPolicies { + inner: Arc>, +} + +impl Default for SharedSharingPolicies { + fn default() -> Self { + Self { + inner: Arc::new(RwLock::new(SharingPolicies::default())), + } + } +} + +impl SharedSharingPolicies { + /// Open the durable store and wrap it for sharing across host services. + pub fn open(private_dir: impl AsRef) -> Result { + Ok(Self { + inner: Arc::new(RwLock::new(SharingPolicies::open(private_dir)?)), + }) + } + + pub fn set_activation_grants( + &self, + recipient: &PluginIdentity, + grant: ActivationReadGrant, + ) -> Result<(), SharingPolicyError> { + self.write()?.set_activation_grants(recipient, grant) + } + + pub fn clear_activation_grants( + &self, + recipient: &PluginIdentity, + ) -> Result<(), SharingPolicyError> { + self.write()?.clear_activation_grants(recipient) + } + + pub fn set_source_recipient_policy( + &self, + policy: SourceRecipientPolicy, + ) -> Result<(), SharingPolicyError> { + self.write()?.set_source_recipient_policy(policy) + } + + pub fn revoke_source_recipient_policy( + &self, + source: &PluginIdentity, + recipient: &PluginIdentity, + class: SharingClass, + dataset_id: &str, + ) -> Result { + self.write()? + .revoke_source_recipient_policy(source, recipient, class, dataset_id) + } + + pub fn recipient_snapshot( + &self, + recipient: &PluginIdentity, + ) -> Result { + self.read()?.recipient_snapshot(recipient) + } + + /// Atomically replace one recipient's complete data-sharing policy, fenced by the revision + /// shown in its current settings snapshot. + pub fn replace_recipient_policies( + &self, + recipient: &PluginIdentity, + expected_revision: u64, + grant: ActivationReadGrant, + source_policies: Vec, + ) -> Result { + self.write()?.replace_recipient_policies( + recipient, + expected_revision, + grant, + source_policies, + ) + } + + pub(crate) fn replace_recipient_policies_snapshot( + &self, + recipient: &PluginIdentity, + expected_revision: u64, + grant: ActivationReadGrant, + source_policies: Vec, + ) -> Result { + let mut policies = self.write()?; + policies.replace_recipient_policies( + recipient, + expected_revision, + grant, + source_policies, + )?; + policies.recipient_snapshot(recipient) + } + + fn read(&self) -> Result, SharingPolicyError> { + self.inner + .read() + .map_err(|_| SharingPolicyError::LockPoisoned) + } + + fn write( + &self, + ) -> Result, SharingPolicyError> { + self.inner + .write() + .map_err(|_| SharingPolicyError::LockPoisoned) + } +} + +impl Authorizer for SharedSharingPolicies { + fn revision(&self, recipient: &PluginIdentity) -> u64 { + self.read() + .map(|policies| policies.revision(recipient)) + // A maximal revision fences existing cursors if the policy lock is poisoned. + .unwrap_or(u64::MAX) + } + + fn decide(&self, request: &AccessRequest<'_>) -> AccessDecision { + self.read() + .map(|policies| policies.decide(request)) + .unwrap_or_else(|_| AccessDecision { + revision: u64::MAX, + ..AccessDecision::default() + }) + } + + fn common_category( + &self, + recipient: &PluginIdentity, + category: CommonDataCategory, + fields: &BTreeSet, + ) -> AccessDecision { + self.read() + .map(|policies| policies.common_category(recipient, category, fields)) + .unwrap_or_else(|_| AccessDecision { + revision: u64::MAX, + ..AccessDecision::default() + }) + } +} + +impl SharingPolicies { + /// Open the host-owned policy database under a private directory. + pub fn open(private_dir: impl AsRef) -> Result { + let directory = private_dir.as_ref(); + ensure_private_dir(directory)?; + let path = directory.join(STORE_FILE); + let mut policies = match fs::symlink_metadata(&path) { + Ok(metadata) + if metadata.file_type().is_file() && !metadata.file_type().is_symlink() => + { + if metadata.len() > MAX_STORE_BYTES { + return Err(SharingPolicyError::InvalidStore( + "file exceeds size limit".into(), + )); + } + ensure_private_file(&path)?; + let mut bytes = Vec::with_capacity(metadata.len() as usize); + File::open(&path)? + .take(MAX_STORE_BYTES + 1) + .read_to_end(&mut bytes)?; + if bytes.len() as u64 > MAX_STORE_BYTES { + return Err(SharingPolicyError::InvalidStore( + "file exceeds size limit".into(), + )); + } + let store: PersistentStore = serde_json::from_slice(&bytes) + .map_err(|error| SharingPolicyError::InvalidStore(error.to_string()))?; + Self::from_persistent(store)? + } + Ok(_) => { + return Err(SharingPolicyError::InvalidStore( + "unsafe policy file".into(), + )); + } + Err(error) if error.kind() == io::ErrorKind::NotFound => Self::default(), + Err(error) => return Err(error.into()), + }; + policies.path = Some(path); + Ok(policies) + } + + fn from_persistent(store: PersistentStore) -> Result { + if store.schema != STORE_SCHEMA { + return Err(SharingPolicyError::InvalidStore( + "unsupported policy schema".into(), + )); + } + let mut policies = Self::default(); + for persisted in store.activation { + validate_identity(&persisted.recipient)?; + let categories = persisted + .categories + .into_iter() + .map(|raw| { + CommonDataCategory::try_from(raw) + .map_err(|_| SharingPolicyError::InvalidCategory) + }) + .collect::, _>>()?; + let grant = ActivationReadGrant::new(categories, persisted.selected_record_ids)?; + let key = IdentityKey::from(&persisted.recipient); + if policies.activation.insert(key, grant).is_some() { + return Err(SharingPolicyError::InvalidStore( + "duplicate activation identity".into(), + )); + } + } + for persisted in store.source_recipient { + let policy = SourceRecipientPolicy::new( + persisted.source, + persisted.recipient, + persisted.class, + persisted.dataset_id, + persisted.fields, + persisted.history, + persisted.live, + )?; + if policies + .source_recipient + .insert(policy_key(&policy), policy) + .is_some() + { + return Err(SharingPolicyError::InvalidStore( + "duplicate source-recipient policy".into(), + )); + } + } + for persisted in store.revisions { + validate_identity(&persisted.recipient)?; + if persisted.revision == 0 { + return Err(SharingPolicyError::InvalidStore( + "zero policy revision".into(), + )); + } + if policies + .revisions + .insert(IdentityKey::from(&persisted.recipient), persisted.revision) + .is_some() + { + return Err(SharingPolicyError::InvalidStore( + "duplicate policy revision".into(), + )); + } + } + for recipient in policies + .activation + .keys() + .chain(policies.source_recipient.keys().map(|key| &key.recipient)) + { + if !policies.revisions.contains_key(recipient) { + return Err(SharingPolicyError::InvalidStore( + "policy is missing its revision".into(), + )); + } + } + Ok(policies) + } + + fn to_persistent(&self) -> PersistentStore { + let activation = self + .activation + .iter() + .map(|(identity, grant)| PersistedActivationGrant { + recipient: identity_from_key(identity), + categories: grant + .categories + .iter() + .map(|category| *category as i32) + .collect(), + selected_record_ids: grant.selected_record_ids.iter().cloned().collect(), + }) + .collect(); + let revisions = self + .revisions + .iter() + .map(|(identity, revision)| PersistedRevision { + recipient: identity_from_key(identity), + revision: *revision, + }) + .collect(); + PersistentStore { + schema: STORE_SCHEMA, + activation, + source_recipient: self.source_recipient.values().cloned().collect(), + revisions, + } + } + + fn persist(&self) -> Result<(), SharingPolicyError> { + let Some(path) = &self.path else { + return Ok(()); + }; + let parent = path + .parent() + .ok_or_else(|| SharingPolicyError::InvalidStore("policy path has no parent".into()))?; + ensure_private_dir(parent)?; + let bytes = serde_json::to_vec(&self.to_persistent()) + .map_err(|error| SharingPolicyError::InvalidStore(error.to_string()))?; + if bytes.len() as u64 > MAX_STORE_BYTES { + return Err(SharingPolicyError::InvalidStore( + "file exceeds size limit".into(), + )); + } + let sequence = NEXT_TEMP_FILE.fetch_add(1, Ordering::Relaxed); + let temp = parent.join(format!( + ".{STORE_FILE}.{}.{}.tmp", + std::process::id(), + sequence + )); + let mut options = OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600); + } + let result = (|| -> Result<(), SharingPolicyError> { + let mut file = options.open(&temp)?; + file.write_all(&bytes)?; + file.sync_all()?; + atomic_replace(&temp, path)?; + ensure_private_file(path)?; + sync_dir(parent)?; + Ok(()) + })(); + if result.is_err() { + let _ = fs::remove_file(&temp); + } + result + } + + fn commit_candidate(&mut self, candidate: Self) -> Result<(), SharingPolicyError> { + candidate.persist()?; + *self = candidate; + Ok(()) + } + + /// Replace the activation-selected common-data grants for an authenticated plugin. + pub fn set_activation_grants( + &mut self, + recipient: &PluginIdentity, + grant: ActivationReadGrant, + ) -> Result<(), SharingPolicyError> { + validate_identity(recipient)?; + let mut candidate = self.clone(); + candidate.bump_revision(recipient)?; + candidate.activation.insert(recipient.into(), grant); + self.commit_candidate(candidate) + } + + /// Remove all common-data grants associated with this exact plugin/publisher/profile. + pub fn clear_activation_grants( + &mut self, + recipient: &PluginIdentity, + ) -> Result<(), SharingPolicyError> { + validate_identity(recipient)?; + let key: IdentityKey = recipient.into(); + if self.activation.contains_key(&key) { + let mut candidate = self.clone(); + candidate.bump_revision(recipient)?; + candidate.activation.remove(&key); + self.commit_candidate(candidate)?; + } + Ok(()) + } + + /// Current host policy revision for cursor and subscription fencing. + pub fn revision(&self, recipient: &PluginIdentity) -> u64 { + self.revisions + .get(&IdentityKey::from(recipient)) + .copied() + .unwrap_or_default() + } + + fn recipient_snapshot( + &self, + recipient: &PluginIdentity, + ) -> Result { + validate_identity(recipient)?; + let key = IdentityKey::from(recipient); + let grant = self.activation.get(&key).cloned().unwrap_or_default(); + let mut source_recipient_policies = self + .source_recipient + .iter() + .filter(|(policy_key, _)| policy_key.recipient == key) + .map(|(_, policy)| policy.clone()) + .collect::>(); + source_recipient_policies.sort_by(|left, right| { + (&left.source.plugin_id, &left.dataset_id, left.class).cmp(&( + &right.source.plugin_id, + &right.dataset_id, + right.class, + )) + }); + Ok(RecipientSharingSnapshot { + revision: self.revision(recipient), + categories: grant.categories, + selected_record_ids: grant.selected_record_ids, + source_recipient_policies, + }) + } + + fn replace_recipient_policies( + &mut self, + recipient: &PluginIdentity, + expected_revision: u64, + grant: ActivationReadGrant, + source_policies: Vec, + ) -> Result { + validate_identity(recipient)?; + if self.revision(recipient) != expected_revision { + return Err(SharingPolicyError::StaleRevision); + } + if source_policies.len() > MAX_SOURCE_POLICIES_PER_RECIPIENT { + return Err(SharingPolicyError::TooManyPolicies); + } + let recipient_key = IdentityKey::from(recipient); + let mut policy_keys = BTreeSet::new(); + for policy in &source_policies { + validate_identity(&policy.source)?; + validate_identity(&policy.recipient)?; + if policy.recipient != *recipient + || policy.source == policy.recipient + || policy.class == SharingClass::Common + || !valid_plain_identifier(&policy.dataset_id, MAX_DATASET_ID_BYTES) + || policy.fields.is_empty() + || policy.fields.len() > MAX_FIELDS_PER_POLICY + || policy.fields.iter().any(|field| !valid_field_name(field)) + || !policy_keys.insert(policy_key(policy)) + { + return Err(SharingPolicyError::InvalidFields); + } + } + + let mut candidate = self.clone(); + let revision = candidate.bump_revision(recipient)?; + candidate.activation.insert(recipient_key.clone(), grant); + candidate + .source_recipient + .retain(|key, _| key.recipient != recipient_key); + for policy in source_policies { + candidate + .source_recipient + .insert(policy_key(&policy), policy); + } + self.commit_candidate(candidate)?; + Ok(revision) + } + + fn bump_revision(&mut self, recipient: &PluginIdentity) -> Result { + let key = IdentityKey::from(recipient); + let next = self + .revisions + .get(&key) + .copied() + .unwrap_or_default() + .checked_add(1) + .ok_or(SharingPolicyError::RevisionExhausted)?; + self.revisions.insert(key, next); + Ok(next) + } + + /// Resolve a request's explicit selector against the recipient's current activation grants. + /// + /// The result is a filter for a subsequent host query; no data access occurs here. Missing + /// activation grants, a missing selector, and an empty selector all authorize no shared data. + pub fn authorize_common_query( + &self, + recipient: &PluginIdentity, + selector: Option<&CommonDataSelector>, + ) -> Result { + validate_identity(recipient)?; + let grant = self.activation.get(&recipient.into()); + let no_categories = BTreeSet::new(); + let no_records = BTreeSet::new(); + let categories = grant.map_or(&no_categories, |grant| &grant.categories); + let records = grant.map_or(&no_records, |grant| &grant.selected_record_ids); + Ok(common_data::authorize_selector( + selector, categories, records, + )?) + } + + /// Test whether a particular record is selected by the authorized per-query filter. + pub fn common_record_in_query( + selection: &AuthorizedSelection, + category: CommonDataCategory, + record_id: &str, + ) -> bool { + selection.includes_category(category) || selection.includes_record(record_id) + } + + /// Category-wide common read for a domain catalog such as the runtime catalog. + /// + /// This grants projection names only. It never grants mutation, execution or a private field, + /// and an empty or filtered-out field set is denied rather than widened. + pub fn common_category( + &self, + recipient: &PluginIdentity, + category: CommonDataCategory, + fields: &BTreeSet, + ) -> AccessDecision { + let revision = self.revision(recipient); + let denied = AccessDecision { + revision, + ..AccessDecision::default() + }; + if validate_identity(recipient).is_err() + || category == CommonDataCategory::Unspecified + || fields.is_empty() + { + return denied; + } + let Some(grant) = self.activation.get(&IdentityKey::from(recipient)) else { + return denied; + }; + if !grant.categories.contains(&category) { + return denied; + } + let fields = fields + .iter() + .filter(|field| valid_field_name(field)) + .cloned() + .collect::>(); + let allowed = !fields.is_empty(); + AccessDecision { + allowed, + fields, + history: allowed, + live: allowed, + revision, + } + } + + /// Replace one exact source-to-recipient dataset policy. + pub fn set_source_recipient_policy( + &mut self, + policy: SourceRecipientPolicy, + ) -> Result<(), SharingPolicyError> { + // Revalidate at the mutation boundary in case a policy was deserialized or otherwise + // constructed outside this module in the future. + validate_identity(&policy.source)?; + validate_identity(&policy.recipient)?; + if policy.class == SharingClass::Common + || !valid_plain_identifier(&policy.dataset_id, MAX_DATASET_ID_BYTES) + || policy.fields.is_empty() + || policy.fields.len() > MAX_FIELDS_PER_POLICY + || policy.fields.iter().any(|field| !valid_field_name(field)) + { + return Err(SharingPolicyError::InvalidFields); + } + let mut candidate = self.clone(); + candidate.bump_revision(&policy.recipient)?; + candidate + .source_recipient + .insert(policy_key(&policy), policy); + self.commit_candidate(candidate) + } + + pub fn revoke_source_recipient_policy( + &mut self, + source: &PluginIdentity, + recipient: &PluginIdentity, + class: SharingClass, + dataset_id: &str, + ) -> Result { + validate_identity(source)?; + validate_identity(recipient)?; + if !valid_plain_identifier(dataset_id, MAX_DATASET_ID_BYTES) { + return Err(SharingPolicyError::InvalidDatasetId); + } + let key = PolicyKey { + source: source.into(), + recipient: recipient.into(), + class, + dataset_id: dataset_id.to_owned(), + }; + if self.source_recipient.contains_key(&key) { + let mut candidate = self.clone(); + candidate.bump_revision(recipient)?; + candidate.source_recipient.remove(&key); + self.commit_candidate(candidate)?; + Ok(true) + } else { + Ok(false) + } + } + + /// Authorize one field and delivery path using the exact source, recipient, class and dataset. + pub fn allows_source_delivery( + &self, + source: &PluginIdentity, + recipient: &PluginIdentity, + class: SharingClass, + dataset_id: &str, + field: &str, + delivery: Delivery, + ) -> Result { + validate_identity(source)?; + validate_identity(recipient)?; + if !valid_plain_identifier(dataset_id, MAX_DATASET_ID_BYTES) { + return Err(SharingPolicyError::InvalidDatasetId); + } + if !valid_field_name(field) { + return Err(SharingPolicyError::InvalidFields); + } + let Some(policy) = self.source_recipient.get(&PolicyKey { + source: source.into(), + recipient: recipient.into(), + class, + dataset_id: dataset_id.to_owned(), + }) else { + return Ok(false); + }; + let delivery_allowed = match delivery { + Delivery::Query => true, + Delivery::History => policy.history, + Delivery::Live => policy.live, + }; + Ok(delivery_allowed && policy.fields.contains(field)) + } + + fn decide_access(&self, request: &AccessRequest<'_>) -> AccessDecision { + let revision = self.revision(request.recipient); + let denied = AccessDecision { + revision, + ..AccessDecision::default() + }; + if validate_identity(request.recipient).is_err() + || validate_identity(request.source).is_err() + || request.source.profile_id != request.recipient.profile_id + || !valid_plain_identifier(request.record_id, MAX_RECORD_ID_BYTES) + || !valid_plain_identifier(request.dataset_id, MAX_DATASET_ID_BYTES) + { + return denied; + } + + // The broker owns the private-owner permission check and can bypass sharing review for + // that path. Returning deny here makes accidentally routing owner data through the + // cross-plugin broker fail closed. + if request.scope == AccessScope::Owner { + return denied; + } + + let requested_scope_is_explicit = match &request.scope { + AccessScope::Owner => false, + AccessScope::Category(category) => { + request.class == SharingClass::Common && request.category == Some(*category) + } + AccessScope::SelectedRecord(record_id) => { + request.class == SharingClass::Common && record_id == request.record_id + } + AccessScope::Dataset(dataset_id) => { + request.class != SharingClass::Common && dataset_id == request.dataset_id + } + }; + if !requested_scope_is_explicit { + return denied; + } + + if request.fields.is_empty() { + return denied; + } + + if request.class == SharingClass::Common { + let Some(grant) = self.activation.get(&IdentityKey::from(request.recipient)) else { + return denied; + }; + let scope_granted = match &request.scope { + AccessScope::Owner => false, + AccessScope::Category(category) => grant.categories.contains(category), + AccessScope::SelectedRecord(record_id) => { + grant.selected_record_ids.contains(record_id) + } + AccessScope::Dataset(_) => false, + }; + if !scope_granted { + return denied; + } + let fields = request + .fields + .iter() + .filter(|field| valid_field_name(field)) + .cloned() + .collect::>(); + let allowed = !fields.is_empty(); + return AccessDecision { + allowed, + fields, + history: allowed && request.delivery == Delivery::History, + live: allowed && request.delivery == Delivery::Live, + revision, + }; + } + + let Some(policy) = self.source_recipient.get(&PolicyKey { + source: request.source.into(), + recipient: request.recipient.into(), + class: request.class, + dataset_id: request.dataset_id.to_owned(), + }) else { + return denied; + }; + let delivery_allowed = match request.delivery { + Delivery::Query => true, + Delivery::History => policy.history, + Delivery::Live => policy.live, + }; + let fields = request + .fields + .iter() + .filter(|field| valid_field_name(field) && policy.fields.contains(*field)) + .cloned() + .collect::>(); + let allowed = delivery_allowed && !fields.is_empty(); + AccessDecision { + allowed, + fields, + history: policy.history, + live: policy.live, + revision, + } + } +} + +impl Authorizer for SharingPolicies { + fn revision(&self, recipient: &PluginIdentity) -> u64 { + SharingPolicies::revision(self, recipient) + } + + fn decide(&self, request: &AccessRequest<'_>) -> AccessDecision { + self.decide_access(request) + } +} + +fn policy_key(policy: &SourceRecipientPolicy) -> PolicyKey { + PolicyKey { + source: (&policy.source).into(), + recipient: (&policy.recipient).into(), + class: policy.class, + dataset_id: policy.dataset_id.clone(), + } +} + +fn validate_identity(identity: &PluginIdentity) -> Result<(), SharingPolicyError> { + identity + .validate() + .map_err(|_| SharingPolicyError::InvalidIdentity) +} + +fn valid_plain_identifier(value: &str, max_bytes: usize) -> bool { + !value.trim().is_empty() && value.len() <= max_bytes && !value.chars().any(char::is_control) +} + +fn valid_field_name(value: &str) -> bool { + if value.is_empty() + || value.len() > MAX_FIELD_BYTES + || value.split('.').any(|part| { + part.is_empty() + || !part + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-') + }) + { + return false; + } + + // Reject common secret-bearing names after normalizing punctuation and case, so variations + // such as `refresh_token`, `api-key`, and `Private.Key` cannot bypass the denylist. + let normalized = value + .bytes() + .filter(u8::is_ascii_alphanumeric) + .map(|byte| byte.to_ascii_lowercase()) + .map(char::from) + .collect::(); + ![ + "password", + "passwd", + "secret", + "token", + "credential", + "privatekey", + "apikey", + "authcookie", + "authorization", + ] + .iter() + .any(|secret| normalized.contains(secret)) +} + +#[derive(Debug, Error, PartialEq, Eq)] +pub enum SharingPolicyError { + #[error("authenticated plugin identity is invalid")] + InvalidIdentity, + #[error("common-data category is unspecified")] + InvalidCategory, + #[error("selected record id is invalid")] + InvalidRecordId, + #[error("dataset id is invalid")] + InvalidDatasetId, + #[error("field list is invalid or contains a secret-bearing field")] + InvalidFields, + #[error("common data cannot use a source-recipient policy")] + InvalidPolicyClass, + #[error("sharing policy changed; reload the settings before saving")] + StaleRevision, + #[error("recipient has too many source-sharing policies")] + TooManyPolicies, + #[error("policy revision exhausted")] + RevisionExhausted, + #[error("sharing policy lock is poisoned")] + LockPoisoned, + #[error("policy store is invalid: {0}")] + InvalidStore(String), + #[error("policy store I/O failed: {0}")] + Io(String), + #[error(transparent)] + Selector(#[from] SelectorError), +} + +impl From for SharingPolicyError { + fn from(error: io::Error) -> Self { + Self::Io(error.to_string()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn identity(plugin_id: &str, publisher: &str, profile: &str) -> PluginIdentity { + PluginIdentity { + plugin_id: plugin_id.into(), + publisher_fingerprint: publisher.into(), + profile_id: profile.into(), + } + } + + fn selector(categories: &[CommonDataCategory], record_ids: &[&str]) -> CommonDataSelector { + CommonDataSelector { + categories: categories.iter().map(|category| *category as i32).collect(), + selected_record_ids: record_ids.iter().map(|id| (*id).to_owned()).collect(), + } + } + + #[test] + fn common_data_is_default_deny_and_requires_per_query_selection() { + let mut policies = SharingPolicies::default(); + let recipient = identity("org.consumer", "SHA256:consumer", "profile-a"); + let requested = selector(&[CommonDataCategory::GamePaths], &["record-allowed"]); + + let no_activation = policies + .authorize_common_query(&recipient, Some(&requested)) + .unwrap(); + assert!(!no_activation.includes_category(CommonDataCategory::GamePaths)); + assert!(!no_activation.includes_record("record-allowed")); + + policies + .set_activation_grants( + &recipient, + ActivationReadGrant::new( + [CommonDataCategory::GamePaths], + ["record-allowed".to_owned()], + ) + .unwrap(), + ) + .unwrap(); + let omitted = policies.authorize_common_query(&recipient, None).unwrap(); + assert!(!omitted.includes_category(CommonDataCategory::GamePaths)); + assert!(!omitted.includes_record("record-allowed")); + + let selected = policies + .authorize_common_query(&recipient, Some(&requested)) + .unwrap(); + assert!(selected.includes_category(CommonDataCategory::GamePaths)); + assert!(selected.includes_record("record-allowed")); + assert!(!selected.includes_record("record-other")); + } + + #[test] + fn category_and_selected_record_grants_are_independent() { + let mut policies = SharingPolicies::default(); + let recipient = identity("org.consumer", "SHA256:consumer", "profile-a"); + policies + .set_activation_grants( + &recipient, + ActivationReadGrant::new([], ["record-only".to_owned()]).unwrap(), + ) + .unwrap(); + let request = selector( + &[CommonDataCategory::GamePerformanceHistory], + &["record-only", "category-ungranted"], + ); + let selected = policies + .authorize_common_query(&recipient, Some(&request)) + .unwrap(); + assert!(!selected.includes_category(CommonDataCategory::GamePerformanceHistory)); + assert!(SharingPolicies::common_record_in_query( + &selected, + CommonDataCategory::GamePaths, + "record-only" + )); + assert!(!SharingPolicies::common_record_in_query( + &selected, + CommonDataCategory::GamePaths, + "category-ungranted" + )); + } + + #[test] + fn authorizer_requires_exact_explicit_common_scope_and_projects_safe_fields() { + let recipient = identity("org.consumer", "SHA256:consumer", "profile-a"); + let source = identity("org.source", "SHA256:source", "profile-a"); + let mut policies = SharingPolicies::default(); + policies + .set_activation_grants( + &recipient, + ActivationReadGrant::new( + [CommonDataCategory::GamePaths], + ["record-selected".into()], + ) + .unwrap(), + ) + .unwrap(); + + let available = [ + "game.path".to_owned(), + "game.token".to_owned(), + "metadata.note".to_owned(), + ] + .into_iter() + .collect(); + let request = AccessRequest { + recipient: &recipient, + source: &source, + record_id: "record-selected", + dataset_id: "games", + category: Some(CommonDataCategory::GamePaths), + scope: AccessScope::SelectedRecord("record-selected".into()), + class: SharingClass::Common, + fields: &available, + delivery: Delivery::Query, + }; + let selected = policies.decide(&request); + assert!(selected.allowed); + assert_eq!( + selected.fields, + ["game.path", "metadata.note"] + .into_iter() + .map(str::to_owned) + .collect() + ); + assert_eq!(selected.revision, policies.revision(&recipient)); + + let category_query = AccessRequest { + record_id: "another-published-record", + scope: AccessScope::Category(CommonDataCategory::GamePaths), + ..request.clone() + }; + assert!(policies.decide(&category_query).allowed); + + let category_without_grant = AccessRequest { + scope: AccessScope::Category(CommonDataCategory::GamePerformanceHistory), + category: Some(CommonDataCategory::GamePerformanceHistory), + ..request + }; + assert!(!policies.decide(&category_without_grant).allowed); + } + + #[test] + fn authorizer_applies_per_field_history_and_live_grants() { + let source = identity("org.source", "SHA256:source", "profile-a"); + let recipient = identity("org.consumer", "SHA256:consumer", "profile-a"); + let mut policies = SharingPolicies::default(); + policies + .set_source_recipient_policy( + SourceRecipientPolicy::new( + source.clone(), + recipient.clone(), + SharingClass::Sensitive, + "hardware".into(), + ["device.model".into()], + true, + false, + ) + .unwrap(), + ) + .unwrap(); + let available = ["device.model".to_owned(), "device.serial".to_owned()] + .into_iter() + .collect(); + let request = AccessRequest { + recipient: &recipient, + source: &source, + record_id: "hardware-record", + dataset_id: "hardware", + category: None, + scope: AccessScope::Dataset("hardware".into()), + class: SharingClass::Sensitive, + fields: &available, + delivery: Delivery::History, + }; + + let history = policies.decide(&request); + assert!(history.allowed); + assert_eq!( + history.fields, + ["device.model".to_owned()].into_iter().collect() + ); + assert!(history.history); + assert!(!history.live); + + let live_request = AccessRequest { + delivery: Delivery::Live, + ..request.clone() + }; + assert!(!policies.decide(&live_request).allowed); + + let foreign_source = identity("org.source", "SHA256:rotated", "profile-a"); + let foreign_request = AccessRequest { + source: &foreign_source, + ..request + }; + assert!(!policies.decide(&foreign_request).allowed); + } + + #[test] + fn sensitive_and_custom_dataset_scope_requires_exact_dataset_and_delivery_grants() { + let source = identity("org.source", "SHA256:source", "profile-a"); + let recipient = identity("org.consumer", "SHA256:consumer", "profile-a"); + let mut policies = SharingPolicies::default(); + policies + .set_source_recipient_policy( + SourceRecipientPolicy::new( + source.clone(), + recipient.clone(), + SharingClass::Custom, + "org.source.metrics".into(), + ["fps.average".into()], + true, + true, + ) + .unwrap(), + ) + .unwrap(); + let fields = ["fps.average".to_owned()].into_iter().collect(); + let request = AccessRequest { + recipient: &recipient, + source: &source, + record_id: "record-9", + dataset_id: "org.source.metrics", + category: None, + scope: AccessScope::Dataset("org.source.metrics".into()), + class: SharingClass::Custom, + fields: &fields, + delivery: Delivery::Query, + }; + + for delivery in [Delivery::Query, Delivery::History, Delivery::Live] { + assert!( + policies + .decide(&AccessRequest { + delivery, + ..request.clone() + }) + .allowed + ); + } + + let wrong_dataset = AccessRequest { + scope: AccessScope::Dataset("org.source.other".into()), + ..request.clone() + }; + assert!(!policies.decide(&wrong_dataset).allowed); + + let category_scope = AccessRequest { + category: Some(CommonDataCategory::GamePaths), + scope: AccessScope::Category(CommonDataCategory::GamePaths), + ..request.clone() + }; + assert!(!policies.decide(&category_scope).allowed); + let selected_record_scope = AccessRequest { + scope: AccessScope::SelectedRecord("record-9".into()), + ..request.clone() + }; + assert!(!policies.decide(&selected_record_scope).allowed); + + let common_dataset_scope = AccessRequest { + class: SharingClass::Common, + ..request + }; + assert!(!policies.decide(&common_dataset_scope).allowed); + } + + #[test] + fn malformed_selector_categories_and_records_are_rejected() { + let policies = SharingPolicies::default(); + let recipient = identity("org.consumer", "SHA256:consumer", "profile-a"); + let unspecified = CommonDataSelector { + categories: vec![CommonDataCategory::Unspecified as i32], + selected_record_ids: Vec::new(), + }; + assert_eq!( + policies.authorize_common_query(&recipient, Some(&unspecified)), + Err(SharingPolicyError::Selector(SelectorError::Unspecified)) + ); + let duplicate_record = CommonDataSelector { + categories: Vec::new(), + selected_record_ids: vec!["same".into(), "same".into()], + }; + assert_eq!( + policies.authorize_common_query(&recipient, Some(&duplicate_record)), + Err(SharingPolicyError::Selector( + SelectorError::DuplicateRecordId + )) + ); + assert!( + ActivationReadGrant::new([CommonDataCategory::Unspecified], std::iter::empty()) + .is_err() + ); + } + + #[test] + fn exact_plugin_publisher_and_profile_identity_is_required() { + let mut policies = SharingPolicies::default(); + let recipient = identity("org.consumer", "SHA256:consumer", "profile-a"); + policies + .set_activation_grants( + &recipient, + ActivationReadGrant::new([CommonDataCategory::RuntimeCatalog], std::iter::empty()) + .unwrap(), + ) + .unwrap(); + let changed_publisher = identity("org.consumer", "SHA256:other", "profile-a"); + let changed_profile = identity("org.consumer", "SHA256:consumer", "profile-b"); + let query = selector(&[CommonDataCategory::RuntimeCatalog], &[]); + for foreign in [&changed_publisher, &changed_profile] { + let selection = policies + .authorize_common_query(foreign, Some(&query)) + .unwrap(); + assert!(!selection.includes_category(CommonDataCategory::RuntimeCatalog)); + } + } + + #[test] + fn policy_revision_increases_when_grants_change_and_fences_revocation() { + let source = identity("org.source", "SHA256:source", "profile-a"); + let recipient = identity("org.consumer", "SHA256:consumer", "profile-a"); + let mut policies = SharingPolicies::default(); + assert_eq!(policies.revision(&recipient), 0); + policies + .set_activation_grants( + &recipient, + ActivationReadGrant::new([CommonDataCategory::GamePaths], std::iter::empty()) + .unwrap(), + ) + .unwrap(); + let activation_revision = policies.revision(&recipient); + assert_eq!(activation_revision, 1); + + policies + .set_source_recipient_policy( + SourceRecipientPolicy::new( + source.clone(), + recipient.clone(), + SharingClass::Sensitive, + "org.source.device".into(), + ["device.model".into()], + false, + false, + ) + .unwrap(), + ) + .unwrap(); + assert_eq!(policies.revision(&recipient), activation_revision + 1); + assert!( + policies + .revoke_source_recipient_policy( + &source, + &recipient, + SharingClass::Sensitive, + "org.source.device", + ) + .unwrap() + ); + assert_eq!(policies.revision(&recipient), activation_revision + 2); + } + + #[test] + fn sensitive_and_custom_fields_are_scoped_and_history_live_are_separate() { + let source = identity("org.source", "SHA256:source", "profile-a"); + let recipient = identity("org.consumer", "SHA256:consumer", "profile-a"); + let mut policies = SharingPolicies::default(); + policies + .set_source_recipient_policy( + SourceRecipientPolicy::new( + source.clone(), + recipient.clone(), + SharingClass::Custom, + "org.source.dataset".into(), + ["summary.fps".into(), "summary.platform".into()], + false, + true, + ) + .unwrap(), + ) + .unwrap(); + + assert!( + policies + .allows_source_delivery( + &source, + &recipient, + SharingClass::Custom, + "org.source.dataset", + "summary.fps", + Delivery::Query, + ) + .unwrap() + ); + assert!( + !policies + .allows_source_delivery( + &source, + &recipient, + SharingClass::Custom, + "org.source.dataset", + "summary.fps", + Delivery::History, + ) + .unwrap() + ); + assert!( + policies + .allows_source_delivery( + &source, + &recipient, + SharingClass::Custom, + "org.source.dataset", + "summary.fps", + Delivery::Live, + ) + .unwrap() + ); + assert!( + !policies + .allows_source_delivery( + &source, + &recipient, + SharingClass::Custom, + "org.source.dataset", + "summary.platform.extra", + Delivery::Query, + ) + .unwrap() + ); + assert!( + !policies + .allows_source_delivery( + &source, + &recipient, + SharingClass::Sensitive, + "org.source.dataset", + "summary.fps", + Delivery::Query, + ) + .unwrap() + ); + } + + #[test] + fn secret_and_malformed_fields_are_rejected() { + let source = identity("org.source", "SHA256:source", "profile-a"); + let recipient = identity("org.consumer", "SHA256:consumer", "profile-a"); + for secret_field in [ + "api_key", + "refresh.token", + "nested.passwordHash", + "auth-cookie", + ] { + assert_eq!( + SourceRecipientPolicy::new( + source.clone(), + recipient.clone(), + SharingClass::Sensitive, + "org.source.dataset".into(), + [secret_field.into()], + true, + true, + ) + .unwrap_err(), + SharingPolicyError::InvalidFields + ); + } + assert!( + SourceRecipientPolicy::new( + source, + recipient, + SharingClass::Sensitive, + "org.source.dataset".into(), + ["field..name".into()], + true, + false, + ) + .is_err() + ); + } + + #[test] + fn common_and_source_recipient_grants_survive_reopen_and_revocation() { + let directory = tempfile::tempdir().unwrap(); + let source = identity("org.source", "SHA256:source", "profile-a"); + let recipient = identity("org.consumer", "SHA256:consumer", "profile-a"); + let selected = selector(&[CommonDataCategory::GamePerformanceHistory], &["record-1"]); + let mut policies = SharingPolicies::open(directory.path()).unwrap(); + policies + .set_activation_grants( + &recipient, + ActivationReadGrant::new( + [CommonDataCategory::GamePerformanceHistory], + ["record-1".into()], + ) + .unwrap(), + ) + .unwrap(); + policies + .set_source_recipient_policy( + SourceRecipientPolicy::new( + source.clone(), + recipient.clone(), + SharingClass::Sensitive, + "hardware".into(), + ["device.model".into()], + true, + false, + ) + .unwrap(), + ) + .unwrap(); + let persisted_revision = policies.revision(&recipient); + drop(policies); + + let mut reopened = SharingPolicies::open(directory.path()).unwrap(); + assert_eq!(reopened.revision(&recipient), persisted_revision); + let common = reopened + .authorize_common_query(&recipient, Some(&selected)) + .unwrap(); + assert!(common.includes_category(CommonDataCategory::GamePerformanceHistory)); + assert!(common.includes_record("record-1")); + assert!( + reopened + .allows_source_delivery( + &source, + &recipient, + SharingClass::Sensitive, + "hardware", + "device.model", + Delivery::History, + ) + .unwrap() + ); + + assert!( + reopened + .revoke_source_recipient_policy( + &source, + &recipient, + SharingClass::Sensitive, + "hardware", + ) + .unwrap() + ); + assert_eq!(reopened.revision(&recipient), persisted_revision + 1); + drop(reopened); + + let reopened = SharingPolicies::open(directory.path()).unwrap(); + assert_eq!(reopened.revision(&recipient), persisted_revision + 1); + assert!( + !reopened + .allows_source_delivery( + &source, + &recipient, + SharingClass::Sensitive, + "hardware", + "device.model", + Delivery::History, + ) + .unwrap() + ); + let common = reopened + .authorize_common_query(&recipient, Some(&selected)) + .unwrap(); + assert!(common.includes_category(CommonDataCategory::GamePerformanceHistory)); + } + + #[test] + fn recipient_policy_replacement_is_atomic_persisted_and_revision_fenced() { + let directory = tempfile::tempdir().unwrap(); + let shared = SharedSharingPolicies::open(directory.path()).unwrap(); + let source = identity("org.source", "SHA256:source", "profile-a"); + let recipient = identity("org.consumer", "SHA256:consumer", "profile-a"); + let policy = SourceRecipientPolicy::new( + source.clone(), + recipient.clone(), + SharingClass::Custom, + "org.source.metrics".into(), + ["fps".into()], + true, + false, + ) + .unwrap(); + let expected_revision = shared.recipient_snapshot(&recipient).unwrap().revision; + let next_revision = shared + .replace_recipient_policies( + &recipient, + expected_revision, + ActivationReadGrant::new( + [CommonDataCategory::GamePerformanceHistory], + ["record-1".into()], + ) + .unwrap(), + vec![policy], + ) + .unwrap(); + assert_eq!(next_revision, expected_revision + 1); + assert!(matches!( + shared.replace_recipient_policies( + &recipient, + expected_revision, + ActivationReadGrant::default(), + Vec::new(), + ), + Err(SharingPolicyError::StaleRevision) + )); + + let snapshot = shared.recipient_snapshot(&recipient).unwrap(); + assert!( + snapshot + .categories + .contains(&CommonDataCategory::GamePerformanceHistory) + ); + assert!(snapshot.selected_record_ids.contains("record-1")); + assert_eq!(snapshot.source_recipient_policies.len(), 1); + assert!( + snapshot.source_recipient_policies[0] + .fields() + .contains("fps") + ); + + let reopened = SharedSharingPolicies::open(directory.path()).unwrap(); + let reopened_snapshot = reopened.recipient_snapshot(&recipient).unwrap(); + assert_eq!(reopened_snapshot, snapshot); + assert!( + reopened + .revoke_source_recipient_policy( + &source, + &recipient, + SharingClass::Custom, + "org.source.metrics", + ) + .unwrap() + ); + assert_eq!( + reopened + .recipient_snapshot(&recipient) + .unwrap() + .source_recipient_policies + .len(), + 0 + ); + } + + #[test] + fn recipient_policy_replacement_rejects_foreign_recipients_and_duplicates() { + let recipient = identity("org.consumer", "SHA256:consumer", "profile-a"); + let other = identity("org.other", "SHA256:other", "profile-a"); + let source = identity("org.source", "SHA256:source", "profile-a"); + let policy = SourceRecipientPolicy::new( + source, + other.clone(), + SharingClass::Custom, + "metrics".into(), + ["fps".into()], + false, + true, + ) + .unwrap(); + let mut policies = SharingPolicies::default(); + assert!(matches!( + policies.replace_recipient_policies( + &recipient, + 0, + ActivationReadGrant::default(), + vec![policy.clone()], + ), + Err(SharingPolicyError::InvalidFields) + )); + assert!(matches!( + policies.replace_recipient_policies( + &other, + 0, + ActivationReadGrant::default(), + vec![policy.clone(), policy], + ), + Err(SharingPolicyError::InvalidFields) + )); + } + + #[test] + fn persistence_rejects_unknown_fields_unsupported_schema_and_oversized_file() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join(STORE_FILE); + fs::write( + &path, + br#"{"schema":1,"activation":[],"source_recipient":[],"revisions":[],"extra":true}"#, + ) + .unwrap(); + assert!(matches!( + SharingPolicies::open(directory.path()), + Err(SharingPolicyError::InvalidStore(_)) + )); + + fs::write( + &path, + br#"{"schema":2,"activation":[],"source_recipient":[],"revisions":[]}"#, + ) + .unwrap(); + assert!(matches!( + SharingPolicies::open(directory.path()), + Err(SharingPolicyError::InvalidStore(message)) if message == "unsupported policy schema" + )); + + fs::write(&path, vec![b'x'; MAX_STORE_BYTES as usize + 1]).unwrap(); + assert!(matches!( + SharingPolicies::open(directory.path()), + Err(SharingPolicyError::InvalidStore(message)) if message == "file exceeds size limit" + )); + } + + #[test] + fn shared_handle_serializes_mutations_and_implements_authorizer() { + let directory = tempfile::tempdir().unwrap(); + let shared = SharedSharingPolicies::open(directory.path()).unwrap(); + let recipient = identity("org.consumer", "SHA256:consumer", "profile-a"); + let source = identity("org.source", "SHA256:source", "profile-a"); + let available = ["runtime.name".to_owned()].into_iter().collect(); + let request = AccessRequest { + recipient: &recipient, + source: &source, + record_id: "runtime-1", + dataset_id: "runtime-catalog", + category: Some(CommonDataCategory::RuntimeCatalog), + scope: AccessScope::Category(CommonDataCategory::RuntimeCatalog), + class: SharingClass::Common, + fields: &available, + delivery: Delivery::Query, + }; + let authorizer: Arc = Arc::new(shared.clone()); + let before = authorizer.revision(&recipient); + assert!(!authorizer.decide(&request).allowed); + + shared + .set_activation_grants( + &recipient, + ActivationReadGrant::new([CommonDataCategory::RuntimeCatalog], std::iter::empty()) + .unwrap(), + ) + .unwrap(); + let granted = authorizer.decide(&request); + assert!(granted.allowed); + assert!(granted.revision > before); + + shared.clear_activation_grants(&recipient).unwrap(); + let revoked = authorizer.decide(&request); + assert!(!revoked.allowed); + assert!(revoked.revision > granted.revision); + } +} diff --git a/crates/app/src/plugin_host/startup.rs b/crates/app/src/plugin_host/startup.rs new file mode 100644 index 000000000..30170b12e --- /dev/null +++ b/crates/app/src/plugin_host/startup.rs @@ -0,0 +1,364 @@ +//! Composition of installed third-party provider packages into the desktop library. +//! +//! The official providers still come from the manifests embedded at build time. A signed package +//! accepted through the reviewed import flow has its own JSON manifest instead, so this host-side +//! step verifies the same registry, publisher pin and compatibility facts the runtime already +//! uses, then derives the minimal provider manifest the library scans: +//! +//! ```toml +//! id = "" +//! name = "" +//! platforms = [""] +//! source = "community" +//! +//! [scan] +//! plugin = "" +//! ``` +//! +//! The official list, its order and its behavior are unchanged: third-party providers are +//! appended after it in plugin-id order, and an id that collides with an official provider is +//! refused. Everything that touches the registry, trust store or package files runs on blocking +//! workers. + +use std::path::{Path, PathBuf}; + +use gamenode_core::provider::{self, Platform, PluginBackend, Provider}; +use gamenode_platform::paths::DataPaths; +use gamenode_platform::plugin_environment::EmulationPolicy; +use gamenode_platform::plugin_registry::{InstalledPluginVersion, PluginPackageRegistry}; +use gamenode_plugin_protocol::capability; + +use super::managed_packages::ManagedPackageLifecycle; +use super::package::ValidatedManifest; +use super::profile::PluginStateLayout; +use super::publisher_trust::{KeyStatus, PublisherTrustStore}; + +/// The provider list the library starts (or continues) with, plus one diagnostic per package +/// that was deliberately skipped. +#[derive(Clone, Debug, Default)] +pub struct LibraryProviders { + pub providers: Vec, + pub diagnostics: Vec, +} + +impl LibraryProviders { + pub fn get(&self, id: &str) -> Option<&Provider> { + self.providers.iter().find(|provider| provider.id() == id) + } +} + +/// One installed third-party provider that passed every host check. +struct ComposedProvider { + plugin_id: String, + provider_id: String, + provider: Provider, +} + +/// The providers the desktop library composes at startup: every official manifest that applies +/// to `platform`, followed by every active, trusted, publisher-pinned, compatible third-party +/// provider package in the registry. +pub async fn load_library_providers(platform: Platform, paths: &DataPaths) -> LibraryProviders { + let mut loaded = crate::providers::load_bundled_with_plugins( + platform, + &crate::plugin_host::backends(platform), + ); + let mut result = LibraryProviders { + providers: std::mem::take(&mut loaded.providers), + diagnostics: loaded.diagnostics.iter().map(ToString::to_string).collect(), + }; + let official: std::collections::BTreeSet = result + .providers + .iter() + .map(|provider| provider.id().to_owned()) + .collect(); + + let registry = paths.plugin_packages_dir(); + let trust_dir = PluginStateLayout::managed(paths).trust_dir(); + let composition = match open_registry(registry).await { + Ok(registry) => compose(platform, registry, trust_dir, None).await, + Err(problem) => Composition { + diagnostics: vec![problem], + ..Default::default() + }, + }; + result.diagnostics.extend(composition.diagnostics); + for entry in composition.eligible { + if official.contains(&entry.provider_id) { + result.diagnostics.push(format!( + "third-party package `{}` was skipped: provider id `{}` is reserved by an official provider", + entry.plugin_id, entry.provider_id + )); + continue; + } + if result.get(&entry.provider_id).is_some() { + result.diagnostics.push(format!( + "third-party package `{}` was skipped: provider id `{}` is already registered", + entry.plugin_id, entry.provider_id + )); + continue; + } + result.providers.push(entry.provider); + } + for diagnostic in &result.diagnostics { + tracing::warn!(%diagnostic, "library provider composition skipped a package"); + } + result +} + +/// Re-reads one installed package after an accepted import. Returns the provider to add to an +/// already running library, or `None` when the package is not a discovery provider. +pub async fn installed_library_provider( + platform: Platform, + paths: &DataPaths, + plugin_id: &str, +) -> Result, String> { + installed_provider_from_registry( + platform, + open_registry(paths.plugin_packages_dir()).await?, + PluginStateLayout::managed(paths).trust_dir(), + plugin_id, + ) + .await +} + +/// The same re-read for callers that already hold the import service's registry and trust paths. +pub(crate) async fn installed_provider_from_registry( + platform: Platform, + registry: PluginPackageRegistry, + trust_dir: PathBuf, + plugin_id: &str, +) -> Result, String> { + let composition = compose(platform, registry, trust_dir, Some(plugin_id)).await; + let mut providers = composition.eligible.into_iter(); + match (providers.next(), providers.next()) { + (None, _) => Ok(None), + (Some(entry), None) => Ok(Some(entry.provider)), + (Some(_), Some(_)) => Err("the installed provider package is ambiguous".to_owned()), + } +} + +async fn open_registry(path: PathBuf) -> Result { + tokio::task::spawn_blocking(move || PluginPackageRegistry::at(path)) + .await + .map_err(|_| "plugin package registry worker failed".to_owned())? + .map_err(|error| format!("plugin package registry is unavailable: {error}")) +} + +#[derive(Default)] +struct Composition { + eligible: Vec, + diagnostics: Vec, +} + +/// Runs the registry, trust and package checks for one provider or every active package. +async fn compose( + platform: Platform, + registry: PluginPackageRegistry, + trust_dir: PathBuf, + only: Option<&str>, +) -> Composition { + let only = only.map(str::to_owned); + let lookup = registry.clone(); + let installed = tokio::task::spawn_blocking(move || lookup.active_versions()) + .await + .map_err(|_| "plugin package registry worker failed".to_owned()) + .and_then(|versions| { + versions.map_err(|error| format!("plugin package registry is unavailable: {error}")) + }); + let installed = match installed { + Ok(installed) => installed, + Err(error) => { + return Composition { + diagnostics: vec![error], + ..Default::default() + }; + } + }; + let trust = tokio::task::spawn_blocking(move || PublisherTrustStore::open(trust_dir)) + .await + .map_err(|_| "publisher trust worker failed".to_owned()) + .and_then(|trust| { + trust.map_err(|error| format!("publisher trust store is unavailable: {error}")) + }); + let trust = match trust { + Ok(trust) => trust, + Err(error) => { + return Composition { + diagnostics: vec![error], + ..Default::default() + }; + } + }; + let packages = ManagedPackageLifecycle::new(registry); + let mut composition = Composition::default(); + for installed in installed { + if only + .as_deref() + .is_some_and(|plugin_id| plugin_id != installed.plugin_id) + { + continue; + } + let plugin_id = installed.plugin_id.clone(); + match compose_one(platform, installed, &trust, &packages).await { + Ok(entry) => composition.eligible.push(entry), + Err(problem) => { + tracing::warn!(%problem, %plugin_id, "third-party provider package is not eligible for the library"); + composition + .diagnostics + .push(format!("package `{plugin_id}`: {problem}")); + } + } + } + composition + .eligible + .sort_by(|left, right| left.plugin_id.cmp(&right.plugin_id)); + composition +} + +async fn compose_one( + platform: Platform, + installed: InstalledPluginVersion, + trust: &PublisherTrustStore, + packages: &ManagedPackageLifecycle, +) -> Result { + let manifest = read_manifest(&installed).await?; + let package = manifest.manifest(); + if package.id != installed.plugin_id || package.version != installed.version { + return Err(format!( + "plugin package `{}` does not match its registry record", + installed.plugin_id + )); + } + if package.kind != super::package::PluginKind::Provider { + return Err(format!( + "plugin package `{}` is not a provider", + installed.plugin_id + )); + } + if !package + .permissions + .iter() + .any(|permission| permission.id == capability::DISCOVERY) + { + return Err(format!( + "plugin package `{}` does not declare `{}`", + installed.plugin_id, + capability::DISCOVERY + )); + } + let provider_id = package + .provider_id + .clone() + .ok_or_else(|| "provider package has no provider id".to_owned())?; + let publisher_key = manifest.publisher_key(); + match trust + .inspect(&installed.plugin_id, &publisher_key) + .map_err(|error| format!("publisher trust status is unavailable: {error}"))? + { + KeyStatus::Trusted { .. } => {} + KeyStatus::Untrusted { .. } => { + return Err(format!( + "plugin package `{}` has an untrusted publisher", + installed.plugin_id + )); + } + KeyStatus::Changed { .. } => { + return Err(format!( + "plugin package `{}` has a changed publisher key", + installed.plugin_id + )); + } + } + let report = packages + .inspect_candidate( + &installed.package_path, + publisher_key, + EmulationPolicy::RequireNative, + ) + .await + .map_err(|error| { + format!( + "plugin package `{}` is invalid: {error}", + installed.plugin_id + ) + })?; + report.selected_target().map_err(|error| { + format!( + "plugin package `{}` is incompatible: {error}", + installed.plugin_id + ) + })?; + + let backend = PluginBackend { + plugin_id: installed.plugin_id.clone(), + provider_id: provider_id.clone(), + discovery: true, + catalog: false, + counter: false, + actions: false, + achievements: false, + }; + let synthetic = synthetic_manifest(&provider_id, &package.name, platform, &backend.plugin_id); + let loaded = provider::load_with_plugins( + &[("community-provider.toml", synthetic.as_str())], + platform, + std::slice::from_ref(&backend), + ); + let provider = loaded.providers.into_iter().next().ok_or_else(|| { + loaded + .diagnostics + .iter() + .map(ToString::to_string) + .collect::>() + .join("; ") + })?; + Ok(ComposedProvider { + plugin_id: installed.plugin_id, + provider_id, + provider, + }) +} + +async fn read_manifest(installed: &InstalledPluginVersion) -> Result { + let root = installed.package_path.clone(); + tokio::task::spawn_blocking(move || read_manifest_blocking(&root)) + .await + .map_err(|_| "plugin manifest worker failed".to_owned())? +} + +/// Reads the same bounded, non-symlink manifest the runtime composition reads. +fn read_manifest_blocking(package_root: &Path) -> Result { + let path = package_root.join("plugin.json"); + let metadata = std::fs::symlink_metadata(&path) + .map_err(|error| format!("plugin manifest unavailable: {error}"))?; + if !metadata.is_file() || metadata.file_type().is_symlink() || metadata.len() > 4 * 1024 * 1024 + { + return Err("plugin manifest is not a bounded regular file".to_owned()); + } + let bytes = + std::fs::read(path).map_err(|error| format!("plugin manifest unavailable: {error}"))?; + super::package::Manifest::parse_json(&bytes) + .map_err(|error| format!("plugin manifest is invalid: {error}")) +} + +fn synthetic_manifest( + provider_id: &str, + name: &str, + platform: Platform, + plugin_id: &str, +) -> String { + format!( + "id = {provider_id:?}\nname = {name:?}\nplatforms = [{platform:?}]\nsource = \"community\"\n\n[scan]\nplugin = {plugin_id:?}\n", + platform = platform_name(platform) + ) +} + +fn platform_name(platform: Platform) -> &'static str { + match platform { + Platform::Windows => "windows", + Platform::Linux => "linux", + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/app/src/plugin_host/startup/tests.rs b/crates/app/src/plugin_host/startup/tests.rs new file mode 100644 index 000000000..139cc8677 --- /dev/null +++ b/crates/app/src/plugin_host/startup/tests.rs @@ -0,0 +1,1034 @@ +//! Regression coverage for composing installed third-party provider packages into the library. +//! +//! The bug this covers: the desktop built `LibraryMachine` from the embedded official manifests +//! only, while an installed third-party provider lived in the package registry and was registered +//! with the runtime. These tests install real signed fixture packages into a temporary registry and +//! drive the same startup and post-import composition the binary uses, through the library scan +//! effects and a real SQLite library store. + +use std::collections::{BTreeMap, VecDeque}; +use std::path::{Path, PathBuf}; +use std::sync::Mutex; + +use base64::Engine as _; +use gamenode_core::library::{ + Effect, Input, LastAccount, LibraryCache, LibraryMachine, LibraryStore, ScanOutcome, +}; +use gamenode_platform::db::SqliteSettingsStore; +use gamenode_platform::paths::DataPaths; +use gamenode_platform::plugin_registry::PluginPackageRegistry; +use gamenode_plugin_protocol::models; +use gamenode_plugin_protocol::proto::{ + DiscoveryRecord, DiscoveryResult, OperationDisposition, OperationResult, ProviderOperation, +}; +use tonic::Status; + +use super::*; +use crate::plugin_host::provider::Completion; +use crate::plugin_host::publisher_trust; +use crate::plugin_host::runtime::{Observer, ProviderRuntime}; +use crate::plugin_host::updates::{PluginImportInstallOutcome, PluginUpdateService}; + +const FIXTURE_PLUGIN: &str = "dev.example.third-party-provider"; +const FIXTURE_PROVIDER: &str = "third-party-fixture"; +const FIXTURE_VERSION: &str = "1.0.0"; + +/// Runs the repository package tool; the fixture key and every archive are real tool output. +fn package_tool(work: &Path, args: &[&str]) -> String { + let script = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../scripts/plugin-package.py"); + assert!(script.is_file(), "missing plugin package tool: {script:?}"); + let output = std::process::Command::new("python3") + .arg(&script) + .args(args) + .current_dir(work) + .output() + .expect("python3 with the cryptography package must run the package fixture tooling"); + assert!( + output.status.success(), + "plugin-package.py {args:?} failed: {}", + String::from_utf8_lossy(&output.stderr) + ); + String::from_utf8(output.stdout).unwrap() +} + +struct Fixture { + dir: tempfile::TempDir, + key: PathBuf, + public_key: String, + key_bytes: [u8; 32], +} + +impl Fixture { + fn new() -> Self { + let dir = tempfile::tempdir().unwrap(); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt as _; + std::fs::set_permissions(dir.path(), std::fs::Permissions::from_mode(0o700)).unwrap(); + } + let key = dir.path().join("fixture-dev.pem"); + let output = package_tool( + dir.path(), + &[ + "keygen", + "--development", + "--private-key", + key.to_str().unwrap(), + ], + ); + let public_key = output + .lines() + .find_map(|line| line.strip_prefix("publisher.public_key (base64): ")) + .expect("keygen prints the fixture publisher key") + .to_owned(); + let key_bytes: [u8; 32] = base64::engine::general_purpose::STANDARD + .decode(&public_key) + .unwrap() + .try_into() + .unwrap(); + Self { + dir, + key, + public_key, + key_bytes, + } + } + + fn fingerprint(&self) -> String { + publisher_trust::key_fingerprint(&self.key_bytes) + } + + /// A signed provider package. `provider_id` defaults to the fixture provider. + fn provider(&self, name: &str, provider_id: Option<&str>, discovery: bool) -> Package { + self.provider_as( + FIXTURE_PLUGIN, + name, + provider_id.unwrap_or(FIXTURE_PROVIDER), + discovery, + "linux", + ) + } + + fn provider_as( + &self, + plugin_id: &str, + name: &str, + provider_id: &str, + discovery: bool, + os: &str, + ) -> Package { + let mut permissions = vec![serde_json::json!({ + "id": "provider.context.read", + "required": true, + "scope": "own-provider", + "reason": "Read the host-issued provider context." + })]; + if discovery { + permissions.push(serde_json::json!({ + "id": "library.discovery", + "required": false, + "scope": "own-provider", + "reason": "Discover this provider's games." + })); + } + self.package( + plugin_id, + name, + "provider", + Some(provider_id), + permissions, + os, + "1.6.0", + ) + } + + fn extension(&self, plugin_id: &str, name: &str) -> Package { + self.package( + plugin_id, + name, + "extension", + None, + vec![serde_json::json!({ + "id": "game.launch", + "required": false, + "scope": "own-provider", + "reason": "Launch a game." + })], + "linux", + "1.6.0", + ) + } + + #[allow(clippy::too_many_arguments)] // A test package fixture with its identity and permissions. + fn package( + &self, + plugin_id: &str, + name: &str, + kind: &str, + provider_id: Option<&str>, + permissions: Vec, + os: &str, + api_min: &str, + ) -> Package { + let slug = name.to_ascii_lowercase().replace([' ', '/'], "-"); + let source = self.dir.path().join(format!("{slug}-source")); + std::fs::create_dir_all(source.join("bin")).unwrap(); + std::fs::create_dir_all(source.join("licenses")).unwrap(); + std::fs::write(source.join("bin/plugin"), b"fixture executable").unwrap(); + std::fs::write(source.join("licenses/LICENSE"), b"fixture license").unwrap(); + let mut manifest = serde_json::json!({ + "schema": 1, + "id": plugin_id, + "kind": kind, + "name": name, + "version": FIXTURE_VERSION, + "api": { "min": api_min, "max": "1.6.0" }, + "permissions": permissions, + "targets": [{ + "os": os, + "arch": "x86_64", + "abi": "gnu", + "entrypoint": "bin/plugin" + }], + "publisher": { + "key_id": "fixture-dev", + "public_key": self.public_key + }, + "license": { "expression": "MIT", "files": ["licenses/LICENSE"] } + }); + if let Some(provider_id) = provider_id { + manifest["provider_id"] = serde_json::json!(provider_id); + } + std::fs::write( + source.join("plugin.json"), + serde_json::to_vec(&manifest).unwrap(), + ) + .unwrap(); + let archive = self.dir.path().join(format!("{slug}.gnplugin")); + package_tool( + self.dir.path(), + &[ + "pack", + "--source", + source.to_str().unwrap(), + "--output", + archive.to_str().unwrap(), + "--private-key", + self.key.to_str().unwrap(), + ], + ); + // `pack` writes the signed metadata into the archive, not the source directory. The + // reviewed import stages the extracted archive; do the same for direct registry installs. + let staged = self.dir.path().join(format!("{slug}-staged")); + extract_archive(&archive, &staged); + Package { archive, staged } + } +} + +struct Package { + archive: PathBuf, + /// The archive contents, including `integrity.json` and `signature.ed25519`. + staged: PathBuf, +} + +fn extract_archive(archive: &Path, dest: &Path) { + let file = std::fs::File::open(archive).unwrap(); + let mut zip = zip::ZipArchive::new(file).unwrap(); + for index in 0..zip.len() { + let mut entry = zip.by_index(index).unwrap(); + let name = entry + .enclosed_name() + .unwrap_or_else(|| panic!("unsafe archive path: {}", entry.name())); + let path = dest.join(name); + if entry.is_dir() { + std::fs::create_dir_all(&path).unwrap(); + continue; + } + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent).unwrap(); + } + let mut out = std::fs::File::create(&path).unwrap(); + std::io::copy(&mut entry, &mut out).unwrap(); + } +} + +fn paths() -> (tempfile::TempDir, DataPaths) { + let dir = tempfile::tempdir().unwrap(); + let paths = DataPaths::at(dir.path().join("app-data")); + paths.ensure_data_dir().unwrap(); + crate::plugin_host::profile::PluginStateLayout::prepare_managed(&paths).unwrap(); + (dir, paths) +} + +fn trust(fixture: &Fixture, paths: &DataPaths, plugin_id: &str) { + let dir = crate::plugin_host::profile::PluginStateLayout::managed(paths).trust_dir(); + let mut store = publisher_trust::PublisherTrustStore::open(dir).unwrap(); + store + .confirm_first_key(plugin_id, &fixture.key_bytes, &fixture.fingerprint()) + .unwrap(); +} + +/// Installs a signed provider package directly into the immutable registry, exactly as an +/// accepted import leaves it. +fn install_signed(fixture: &Fixture, paths: &DataPaths, plugin_id: &str, package: &Package) { + let registry = PluginPackageRegistry::open(paths).unwrap(); + registry + .install_signed_with_entrypoint( + plugin_id, + FIXTURE_VERSION, + &package.staged, + &fixture.key_bytes, + "bin/plugin", + true, + ) + .unwrap(); +} + +/// Installs an arbitrary package directory without signature validation. Used only to model the +/// malformed and reserved-id entries a corrupt or legacy registry can contain; the reviewed +/// import flow refuses these before any registry write. +fn install_unverified(paths: &DataPaths, plugin_id: &str, package_root: &Path) { + let registry = PluginPackageRegistry::open(paths).unwrap(); + registry + .install_verified(plugin_id, FIXTURE_VERSION, package_root, true) + .unwrap(); +} + +fn library_store(paths: &DataPaths) -> std::sync::Arc { + let settings = SqliteSettingsStore::open(&paths.database_file()).unwrap(); + std::sync::Arc::new(settings.library_store()) +} + +fn account() -> LastAccount { + LastAccount { + id: "fixture-account".to_owned(), + name: "Fixture Account".to_owned(), + } +} + +/// Starts the library for one account and returns the initial scan effects. +fn start_machine(providers: Vec) -> (LibraryMachine, Vec) { + let mut machine = LibraryMachine::new(providers, Default::default()); + let effects = machine.handle(Input::AccountChanged(Some(account()))); + let op = effects + .iter() + .find_map(|effect| match effect { + Effect::LoadCache { op, .. } => Some(*op), + _ => None, + }) + .expect("the account load starts with a cache read"); + let effects = machine.handle(Input::Loaded { + op, + result: Ok(LibraryCache::default()), + }); + (machine, effects) +} + +/// A provider runtime whose answer is controlled per provider. Official providers scan empty; +/// the fixture provider reports the configured records or failure. +struct FixtureRuntime { + provider: String, + records: Mutex>, + failure: Mutex>, + discoveries: Mutex>, +} + +impl FixtureRuntime { + fn new(provider: &str) -> Self { + Self { + provider: provider.to_owned(), + records: Mutex::new(Vec::new()), + failure: Mutex::new(None), + discoveries: Mutex::new(Vec::new()), + } + } + + fn set_records(&self, records: Vec) { + *self.records.lock().unwrap() = records; + } + + fn fail(&self, reason: &str) { + *self.failure.lock().unwrap() = Some(reason.to_owned()); + } + + fn discoveries(&self) -> Vec { + self.discoveries.lock().unwrap().clone() + } +} + +#[async_trait::async_trait] +impl ProviderRuntime for FixtureRuntime { + fn accounts(&self) -> Vec { + Vec::new() + } + fn has_provider(&self, _provider: &str) -> bool { + true + } + fn status(&self, _provider: &str) -> Option { + None + } + fn available(&self, _provider: &str) -> bool { + true + } + fn set_observer(&self, _observer: Observer) {} + async fn shutdown(&self) {} + async fn execute( + &self, + provider: &str, + operation: ProviderOperation, + ) -> Result { + if operation != ProviderOperation::Discover { + return Ok(Completion::fixture( + OperationResult { + disposition: OperationDisposition::Completed as i32, + ..Default::default() + }, + Default::default(), + )); + } + if provider == self.provider { + self.discoveries.lock().unwrap().push(provider.to_owned()); + if let Some(reason) = self.failure.lock().unwrap().clone() { + return Err(Status::unavailable(reason)); + } + } + let records = if provider == self.provider { + self.records.lock().unwrap().clone() + } else { + Vec::new() + }; + Ok(Completion::fixture( + OperationResult { + disposition: OperationDisposition::Completed as i32, + discovery: Some(DiscoveryResult { + provider_id: provider.to_owned(), + records, + ..Default::default() + }), + ..Default::default() + }, + Default::default(), + )) + } +} + +/// Drives the machine's scan effects through the runtime and persists the outcomes, mirroring the +/// engine's `LibEffect::RunScan` / `LibEffect::PersistScan` path without a network or account. +async fn drive( + machine: &mut LibraryMachine, + runtime: &dyn ProviderRuntime, + store: &dyn LibraryStore, + effects: Vec, +) { + let mut queue: VecDeque = effects.into(); + while let Some(effect) = queue.pop_front() { + match effect { + Effect::RunScan { op, provider } => { + let result = match runtime + .execute(&provider, ProviderOperation::Discover) + .await + { + Ok(completion) => completion + .result + .discovery + .filter(|discovery| discovery.provider_id == provider) + .map(|discovery| { + gamenode_core::provider::record::finish_records( + &provider, + discovery + .records + .into_iter() + .map(|record| gamenode_core::provider::RawRecord { + id: Some(record.id), + name: Some(record.name), + install_dir: Some(record.install_dir), + fields: record.fields.into_iter().collect(), + }) + .collect(), + &[], + ) + }) + .ok_or_else(|| "provider discovery returned no observations".to_owned()), + Err(status) => Err(status.message().to_owned()), + }; + let more = machine.handle(Input::ProviderScanned { + op, + provider, + result, + targets: BTreeMap::new(), + now: 100, + }); + queue.extend(more); + } + Effect::PersistScan { + provider, + outcome, + now, + } => match outcome { + ScanOutcome::Scanned { records, targets } => { + store.save_scan(&provider, &records, &targets, now).unwrap(); + } + ScanOutcome::Failed(error) => store.save_scan_failure(&provider, &error).unwrap(), + }, + _ => {} + } + } +} + +fn row(paths: &DataPaths, provider: &str) -> Option<(Option, Option)> { + let conn = gamenode_platform::db::open(&paths.database_file()).unwrap(); + conn.query_row( + "SELECT last_success_at, last_error FROM provider_scans WHERE provider = ?1", + [provider], + |row| Ok((row.get(0)?, row.get(1)?)), + ) + .ok() +} + +fn library_entry(paths: &DataPaths, key: &str) -> Option<(String, String, bool)> { + let conn = gamenode_platform::db::open(&paths.database_file()).unwrap(); + conn.query_row( + "SELECT provider, name, installed FROM library_entries WHERE key = ?1", + [key], + |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)), + ) + .ok() +} + +fn official_providers(platform: Platform) -> Vec { + crate::providers::load_bundled_with_plugins(platform, &crate::plugin_host::backends(platform)) + .providers +} + +/// The regression the bug escaped: the binary's own startup composition must include an already +/// installed third-party provider, and the library scan must list its records. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn startup_composition_loads_an_installed_provider_into_the_library_and_scans_it() { + let (_dir, paths) = paths(); + let fixture = Fixture::new(); + let package = fixture.provider("Third Party Fixture", Some(FIXTURE_PROVIDER), true); + install_signed(&fixture, &paths, FIXTURE_PLUGIN, &package); + trust(&fixture, &paths, FIXTURE_PLUGIN); + + let composed = load_library_providers(Platform::Linux, &paths).await; + assert!( + composed.diagnostics.is_empty(), + "{:?}", + composed.diagnostics + ); + let provider = composed + .get(FIXTURE_PROVIDER) + .expect("the installed provider joins the startup library list"); + assert_eq!(provider.name(), "Third Party Fixture"); + assert_eq!(provider.source(), "community"); + assert_eq!(provider.discovery_plugin(), Some(FIXTURE_PLUGIN)); + + // The official providers are the same entries, in the same order, with their backends. + let official = official_providers(Platform::Linux); + assert_eq!( + composed + .providers + .iter() + .take(official.len()) + .map(|provider| provider.id()) + .collect::>(), + official + .iter() + .map(|provider| provider.id()) + .collect::>() + ); + assert_eq!(composed.providers.len(), official.len() + 1); + + let store = library_store(&paths); + let (mut machine, effects) = start_machine(composed.providers); + let runtime = FixtureRuntime::new(FIXTURE_PROVIDER); + runtime.set_records(vec![DiscoveryRecord { + id: "FIXTURE-1".to_owned(), + name: "Fixture Game".to_owned(), + install_dir: "/fixtures/Fixture Game".to_owned(), + ..Default::default() + }]); + drive(&mut machine, &runtime, store.as_ref(), effects).await; + + assert_eq!(runtime.discoveries(), [FIXTURE_PROVIDER]); + let entry = machine + .entry(&format!("{FIXTURE_PROVIDER}:FIXTURE-1")) + .expect("the scan added the provider's record"); + assert_eq!(entry.name.as_deref(), Some("Fixture Game")); + assert!(entry.installed); + assert_eq!( + machine + .scan_state(FIXTURE_PROVIDER) + .and_then(|state| state.last_success_at), + Some(100) + ); + let (success, error) = row(&paths, FIXTURE_PROVIDER).expect("provider_scans has a row"); + assert_eq!(success, Some(100)); + assert_eq!(error, None); + assert_eq!( + library_entry(&paths, &format!("{FIXTURE_PROVIDER}:FIXTURE-1")), + Some((FIXTURE_PROVIDER.to_owned(), "Fixture Game".to_owned(), true)) + ); + let view = machine.view().expect("the library view is available"); + assert!( + view.providers + .iter() + .any(|provider| provider.id == FIXTURE_PROVIDER && provider.count == 1), + "{:?}", + view.providers + ); +} + +/// The reviewed import path: install a signed package at runtime, add it to the existing library, +/// request a scan, and keep the previous machine and its records. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn importing_a_provider_at_runtime_adds_and_scans_it_without_a_new_machine() { + let (_dir, paths) = paths(); + let fixture = Fixture::new(); + let package = fixture.provider("Imported Fixture", Some(FIXTURE_PROVIDER), true); + trust(&fixture, &paths, FIXTURE_PLUGIN); + + // Start with the official providers only, exactly like a host whose registry is empty. + let composed = load_library_providers(Platform::Linux, &paths).await; + assert!(composed.get(FIXTURE_PROVIDER).is_none()); + let store = library_store(&paths); + let (mut machine, effects) = start_machine(composed.providers); + let runtime = FixtureRuntime::new(FIXTURE_PROVIDER); + drive(&mut machine, &runtime, store.as_ref(), effects).await; + assert!( + machine + .providers() + .iter() + .all(|p| p.id() != FIXTURE_PROVIDER) + ); + + // The reviewed import installs and pins the package. Registration/activation needs a composed + // host, which this library-level test deliberately does not build. + let service = import_service(&paths); + let outcome = reviewed_import(&service, &fixture, &package).await; + assert_eq!(outcome.plugin_id, FIXTURE_PLUGIN); + + // The app's post-import callback re-reads the installed package and adds it to the same + // machine; no new LibraryMachine and no restart. + let provider = service + .library_provider(FIXTURE_PLUGIN) + .await + .unwrap() + .expect("the imported provider composes"); + assert_eq!(provider.id(), FIXTURE_PROVIDER); + machine.put_provider(provider); + assert_eq!( + machine + .providers() + .iter() + .filter(|provider| provider.id() == FIXTURE_PROVIDER) + .count(), + 1 + ); + + runtime.set_records(vec![DiscoveryRecord { + id: "IMPORTED-1".to_owned(), + name: "Imported Game".to_owned(), + install_dir: "/fixtures/Imported Game".to_owned(), + ..Default::default() + }]); + let effects = machine.handle(Input::ScanRequested); + drive(&mut machine, &runtime, store.as_ref(), effects).await; + + assert_eq!(runtime.discoveries(), [FIXTURE_PROVIDER]); + assert!( + machine + .entry(&format!("{FIXTURE_PROVIDER}:IMPORTED-1")) + .is_some_and(|entry| entry.installed) + ); + let (success, error) = row(&paths, FIXTURE_PROVIDER).expect("provider_scans has a row"); + assert_eq!(success, Some(100)); + assert_eq!(error, None); +} + +/// A failed scan after the provider joined the library keeps the previous records and stores the +/// provider error. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_failed_scan_keeps_the_previous_records_and_reports_the_provider_error() { + let (_dir, paths) = paths(); + let fixture = Fixture::new(); + let package = fixture.provider("Failing Fixture", Some(FIXTURE_PROVIDER), true); + install_signed(&fixture, &paths, FIXTURE_PLUGIN, &package); + trust(&fixture, &paths, FIXTURE_PLUGIN); + + let composed = load_library_providers(Platform::Linux, &paths).await; + let store = library_store(&paths); + let (mut machine, effects) = start_machine(composed.providers); + let runtime = FixtureRuntime::new(FIXTURE_PROVIDER); + runtime.set_records(vec![DiscoveryRecord { + id: "KEPT-1".to_owned(), + name: "Kept Game".to_owned(), + install_dir: "/fixtures/Kept Game".to_owned(), + ..Default::default() + }]); + drive(&mut machine, &runtime, store.as_ref(), effects).await; + assert!( + machine + .entry(&format!("{FIXTURE_PROVIDER}:KEPT-1")) + .is_some_and(|entry| entry.installed) + ); + + runtime.fail("the fixture collection is unreadable"); + let effects = machine.handle(Input::ScanRequested); + drive(&mut machine, &runtime, store.as_ref(), effects).await; + + let entry = machine + .entry(&format!("{FIXTURE_PROVIDER}:KEPT-1")) + .expect("a failed scan never deletes a record"); + assert!(entry.installed, "the previous installed state stays"); + assert_eq!( + machine + .scan_state(FIXTURE_PROVIDER) + .and_then(|state| state.last_error.as_deref()), + Some("the fixture collection is unreadable") + ); + let (success, error) = row(&paths, FIXTURE_PROVIDER).expect("provider_scans has a row"); + assert_eq!(success, Some(100), "the earlier success is retained"); + assert_eq!( + error.as_deref(), + Some("the fixture collection is unreadable") + ); +} + +/// Untrusted, incompatible, extension-only, discovery-less, reserved and malformed packages are +/// skipped with a diagnostic; the official providers remain composed. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn ineligible_third_party_packages_are_skipped_and_official_providers_remain() { + let (_dir, paths) = paths(); + let fixture = Fixture::new(); + + // Untrusted: signed and installed, but no key was pinned. + let untrusted = fixture.provider("Untrusted Candidate", Some("untrusted-candidate"), true); + install_signed(&fixture, &paths, FIXTURE_PLUGIN, &untrusted); + + // Incompatible: the only target is a Windows executable on Linux. + const INCOMPATIBLE: &str = "dev.example.incompatible-provider"; + let incompatible = fixture.provider_as( + INCOMPATIBLE, + "Incompatible Candidate", + "incompatible-candidate", + true, + "windows", + ); + install_signed(&fixture, &paths, INCOMPATIBLE, &incompatible); + trust(&fixture, &paths, INCOMPATIBLE); + + // The remaining packages are unsigned registry entries, so each gets its own plugin id. + const EXTENSION: &str = "dev.example.extension-only"; + let extension = fixture.extension(EXTENSION, "Extension Candidate"); + install_unverified(&paths, EXTENSION, &extension.staged); + const NO_DISCOVERY: &str = "dev.example.no-discovery"; + let no_discovery = fixture.provider_as( + NO_DISCOVERY, + "No Discovery Candidate", + "no-discovery-candidate", + false, + "linux", + ); + install_unverified(&paths, NO_DISCOVERY, &no_discovery.staged); + const RESERVED: &str = "dev.example.reserved"; + let reserved = fixture.provider_as(RESERVED, "Reserved Candidate", "steam", true, "linux"); + install_unverified(&paths, RESERVED, &reserved.staged); + + // A malformed manifest as found by a corrupt registry. It is not even valid JSON. + let malformed = fixture.dir.path().join("malformed-source"); + std::fs::create_dir_all(&malformed).unwrap(); + std::fs::write(malformed.join("plugin.json"), b"{ not a manifest").unwrap(); + install_unverified(&paths, "dev.example.malformed", &malformed); + + let composed = load_library_providers(Platform::Linux, &paths).await; + for unexpected in [ + "untrusted-candidate", + "incompatible-candidate", + "no-discovery-candidate", + ] { + assert!( + composed.get(unexpected).is_none(), + "`{unexpected}` was not added" + ); + } + assert!(!composed.diagnostics.is_empty()); + let diagnostics = composed.diagnostics.join("\n"); + for expected in [ + "untrusted publisher", + "incompatible", + "does not declare `library.discovery`", + "is not a provider", + ] { + assert!( + diagnostics.contains(expected), + "missing `{expected}` in:\n{diagnostics}" + ); + } + // The reserved provider id is rejected by the signed-manifest validation itself, so the + // diagnostic names that rule rather than a duplicate registration. + assert!(diagnostics.contains("reserved"), "{diagnostics}"); + + // Official providers and their order are untouched by every rejected package, and none of + // the rejected packages appended anything (including the reserved `steam` provider id). + let official = official_providers(Platform::Linux); + assert_eq!( + composed + .providers + .iter() + .map(|provider| provider.id().to_owned()) + .collect::>(), + official + .iter() + .map(|provider| provider.id().to_owned()) + .collect::>() + ); + assert!(composed.get("steam").is_some()); + assert_eq!(composed.providers.len(), official.len()); +} + +/// Opens the update service with an active profile and the lifecycle the import path requires. +/// The lifecycle has no host composition, so runtime registration is reported as unavailable; +/// installation and reviewed grants still complete. +fn import_service(paths: &DataPaths) -> PluginUpdateService { + let state = crate::plugin_host::profile::PluginStateLayout::managed(paths); + let api = crate::plugin_host::PluginApi::default(); + api.set_state_layout(state.clone()); + api.providers + .profiles() + .update(Some("fixture-account"), true); + let registry = PluginPackageRegistry::open(paths).unwrap(); + let lifecycle = + std::sync::Arc::new(crate::plugin_host::runtime::ThirdPartyPluginLifecycle::new( + api.providers.clone(), + crate::plugin_host::process::ProviderProcesses::new_for_lifecycle( + api.providers.clone(), + paths.data_dir().join("plugins.sock"), + vec![], + state.clone(), + ) + .unwrap(), + state.clone(), + registry.clone(), + crate::plugin_host::managed_packages::ManagedPackageLifecycle::new(registry), + )); + let service = PluginUpdateService::open(paths).unwrap(); + service.set_lifecycle(lifecycle); + service.set_profiles(api.providers.profiles()); + service +} + +/// Drives the real reviewed standalone import; only the trust confirmation and installation are +/// used, and the runtime composition is intentionally absent. +async fn reviewed_import( + service: &PluginUpdateService, + fixture: &Fixture, + package: &Package, +) -> PluginImportInstallOutcome { + let review = service + .import_review(package.archive.clone()) + .await + .unwrap(); + assert_eq!(review.package.plugin_id, FIXTURE_PLUGIN); + service + .import_confirm_publisher(&review.token, &fixture.fingerprint()) + .await + .unwrap(); + service + .import_install(&review.token, false, &[]) + .await + .unwrap() +} + +/// The real signed Dolphin bundle end to end: the reviewed import registers the provider in the +/// already composed host, and the desktop's own library composition then lists and scans it. +/// Gated by `DOLPHIN_BUNDLE_PATH` because it needs the sibling repository's signed artifact. +#[cfg(target_os = "linux")] +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn the_real_dolphin_bundle_joins_the_running_library_and_discovers_gzle01() { + use std::os::unix::fs::PermissionsExt; + + const DOLPHIN_PLUGIN: &str = "dev.richmont.gamenode.dolphin-emu"; + const DOLPHIN_PROVIDER: &str = "dolphin-emu"; + const DOLPHIN_PUBLISHER_PUBLIC_KEY: &str = "9MJsveQ7SI656O7ykweL/Y+WN1pye9EJ9W+yaQZmidw="; + + let Some(artifact) = crate::plugin_host::bundles::dolphin_bundle_artifact() else { + return; + }; + let directory = tempfile::tempdir().unwrap(); + std::fs::set_permissions(directory.path(), std::fs::Permissions::from_mode(0o700)).unwrap(); + let paths = DataPaths::at(directory.path().join("app-data")); + paths.ensure_data_dir().unwrap(); + crate::plugin_host::profile::PluginStateLayout::prepare_managed(&paths).unwrap(); + + let api = crate::plugin_host::PluginApi::default(); + api.set_state_layout(crate::plugin_host::profile::PluginStateLayout::managed( + &paths, + )); + api.providers + .profiles() + .update(Some("dolphin-library-account"), true); + let settings = SqliteSettingsStore::open(&paths.database_file()).unwrap(); + let registry = PluginPackageRegistry::open(&paths).unwrap(); + let endpoint = paths.data_dir().join("plugins.sock"); + let store = library_store(&paths); + let service = PluginUpdateService::open(&paths).unwrap(); + let host = crate::plugin_host::runtime::HostedProviders::bundled( + api.providers.clone(), + std::sync::Arc::new(Default::default()), + Some(endpoint.clone()), + paths.clone(), + store.clone(), + None, + ) + .await + .unwrap(); + let _server = crate::plugin_host::PluginApiServer::start( + &tokio::runtime::Handle::current(), + &endpoint, + api.clone(), + ) + .unwrap(); + service.set_lifecycle(host.lifecycle()); + service.set_profiles(api.providers.profiles()); + service.set_bundle_store(settings.bundle_store()); + + // Reviewed import into the already composed host: no restart and no second HostedProviders. + let review = service + .bundle_import_review(artifact.clone()) + .await + .unwrap(); + service + .bundle_import_confirm_publisher(&review.token, &review.bundle.publisher_fingerprint) + .await + .unwrap(); + let installed = service + .bundle_import_install(&review.token, false, &[]) + .await + .unwrap(); + assert_eq!( + installed.bundle_id, + "dev.richmont.gamenode.dolphin-emu.bundle" + ); + assert!( + installed + .components + .iter() + .any(|component| component.kind == "provider" && component.active) + ); + assert_eq!( + registry + .active(DOLPHIN_PLUGIN) + .unwrap() + .map(|installed| installed.version), + Some("0.1.0".to_owned()) + ); + // The same host the desktop composed now has the provider; nothing is rebuilt for the import. + assert!(host.has_provider(DOLPHIN_PROVIDER)); + + // Grant the reviewed permissions and enable the provider in the active profile. + let snapshot = host + .lifecycle() + .permission_snapshot(DOLPHIN_PLUGIN.into()) + .await + .unwrap(); + let decisions = snapshot + .requested_permissions + .iter() + .flat_map(|request| { + request.allowed_scopes.iter().map(|scope| { + crate::plugin_host::grants::PermissionDecision { + permission_id: request.permission_id.clone(), + scope: scope.clone(), + granted: true, + } + }) + }) + .collect::>(); + let activation = tokio::sync::Mutex::new(()); + host.lifecycle() + .replace_permissions( + &activation, + DOLPHIN_PLUGIN.into(), + snapshot.profile_id.clone(), + snapshot.publisher_fingerprint.clone(), + snapshot.grant_revision, + decisions, + ) + .await + .unwrap(); + host.lifecycle() + .enable(DOLPHIN_PLUGIN.into()) + .await + .unwrap(); + + // The provider scanner reads a plain GameCube disc header from the temporary collection. + let rom_root = directory.path().join("collection"); + std::fs::create_dir_all(&rom_root).unwrap(); + std::fs::write( + rom_root.join("The Legend of Zelda.iso"), + b"GZLE01\x00\x00\x00\x00", + ) + .unwrap(); + let mut config = host.processes().config(DOLPHIN_PROVIDER).unwrap(); + config.environment.push(( + std::ffi::OsString::from("DOLPHIN_PLUGIN_ROOTS"), + rom_root.into_os_string(), + )); + host.processes() + .replace_config(DOLPHIN_PROVIDER, config) + .await + .unwrap(); + + // The desktop's startup/post-import composition now lists the provider. + let composed = load_library_providers(Platform::Linux, &paths).await; + let provider = composed + .get(DOLPHIN_PROVIDER) + .expect("the real bundle joins the library provider list"); + assert_eq!(provider.discovery_plugin(), Some(DOLPHIN_PLUGIN)); + assert_eq!(provider.source(), "community"); + + // A fresh machine built from that composition represents a startup with the bundle already + // installed; the scan runs through the same still-live host. + let (mut machine, effects) = start_machine(composed.providers); + drive(&mut machine, host.as_ref(), store.as_ref(), effects).await; + + let entry = machine + .entry(&format!("{DOLPHIN_PROVIDER}:GZLE01")) + .expect("the real provider discovered GZLE01"); + assert_eq!(entry.name.as_deref(), Some("The Legend of Zelda")); + assert!(entry.installed); + assert_eq!( + entry.fields.get("platform").map(String::as_str), + Some("gamecube") + ); + let (success, error) = row(&paths, DOLPHIN_PROVIDER).expect("provider_scans has a row"); + assert!(success.is_some()); + assert_eq!(error, None); + assert_eq!( + library_entry(&paths, &format!("{DOLPHIN_PROVIDER}:GZLE01")), + Some(( + DOLPHIN_PROVIDER.to_owned(), + "The Legend of Zelda".to_owned(), + true, + )) + ); + let view = machine.view().expect("the library view is available"); + assert!( + view.providers + .iter() + .any(|provider| provider.id == DOLPHIN_PROVIDER && provider.count == 1), + "{:?}", + view.providers + ); + + // The publisher key the bundle review showed is the pinned development key; no fixture or + // substitute provider supplies the record. + let publisher_key: [u8; 32] = base64::engine::general_purpose::STANDARD + .decode(DOLPHIN_PUBLISHER_PUBLIC_KEY) + .unwrap() + .try_into() + .unwrap(); + let pinned = publisher_trust::key_fingerprint(&publisher_key); + assert_eq!(review.bundle.publisher_fingerprint, pinned); +} diff --git a/crates/app/src/plugin_host/storage.rs b/crates/app/src/plugin_host/storage.rs new file mode 100644 index 000000000..f9b6f3347 --- /dev/null +++ b/crates/app/src/plugin_host/storage.rs @@ -0,0 +1,1376 @@ +//! Private key/value storage of third-party plugins, served through `ResourceHost.Storage*`. +//! +//! A plugin's storage is addressed only by the host-authenticated namespace +//! ([`ExternalNamespaceResolver::storage_owner`]): plugin id, pinned publisher fingerprint and +//! account profile. The request carries a key and nothing else that could name an owner, a path +//! or another namespace. Each namespace has two layers that share one key space: +//! +//! * **durable** (`PERSISTENT`) values live in the plugin's own SQLite file under the host's +//! `plugin-data` folder ([`gamenode_platform::plugin_storage`]); they need `storage.persist`; +//! * **session-only** values stay in the host's memory and are discarded when the plugin's last +//! open session ends or the profile changes; they need only `storage.write`. +//! +//! A key lives in exactly one layer: writing it with the other durability moves it, and a +//! denied durable write never falls back to a volatile one. Revisions come from one counter per +//! namespace, so a deleted and recreated key never repeats a revision. Every operation on a +//! namespace is serialized, and all the work runs on a blocking worker holding that +//! serialization, so cancelling an RPC cannot interleave or abandon a half-done write. + +use std::collections::{BTreeMap, BTreeSet, HashMap}; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex}; +use std::time::{SystemTime, UNIX_EPOCH}; + +use gamenode_platform::plugin_storage::{ + self as durable, DurableStore, FileApproval, IntentApproval, PluginStorageError, ProfileSaved, + PutResult, SaveProfileRow, +}; +use tonic::Status; + +use super::library::CommitGuard; +use super::namespace::ExternalNamespaceResolver; +use super::provider::ResourceCaller; + +pub use durable::{ + ENTRY_OVERHEAD_BYTES, MAX_KEY_BYTES, MAX_TTL_SECONDS, MAX_VALUE_BYTES, QUOTA_BYTES, +}; + +type Clock = Arc i64 + Send + Sync>; + +fn system_clock() -> Clock { + Arc::new(|| { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0, |elapsed| elapsed.as_secs() as i64) + }) +} + +/// How long a stored value lasts. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Durability { + /// Until the plugin's last open session ends. + SessionOnly, + /// Until deleted or expired, across restarts. + Persistent, +} + +/// A value as read back. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Found { + pub value: Vec, + pub revision: u64, + pub durability: Durability, + /// Unix seconds, `None` when the value never expires. + pub expires_at: Option, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PutOutcome { + Applied { + revision: u64, + expires_at: Option, + /// Logical bytes the written layer holds now. + usage: u64, + }, + Conflict { + current: u64, + }, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum DeleteOutcome { + Deleted { + revision: u64, + }, + /// There was nothing under the key. + Absent, + Conflict { + current: u64, + }, +} + +struct Entry { + value: Vec, + revision: u64, + expires_at: Option, +} + +#[derive(Default)] +struct Inner { + /// The highest revision handed out; seeded from the durable store when it is first opened. + counter: u64, + /// The open plugin sessions that used this namespace. + sessions: BTreeSet, + session: BTreeMap, + durable: Option, +} + +struct Slot { + epoch: u64, + inner: Arc>, +} + +/// The host's private plugin storage: where durable data lives and which namespaces are loaded. +pub struct PluginStorage { + /// `plugin-data`; `None` when the host has no data folder, which refuses durable writes. + root: Option, + clock: Clock, + namespaces: Mutex>, +} + +impl Default for PluginStorage { + fn default() -> Self { + Self { + root: None, + clock: system_clock(), + namespaces: Mutex::default(), + } + } +} + +impl PluginStorage { + /// Synchronous access for an already-running blocking backup worker. Never call on an async + /// runtime/UI thread. Only short approval/revision checks run while the namespace is locked. + pub(crate) fn on_backup_worker( + &self, + caller: &ResourceCaller, + work: impl FnOnce(&mut Namespace<'_>) -> Result, + ) -> Result { + let resolver = caller + .namespace + .as_ref() + .ok_or_else(|| Status::failed_precondition("account namespace required"))?; + let identity = resolver.identity(); + let dir = self.root.as_ref().map(|root| { + durable::namespace_dir( + root, + &identity.publisher_fingerprint, + &identity.plugin_id, + &identity.profile_id, + ) + }); + let inner = self.slot(*resolver.storage_owner().key(), caller.profile_epoch)?; + let mut guard = inner + .try_lock() + .map_err(|_| Status::unavailable("backup scope is being updated"))?; + work(&mut Namespace { + inner: &mut guard, + dir: dir.as_deref(), + now: (self.clock)(), + }) + } + + /// Durable data goes below `root` (the `plugin-data` folder). + pub fn new(root: impl Into) -> Self { + Self { + root: Some(root.into()), + ..Self::default() + } + } + + /// The `plugin-data` root, if this host has one. Host administration measures the physical + /// files below it; a plugin reply never carries a path. + pub(crate) fn root(&self) -> Option<&Path> { + self.root.as_deref() + } + + /// Replaces the clock (Unix seconds), for tests of expiry. + #[cfg(test)] + pub(crate) fn with_clock(mut self, clock: impl Fn() -> i64 + Send + Sync + 'static) -> Self { + self.clock = Arc::new(clock); + self + } + + fn slot(&self, owner: [u8; 32], epoch: u64) -> Result>, Status> { + let mut namespaces = self.namespaces.lock().unwrap_or_else(|p| p.into_inner()); + // A new profile epoch drops every namespace of the previous one, session data included. + namespaces.retain(|_, slot| slot.epoch >= epoch); + let slot = namespaces.entry(owner).or_insert_with(|| Slot { + epoch, + inner: Arc::default(), + }); + if slot.epoch != epoch { + return Err(Status::failed_precondition("resource context is stale")); + } + Ok(slot.inner.clone()) + } + + /// Runs `work` on a blocking worker with exclusive use of a plugin's namespace on behalf of + /// the host itself (the settings list of remembered confirmations), not of a plugin session: + /// it does not count as a session using the namespace. + pub(crate) async fn run_for_host( + &self, + resolver: &ExternalNamespaceResolver, + profile_epoch: u64, + work: impl FnOnce(&mut Namespace<'_>) -> Result + Send + 'static, + ) -> Result { + let owner = resolver.storage_owner(); + let identity = resolver.identity(); + let dir = self.root.as_ref().map(|root| { + durable::namespace_dir( + root, + &identity.publisher_fingerprint, + &identity.plugin_id, + &identity.profile_id, + ) + }); + let inner = self.slot(*owner.key(), profile_epoch)?; + let mut guard = inner.lock_owned().await; + let clock = self.clock.clone(); + tokio::task::spawn_blocking(move || { + let mut namespace = Namespace { + inner: &mut guard, + dir: dir.as_deref(), + now: clock(), + }; + work(&mut namespace) + }) + .await + .map_err(|_| Status::unavailable("plugin storage is unavailable"))? + } + + /// Host-only user protection for one durable private key. A plugin RPC has no field that can + /// reach this decision, and it is never exposed through `ResourceHost`. + pub async fn set_persistence_protected( + &self, + resolver: &ExternalNamespaceResolver, + profile_epoch: u64, + key: impl Into, + protected: bool, + ) -> Result { + let key = key.into(); + if key.is_empty() || key.len() > MAX_KEY_BYTES || key.chars().any(char::is_control) { + return Err(Status::invalid_argument("persistence key is invalid")); + } + self.run_for_host(resolver, profile_epoch, move |namespace| { + namespace.set_persistence_protected(&key, protected) + }) + .await + } + + /// Host-only cleanup of one plugin's durable private store: expired and policy-exceeding + /// records are removed, while user-protected records remain. Never called from plugin IPC. + pub async fn cleanup_persistence( + &self, + resolver: &ExternalNamespaceResolver, + profile_epoch: u64, + ) -> Result { + self.run_for_host(resolver, profile_epoch, |namespace| { + namespace.cleanup_persistence().map(|(outcome, _)| outcome) + }) + .await + } + + /// The directory of one namespace below `plugin-data`, if this host has a data folder. + fn namespace_dir(&self, resolver: &ExternalNamespaceResolver) -> Option { + let identity = resolver.identity(); + self.root.as_ref().map(|root| { + durable::namespace_dir( + root, + &identity.publisher_fingerprint, + &identity.plugin_id, + &identity.profile_id, + ) + }) + } + + /// Drops a cached namespace slot after its owner's data was archived or removed, so a later + /// install cannot keep reading through an open connection. + fn forget_slot(&self, owner: [u8; 32], epoch: u64, slot: &Arc>) { + let mut namespaces = self.namespaces.lock().unwrap_or_else(|p| p.into_inner()); + if namespaces.get(&owner).is_some_and(|candidate| { + candidate.epoch == epoch && Arc::ptr_eq(&candidate.inner, slot) + }) { + namespaces.remove(&owner); + } + } + + /// Host-only: makes every live private entry of one plugin/profile namespace inert. The + /// namespace is evicted afterwards, so a reinstall opens the archived rows and needs the + /// separate reviewed reuse. + pub async fn archive_persistence( + &self, + resolver: &ExternalNamespaceResolver, + profile_epoch: u64, + ) -> Result { + let Some(dir) = self.namespace_dir(resolver) else { + return Ok(durable::PrivateArchiveOutcome::default()); + }; + let owner = *resolver.storage_owner().key(); + let slot = self.slot(owner, profile_epoch)?; + let mut guard = slot.clone().lock_owned().await; + let now = (self.clock)(); + let outcome = tokio::task::spawn_blocking(move || { + let mut namespace = Namespace { + inner: &mut guard, + dir: Some(&dir), + now, + }; + namespace.archive_persistence() + }) + .await + .map_err(|_| Status::unavailable("plugin storage is unavailable"))??; + self.forget_slot(owner, profile_epoch, &slot); + Ok(outcome) + } + + /// Host-only: restores one namespace's archived private entries after an explicit review. + /// The caller has already checked the confirmation and the active profile. + pub async fn reuse_archived_persistence( + &self, + resolver: &ExternalNamespaceResolver, + profile_epoch: u64, + ) -> Result { + self.run_for_host(resolver, profile_epoch, |namespace| { + namespace.reuse_archived_persistence() + }) + .await + } + + /// Host-only: reclaims one namespace's archived, unprotected entries in a reviewed cleanup. + pub async fn reclaim_archived_persistence( + &self, + resolver: &ExternalNamespaceResolver, + profile_epoch: u64, + ) -> Result { + self.run_for_host(resolver, profile_epoch, |namespace| { + namespace.reclaim_archived_persistence() + }) + .await + } + + /// Host-only preview of a reviewed publisher migration: what the old identity's private + /// namespace could hand to its re-trusted successor. `None` means this host has no private + /// data folder. Nothing is created or changed. + pub async fn publisher_migration_preview( + &self, + source: &ExternalNamespaceResolver, + target: &ExternalNamespaceResolver, + ) -> Result, Status> { + let Some(root) = self.root.clone() else { + return Ok(None); + }; + let source = source.identity().clone(); + let target = target.identity().clone(); + let now = (self.clock)(); + tokio::task::spawn_blocking(move || { + durable::migration_preview( + &root, + &source.publisher_fingerprint, + &source.plugin_id, + &source.profile_id, + &target.publisher_fingerprint, + &target.plugin_id, + &target.profile_id, + now, + ) + }) + .await + .map_err(|_| Status::unavailable("plugin storage is unavailable"))? + .map(Some) + .map_err(storage_status) + } + + /// Host-only copy of one old publisher identity's private entries to its re-trusted successor. + /// The source keeps every entry, conflicts and expired rows are reported instead of copied, and + /// the target's cached namespace is dropped so a live session reopens the migrated file. + pub async fn migrate_publisher_data( + &self, + source: &ExternalNamespaceResolver, + target: &ExternalNamespaceResolver, + ) -> Result { + let Some(root) = self.root.clone() else { + return Err(Status::failed_precondition( + "private plugin data is unavailable on this host", + )); + }; + let source = source.identity().clone(); + let target_identity = target.identity().clone(); + let target_owner = *target.storage_owner().key(); + let now = (self.clock)(); + let outcome = tokio::task::spawn_blocking(move || { + durable::migrate_namespace( + &root, + &source.publisher_fingerprint, + &source.plugin_id, + &source.profile_id, + &target_identity.publisher_fingerprint, + &target_identity.plugin_id, + &target_identity.profile_id, + now, + ) + }) + .await + .map_err(|_| Status::unavailable("plugin storage is unavailable"))? + .map_err(storage_status)?; + self.namespaces + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .remove(&target_owner); + Ok(outcome) + } + + /// Host-only rollback of one publisher migration's private copies. Only entries tagged with the + /// old fingerprint are removed; the old identity's namespace and later plugin writes stay. + pub async fn revert_publisher_migration( + &self, + target: &ExternalNamespaceResolver, + source_publisher_fingerprint: String, + ) -> Result, Status> { + let Some(root) = self.root.clone() else { + return Ok(None); + }; + let target_identity = target.identity().clone(); + let target_owner = *target.storage_owner().key(); + let outcome = tokio::task::spawn_blocking(move || { + durable::revert_migrated_namespace( + &root, + &target_identity.publisher_fingerprint, + &target_identity.plugin_id, + &target_identity.profile_id, + &source_publisher_fingerprint, + ) + }) + .await + .map_err(|_| Status::unavailable("plugin storage is unavailable"))? + .map_err(storage_status)?; + self.namespaces + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .remove(&target_owner); + Ok(outcome) + } + + /// Host-only: deletes one plugin/profile private namespace directory and reports the logical + /// bytes it held. Another profile, plugin, publisher, game file or backup archive is never + /// touched. The namespace slot is evicted and its cached connection closed first. + pub async fn remove_persistence_namespace( + &self, + resolver: &ExternalNamespaceResolver, + profile_epoch: u64, + ) -> Result { + let Some(dir) = self.namespace_dir(resolver) else { + return Ok(durable::PrivateArchiveOutcome::default()); + }; + let owner = *resolver.storage_owner().key(); + let slot = self.slot(owner, profile_epoch)?; + let mut guard = slot.clone().lock_owned().await; + let now = (self.clock)(); + let outcome = tokio::task::spawn_blocking( + move || -> Result { + let mut namespace = Namespace { + inner: &mut guard, + dir: Some(&dir), + now, + }; + let usage = namespace.store_usage()?; + // Closing the connection before the unlink keeps no stale handle to the deleted + // file. + namespace.inner.durable = None; + namespace.inner.session.clear(); + durable::remove_namespace_at(&dir).map_err(|error| { + tracing::warn!(%error, "private plugin namespace could not be removed"); + Status::unavailable("private plugin data could not be removed") + })?; + Ok(durable::PrivateArchiveOutcome { + records: usage + .categories + .iter() + .map(|category| category.records) + .sum::() + .saturating_add(usage.archived_records), + logical_bytes: usage + .logical_bytes + .saturating_add(usage.archived_logical_bytes), + }) + }, + ) + .await + .map_err(|_| Status::unavailable("plugin storage is unavailable"))??; + self.forget_slot(owner, profile_epoch, &slot); + Ok(outcome) + } + + /// Host-only: drops a cached namespace without touching its files. Used after a bundle + /// uninstall archived or deleted the namespace directly, so no open connection outlives it. + pub async fn forget_persistence_namespace( + &self, + resolver: &ExternalNamespaceResolver, + profile_epoch: u64, + ) -> Result<(), Status> { + let owner = *resolver.storage_owner().key(); + // A namespace that was never opened has nothing to drop. + let slot = { + let namespaces = self.namespaces.lock().unwrap_or_else(|p| p.into_inner()); + match namespaces.get(&owner) { + Some(slot) if slot.epoch == profile_epoch => slot.inner.clone(), + Some(_) => return Err(Status::failed_precondition("resource context is stale")), + None => return Ok(()), + } + }; + let mut guard = slot.clone().lock_owned().await; + let dir = self.namespace_dir(resolver); + tokio::task::spawn_blocking(move || { + let namespace = Namespace { + inner: &mut guard, + dir: dir.as_deref(), + now: 0, + }; + namespace.inner.durable = None; + namespace.inner.session.clear(); + }) + .await + .map_err(|_| Status::unavailable("plugin storage is unavailable"))?; + self.forget_slot(owner, profile_epoch, &slot); + Ok(()) + } + + /// Host-only usage of one plugin/profile private namespace. `None` when the namespace never + /// wrote anything durably. Never creates a store and never returns a value or a path. + pub async fn private_usage( + &self, + resolver: &ExternalNamespaceResolver, + profile_epoch: u64, + ) -> Result, Status> { + self.run_for_host(resolver, profile_epoch, |namespace| { + namespace.private_usage() + }) + .await + } + + /// Runs `work` on a blocking worker with exclusive use of the caller's namespace. + /// `session_open` says whether a plugin session id is still open. + pub(crate) async fn run( + &self, + caller: &ResourceCaller, + session_open: impl Fn(&str) -> bool + Send + 'static, + work: impl FnOnce(&mut Namespace<'_>) -> Result + Send + 'static, + ) -> Result { + let resolver: &ExternalNamespaceResolver = caller.namespace.as_ref().ok_or_else(|| { + Status::failed_precondition("official providers use trusted host adapters") + })?; + let owner = resolver.storage_owner(); + let identity = resolver.identity(); + let dir = self.root.as_ref().map(|root| { + durable::namespace_dir( + root, + &identity.publisher_fingerprint, + &identity.plugin_id, + &identity.profile_id, + ) + }); + let inner = self.slot(*owner.key(), caller.profile_epoch)?; + let mut guard = inner.lock_owned().await; + let clock = self.clock.clone(); + let session_id = caller.session_id.clone(); + tokio::task::spawn_blocking(move || { + guard.sessions.retain(|id| session_open(id)); + if guard.sessions.is_empty() { + guard.session.clear(); + } + guard.sessions.insert(session_id); + let mut namespace = Namespace { + inner: &mut guard, + dir: dir.as_deref(), + now: clock(), + }; + work(&mut namespace) + }) + .await + .map_err(|_| Status::unavailable("plugin storage is unavailable"))? + } +} + +fn unavailable(error: PluginStorageError) -> Status { + // The error text never contains a path; the plugin gets even less. + tracing::warn!(%error, "plugin storage failed"); + Status::unavailable("plugin storage is unavailable") +} + +/// A plugin mutation that names user-protected data fails explicitly; no other storage detail +/// leaves the host. +fn storage_status(error: PluginStorageError) -> Status { + match error { + PluginStorageError::Protected => { + Status::failed_precondition("the entry is protected by the user") + } + PluginStorageError::Archived => Status::failed_precondition( + "archived plugin data requires a reviewed reuse before it can be read or replaced", + ), + PluginStorageError::InvalidMigration => { + Status::failed_precondition("a publisher migration needs two different identities") + } + other => unavailable(other), + } +} + +fn session_bytes(entries: &BTreeMap) -> u64 { + entries + .iter() + .map(|(key, entry)| durable::charge(key, entry.value.len())) + .sum() +} + +fn exhausted(usage: u64) -> Status { + Status::resource_exhausted(format!( + "the plugin storage quota of {QUOTA_BYTES} bytes would be exceeded ({usage} in use); \ + nothing was changed" + )) +} + +/// One caller's namespace, exclusively held on a blocking worker. +pub(crate) struct Namespace<'a> { + inner: &'a mut Inner, + dir: Option<&'a Path>, + now: i64, +} + +impl Namespace<'_> { + /// Drops the session-only values that expired. + fn sweep(&mut self) { + let now = self.now; + self.inner + .session + .retain(|_, entry| entry.expires_at.is_none_or(|at| at > now)); + } + + /// The durable store: opened if it exists, or created when `create` is set. `None` when the + /// namespace never stored anything durably. + fn durable(&mut self, create: bool) -> Result, Status> { + if self.inner.durable.is_none() { + let Some(dir) = self.dir else { + return if create { + Err(Status::unavailable( + "durable plugin storage is not available", + )) + } else { + Ok(None) + }; + }; + let opened = if create { + Some(DurableStore::open(dir).map_err(unavailable)?) + } else { + DurableStore::open_existing(dir).map_err(unavailable)? + }; + if let Some(store) = &opened { + let high_water = store.high_water().map_err(unavailable)?; + self.inner.counter = self.inner.counter.max(high_water); + } + self.inner.durable = opened; + } + Ok(self.inner.durable.as_mut()) + } + + /// The value under `key`, in whichever layer holds it. + pub fn get(&mut self, key: &str) -> Result, Status> { + self.sweep(); + if let Some(entry) = self.inner.session.get(key) { + return Ok(Some(Found { + value: entry.value.clone(), + revision: entry.revision, + durability: Durability::SessionOnly, + expires_at: entry.expires_at, + })); + } + let now = self.now; + let Some(store) = self.durable(false)? else { + return Ok(None); + }; + Ok(store + .get(key, now) + .map_err(unavailable)? + .map(|stored| Found { + value: stored.value, + revision: stored.revision, + durability: Durability::Persistent, + expires_at: stored.expires_at, + })) + } + + /// The logical bytes held in one layer. + pub fn usage(&mut self, durability: Durability) -> Result { + match durability { + Durability::SessionOnly => { + self.sweep(); + Ok(session_bytes(&self.inner.session)) + } + Durability::Persistent => { + let now = self.now; + match self.durable(false)? { + Some(store) => store.usage(now).map_err(unavailable), + None => Ok(0), + } + } + } + } + + /// Durable logical entries exposed to Persistence administration. Values and paths never + /// leave the store; session-only values are deliberately excluded. + pub fn persistence_entries(&mut self) -> Result, Status> { + let now = self.now; + match self.durable(false)? { + Some(store) => store.persistence_entries(now).map_err(unavailable), + None => Ok(Vec::new()), + } + } + + /// Per-category logical accounting and the namespace-wide physical estimate. + pub fn store_usage(&mut self) -> Result { + let now = self.now; + match self.durable(false)? { + Some(store) => store.store_usage(now).map_err(unavailable), + None => Ok(durable::StoreUsage { + categories: vec![durable::CategoryUsage { + category: "private".to_owned(), + records: 0, + logical_bytes: 0, + protected_records: 0, + }], + logical_bytes: 0, + physical_bytes_estimate: 0, + archived_records: 0, + archived_logical_bytes: 0, + oldest_used_at: None, + retention: None, + }), + } + } + + /// Host-only protection decision for one durable private key. No plugin RPC reaches it. + pub fn set_persistence_protected( + &mut self, + key: &str, + protected: bool, + ) -> Result { + match self.durable(false)? { + Some(store) => store + .set_user_protected(key, protected) + .map_err(unavailable), + None => Ok(false), + } + } + + /// Host-only cleanup that keeps user-protected records and advances the namespace revision so + /// stale cursors cannot resume across the change. + pub fn cleanup_persistence(&mut self) -> Result<(durable::CleanupOutcome, u64), Status> { + if self.durable(false)?.is_none() { + return Ok((durable::CleanupOutcome::default(), self.inner.counter)); + } + let revision = self.inner.counter.saturating_add(1); + let now = self.now; + let store = self + .durable(false)? + .ok_or_else(|| Status::unavailable("plugin storage is unavailable"))?; + let outcome = store.cleanup(now).map_err(unavailable)?; + self.inner.counter = revision; + Ok((outcome, revision)) + } + + /// Host-only uninstall Keep for this namespace. Advances the revision so cursors are fenced. + pub fn archive_persistence(&mut self) -> Result { + if self.durable(false)?.is_none() { + return Ok(durable::PrivateArchiveOutcome::default()); + } + let revision = self.inner.counter.saturating_add(1); + let store = self + .durable(false)? + .ok_or_else(|| Status::unavailable("plugin storage is unavailable"))?; + let outcome = store.archive_entries(revision).map_err(unavailable)?; + self.inner.counter = revision; + Ok(outcome) + } + + /// Host-only reuse of this namespace's archived entries. Advances the revision. + pub fn reuse_archived_persistence(&mut self) -> Result { + if self.durable(false)?.is_none() { + return Ok(durable::PrivateArchiveOutcome::default()); + } + let revision = self.inner.counter.saturating_add(1); + let now = self.now; + let store = self + .durable(false)? + .ok_or_else(|| Status::unavailable("plugin storage is unavailable"))?; + let outcome = store + .reuse_archived_entries(now, revision) + .map_err(unavailable)?; + self.inner.counter = revision; + Ok(outcome) + } + + /// Host-only usage of this namespace, including archived rows. Never creates a store. + pub fn private_usage(&mut self) -> Result, Status> { + let now = self.now; + match self.durable(false)? { + Some(store) => store.store_usage(now).map(Some).map_err(unavailable), + None => Ok(None), + } + } + + /// Host-only reviewed reclaim of archived, unprotected entries. Advances the revision. + pub fn reclaim_archived_persistence( + &mut self, + ) -> Result { + if self.durable(false)?.is_none() { + return Ok(durable::PrivateArchiveOutcome::default()); + } + let revision = self.inner.counter.saturating_add(1); + let store = self + .durable(false)? + .ok_or_else(|| Status::unavailable("plugin storage is unavailable"))?; + let outcome = store.reclaim_archived(revision).map_err(unavailable)?; + self.inner.counter = revision; + Ok(outcome) + } + + /// Deletes an atomic set of durable keys and advances the namespace revision once. + pub fn delete_persistence_entries( + &mut self, + keys: &[String], + guard: &CommitGuard, + ) -> Result<(u64, u64), Status> { + let entries = self.persistence_entries()?; + let wanted: std::collections::HashSet<&str> = keys.iter().map(String::as_str).collect(); + if !wanted + .iter() + .all(|key| entries.iter().any(|entry| entry.key == **key)) + { + return Err(Status::not_found("persistence entry not found")); + } + if wanted.is_empty() { + return Ok((0, self.inner.counter)); + } + guard()?; + let revision = self.inner.counter.saturating_add(1); + let now = self.now; + let store = self + .durable(false)? + .ok_or_else(|| Status::not_found("persistence entry not found"))?; + let reclaimed = store + .delete_persistence_entries(keys, now, revision) + .map_err(storage_status)?; + self.inner.counter = revision; + Ok((reclaimed, revision)) + } + + pub fn set_retention_policy( + &mut self, + category: &str, + policy: durable::RetentionPolicy, + guard: &CommitGuard, + ) -> Result<(u64, u64), Status> { + guard()?; + let revision = self.inner.counter.saturating_add(1); + let now = self.now; + let store = self + .durable(true)? + .ok_or_else(|| Status::unavailable("plugin storage unavailable"))?; + let reclaimed = store + .set_retention_policy(category, policy, now, revision) + .map_err(unavailable)?; + self.inner.counter = revision; + Ok((reclaimed, revision)) + } + + /// Stores `value` under `key` when `expected` is the key's current revision (0 for a key + /// that does not exist). `guard` is checked right before the first change. Over the quota + /// is `RESOURCE_EXHAUSTED` and changes nothing. + pub fn put( + &mut self, + key: &str, + value: Vec, + durability: Durability, + ttl_seconds: u64, + expected: u64, + guard: &CommitGuard, + ) -> Result { + let current = self.get(key)?; + let current_revision = current.as_ref().map_or(0, |found| found.revision); + if current_revision != expected { + return Ok(PutOutcome::Conflict { + current: current_revision, + }); + } + let revision = self.inner.counter + 1; + let expires_at = (ttl_seconds != 0).then(|| self.now.saturating_add(ttl_seconds as i64)); + let now = self.now; + let usage = match durability { + Durability::Persistent => { + guard()?; + let store = self + .durable(true)? + .ok_or_else(|| Status::unavailable("plugin storage is unavailable"))?; + match store + .put(key, &value, revision, expires_at, now, QUOTA_BYTES) + .map_err(storage_status)? + { + PutResult::OverQuota { usage } => return Err(exhausted(usage)), + PutResult::Stored { usage } => { + // Now durable: the volatile copy, if any, is the one to go. + self.inner.session.remove(key); + usage + } + } + } + Durability::SessionOnly => { + let others = session_bytes(&self.inner.session) + - self + .inner + .session + .get(key) + .map_or(0, |entry| durable::charge(key, entry.value.len())); + let usage = others + durable::charge(key, value.len()); + if usage > QUOTA_BYTES { + return Err(exhausted(others)); + } + guard()?; + if current + .as_ref() + .is_some_and(|found| found.durability == Durability::Persistent) + && let Some(store) = self.durable(false)? + { + store.remove(key).map_err(storage_status)?; + } + self.inner.session.insert( + key.to_owned(), + Entry { + value, + revision, + expires_at, + }, + ); + usage + } + }; + self.inner.counter = revision; + Ok(PutOutcome::Applied { + revision, + expires_at, + usage, + }) + } + + /// Deletes `key` when `expected` is its current revision. A key that is not there is + /// `Absent`, whatever `expected` is: the desired state already holds. + pub fn delete( + &mut self, + key: &str, + expected: u64, + guard: &CommitGuard, + ) -> Result { + let Some(current) = self.get(key)? else { + return Ok(DeleteOutcome::Absent); + }; + if current.revision != expected { + return Ok(DeleteOutcome::Conflict { + current: current.revision, + }); + } + guard()?; + match current.durability { + Durability::SessionOnly => { + self.inner.session.remove(key); + } + Durability::Persistent => { + if let Some(store) = self.durable(false)? { + store.remove(key).map_err(storage_status)?; + } + } + } + Ok(DeleteOutcome::Deleted { + revision: current.revision, + }) + } +} + +/// How writing or removing a save profile ended. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum ProfileWrite { + /// Written or removed; `revision` is the revision it now has (or the removal's). + Applied { revision: u64 }, + /// The profile is not at the revision the caller expected. + Conflict { current: u64 }, + /// Another profile of the installation already has this name. + NameTaken, + /// There is no profile with this id. + NotFound, +} + +/// Save profiles live in the same per-namespace store, with revisions from the same counter. +impl Namespace<'_> { + /// Every profile of this plugin, ordered by installation and id. + pub fn save_profiles(&mut self) -> Result, Status> { + match self.durable(false)? { + Some(store) => store.save_profile_rows().map_err(unavailable), + None => Ok(Vec::new()), + } + } + + /// The profile with this id. + pub fn save_profile(&mut self, id: &str) -> Result, Status> { + match self.durable(false)? { + Some(store) => store.save_profile_row(id).map_err(unavailable), + None => Ok(None), + } + } + + /// The highest revision this namespace ever handed out. + pub fn revision(&mut self) -> Result { + self.durable(false)?; + Ok(self.inner.counter) + } + + /// Creates (`expected_revision` 0, `row.id` new) or replaces (`expected_revision` is the + /// profile's current revision) a profile, giving it the namespace's next revision. `guard` is + /// checked right before the change. + pub fn put_save_profile( + &mut self, + mut row: SaveProfileRow, + expected_revision: u64, + guard: &CommitGuard, + ) -> Result { + guard()?; + // Opening the store first seeds the counter from the highest revision it ever recorded. + self.durable(true)?; + let revision = self.inner.counter + 1; + let store = self + .durable(true)? + .ok_or_else(|| Status::unavailable("plugin storage is unavailable"))?; + match ( + store.save_profile_row(&row.id).map_err(unavailable)?, + expected_revision, + ) { + (None, 0) => {} + (None, _) => return Ok(ProfileWrite::NotFound), + (Some(existing), expected) if existing.revision != expected => { + return Ok(ProfileWrite::Conflict { + current: existing.revision, + }); + } + (Some(existing), _) => row.created_at = existing.created_at, + } + row.revision = revision; + match store.save_profile(&row).map_err(unavailable)? { + ProfileSaved::NameTaken => Ok(ProfileWrite::NameTaken), + ProfileSaved::Saved => { + self.inner.counter = revision; + Ok(ProfileWrite::Applied { revision }) + } + } + } + + /// Removes a profile if it is at `expected_revision`. The removal takes a revision of its + /// own, so a profile created afterwards never repeats one. + pub fn remove_save_profile( + &mut self, + id: &str, + expected_revision: u64, + guard: &CommitGuard, + ) -> Result { + guard()?; + self.durable(false)?; + let revision = self.inner.counter + 1; + let Some(store) = self.durable(false)? else { + return Ok(ProfileWrite::NotFound); + }; + let Some(existing) = store.save_profile_row(id).map_err(unavailable)? else { + return Ok(ProfileWrite::NotFound); + }; + if existing.revision != expected_revision { + return Ok(ProfileWrite::Conflict { + current: existing.revision, + }); + } + store + .delete_save_profile(id, revision) + .map_err(unavailable)?; + self.inner.counter = revision; + Ok(ProfileWrite::Applied { revision }) + } + + /// The persisted user decision for one shared-resource declaration, if any. + pub fn shared_resource_consent( + &mut self, + profile_id: &str, + resource_id: &str, + ) -> Result, Status> { + match self.durable(false)? { + Some(store) => store + .shared_resource_consent(profile_id, resource_id) + .map_err(unavailable), + None => Ok(None), + } + } + + /// Records the user's exact decision. The caller has already re-resolved the declaration and + /// its current affected set on this namespace worker. + pub fn put_shared_resource_consent( + &mut self, + row: &durable::SharedResourceConsentRow, + ) -> Result<(), Status> { + let store = self + .durable(true)? + .ok_or_else(|| Status::unavailable("plugin storage is unavailable"))?; + store.save_shared_resource_consent(row).map_err(unavailable) + } + + /// Forgets the decision so the next use requires a fresh review. + pub fn revoke_shared_resource_consent( + &mut self, + profile_id: &str, + resource_id: &str, + ) -> Result { + let Some(store) = self.durable(false)? else { + return Ok(false); + }; + store + .revoke_shared_resource_consent(profile_id, resource_id) + .map_err(unavailable) + } +} + +/// File-root approvals live beside the key/value data in the same per-namespace store. +impl Namespace<'_> { + /// The current time, Unix seconds, as this operation sees it. + pub fn now(&self) -> i64 { + self.now + } + + /// The approval of `installation_id` for `kind`, revoked or not. + pub fn approval_for( + &mut self, + installation_id: &str, + kind: &str, + ) -> Result, Status> { + match self.durable(false)? { + Some(store) => store + .approval_for(installation_id, kind) + .map_err(unavailable), + None => Ok(None), + } + } + + /// The approval with this id, revoked or not. + pub fn approval(&mut self, id: &str) -> Result, Status> { + match self.durable(false)? { + Some(store) => store.approval(id).map_err(unavailable), + None => Ok(None), + } + } + + /// Every persistent folder approval in this plugin/profile namespace, revoked or active. + pub fn file_approvals(&mut self) -> Result, Status> { + match self.durable(false)? { + Some(store) => store.approvals().map_err(unavailable), + None => Ok(Vec::new()), + } + } + + /// Records an approval, replacing the earlier one of the same installation and kind. + /// `guard` is checked right before the change. + pub fn save_approval( + &mut self, + approval: &FileApproval, + guard: &CommitGuard, + ) -> Result<(), Status> { + guard()?; + let store = self + .durable(true)? + .ok_or_else(|| Status::unavailable("plugin storage is unavailable"))?; + store.save_approval(approval).map_err(unavailable) + } + + /// The remembered confirmation of `installation_id` for `operation`, if any. + pub fn intent_approval( + &mut self, + installation_id: &str, + operation: &str, + ) -> Result, Status> { + match self.durable(false)? { + Some(store) => store + .intent_approval(installation_id, operation) + .map_err(unavailable), + None => Ok(None), + } + } + + /// Remembers a confirmation, replacing the earlier one for the same installation and + /// operation. `guard` is checked right before the change. + pub fn save_intent_approval( + &mut self, + approval: &IntentApproval, + guard: &CommitGuard, + ) -> Result<(), Status> { + guard()?; + let store = self + .durable(true)? + .ok_or_else(|| Status::unavailable("plugin storage is unavailable"))?; + store.save_intent_approval(approval).map_err(unavailable) + } + + /// Every remembered confirmation of this plugin. + pub fn intent_approvals(&mut self) -> Result, Status> { + match self.durable(false)? { + Some(store) => store.intent_approvals().map_err(unavailable), + None => Ok(Vec::new()), + } + } + + /// Forgets a remembered confirmation. Returns whether it existed. + pub fn revoke_intent_approval(&mut self, id: &str) -> Result { + match self.durable(false)? { + Some(store) => store.revoke_intent_approval(id).map_err(unavailable), + None => Ok(false), + } + } + + /// Revokes an approval; its handles stop working at once. Returns whether it was active. + pub fn revoke_approval(&mut self, id: &str) -> Result { + let now = self.now; + match self.durable(false)? { + Some(store) => store.revoke_approval(id, now).map_err(unavailable), + None => Ok(false), + } + } + + /// The runtime executable approval of `runtime_id`, revoked or active. + pub fn runtime_approval_for( + &mut self, + runtime_id: &str, + ) -> Result, Status> { + match self.durable(false)? { + Some(store) => store.runtime_approval_for(runtime_id).map_err(unavailable), + None => Ok(None), + } + } + + /// The runtime executable approval with this id, revoked or active. + pub fn runtime_approval_by_id( + &mut self, + id: &str, + ) -> Result, Status> { + match self.durable(false)? { + Some(store) => store.runtime_approval_by_id(id).map_err(unavailable), + None => Ok(None), + } + } + + /// Every runtime executable approval in this plugin/profile namespace, revoked or active. + pub fn runtime_approvals( + &mut self, + ) -> Result, Status> { + match self.durable(false)? { + Some(store) => store.runtime_approvals().map_err(unavailable), + None => Ok(Vec::new()), + } + } + + /// Records a runtime executable approval, replacing the earlier one of the same runtime. + /// `guard` is checked right before the change. + pub fn save_runtime_approval( + &mut self, + approval: &gamenode_platform::plugin_storage::RuntimeApproval, + guard: &CommitGuard, + ) -> Result<(), Status> { + guard()?; + let store = self + .durable(true)? + .ok_or_else(|| Status::unavailable("plugin storage is unavailable"))?; + store.save_runtime_approval(approval).map_err(unavailable) + } + + /// Revokes a runtime executable approval. Returns whether it was active. + pub fn revoke_runtime_approval(&mut self, runtime_id: &str) -> Result { + let now = self.now; + match self.durable(false)? { + Some(store) => store + .revoke_runtime_approval(runtime_id, now) + .map_err(unavailable), + None => Ok(false), + } + } +} + +#[cfg(all(test, unix))] +mod tests; + +impl Namespace<'_> { + pub fn plugin_libraries( + &mut self, + ) -> Result, Status> { + match self.durable(false)? { + Some(store) => store.plugin_libraries().map_err(unavailable), + None => Ok(Vec::new()), + } + } + + pub fn put_plugin_library( + &mut self, + mut row: gamenode_platform::plugin_storage::PluginLibraryRow, + expected: u64, + guard: &CommitGuard, + ) -> Result { + guard()?; + self.durable(true)?; + let rows = self.plugin_libraries()?; + let existing = rows.iter().find(|r| r.id == row.id); + if existing.is_none() + && rows.len() >= gamenode_platform::plugin_storage::MAX_PLUGIN_LIBRARIES + { + return Err(Status::resource_exhausted("library record limit reached")); + } + let root_count = rows + .iter() + .filter(|r| r.id != row.id) + .map(|r| r.roots.len()) + .sum::() + + row.roots.len(); + if root_count > gamenode_platform::plugin_storage::MAX_PLUGIN_LIBRARY_ROOTS { + return Err(Status::resource_exhausted("root limit reached")); + } + if existing.as_ref().map_or(0, |r| r.revision) != expected { + return Err(Status::aborted("library revision changed; get it again")); + } + let revision = self + .inner + .counter + .checked_add(1) + .ok_or_else(|| Status::resource_exhausted("revision limit reached"))?; + row.revision = revision; + guard()?; + self.durable(true)? + .ok_or_else(|| Status::unavailable("library storage unavailable"))? + .put_plugin_library(&row) + .map_err(unavailable)?; + self.inner.counter = revision; + Ok(revision) + } +} + +impl Namespace<'_> { + pub fn backup_sources(&mut self, profile: &str) -> Result, Status> { + match self.durable(false)? { + Some(store) => store.backup_sources(profile).map_err(unavailable), + None => Ok(vec![]), + } + } + pub fn remember_backup_source( + &mut self, + profile: &str, + destination: &str, + guard: &CommitGuard, + ) -> Result<(), Status> { + guard()?; + let store = self + .durable(true)? + .ok_or_else(|| Status::unavailable("backup storage unavailable"))?; + let sources = store.backup_sources(profile).map_err(unavailable)?; + if sources.len() >= 32 && !sources.iter().any(|source| source == destination) { + return Err(Status::resource_exhausted( + "backup destination limit reached", + )); + } + store + .remember_backup_source(profile, destination) + .map_err(unavailable) + } +} diff --git a/crates/app/src/plugin_host/storage/tests.rs b/crates/app/src/plugin_host/storage/tests.rs new file mode 100644 index 000000000..57978df26 --- /dev/null +++ b/crates/app/src/plugin_host/storage/tests.rs @@ -0,0 +1,847 @@ +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicI64, Ordering}; + +use super::*; +use crate::plugin_host::grants::PluginIdentity; +use crate::plugin_host::namespace::ExternalNamespaceResolver; + +const START: i64 = 1_000_000; + +fn caller( + plugin: &str, + publisher: &str, + profile: &str, + epoch: u64, + session: &str, +) -> ResourceCaller { + ResourceCaller { + declared_developer: "Fixture developer".into(), + origin: "fixture".into(), + package_digest: Vec::new(), + session_id: session.into(), + provider_id: "provider".into(), + package_version: "1.0.0".into(), + grants: Default::default(), + grant_revision: 1, + profile_epoch: epoch, + namespace: Some( + ExternalNamespaceResolver::new( + PluginIdentity { + plugin_id: plugin.into(), + publisher_fingerprint: publisher.into(), + profile_id: profile.into(), + }, + Some("provider".into()), + epoch, + ) + .unwrap(), + ), + } +} + +fn plugin() -> ResourceCaller { + caller( + "org.example.plugin", + "publisher-a", + "profile-1", + 1, + "session-1", + ) +} + +fn allow() -> CommitGuard { + Box::new(|| Ok(())) +} + +struct Host { + storage: PluginStorage, + clock: Arc, + _temp: tempfile::TempDir, + root: PathBuf, +} + +impl Host { + fn new() -> Self { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path().join("plugin-data"); + let clock = Arc::new(AtomicI64::new(START)); + Self { + storage: Self::storage_at(&root, &clock), + clock, + root, + _temp: temp, + } + } + + fn storage_at(root: &Path, clock: &Arc) -> PluginStorage { + let clock = clock.clone(); + PluginStorage::new(root).with_clock(move || clock.load(Ordering::SeqCst)) + } + + /// A new host process over the same data folder. + fn restart(&mut self) { + self.storage = Self::storage_at(&self.root, &self.clock); + } + + async fn put( + &self, + who: &ResourceCaller, + key: &str, + value: &[u8], + durability: Durability, + ttl: u64, + expected: u64, + ) -> Result { + let (key, value) = (key.to_owned(), value.to_vec()); + self.storage + .run( + who, + |_| true, + move |ns| ns.put(&key, value, durability, ttl, expected, &allow()), + ) + .await + } + + async fn get(&self, who: &ResourceCaller, key: &str) -> Result, Status> { + let key = key.to_owned(); + self.storage + .run(who, |_| true, move |ns| ns.get(&key)) + .await + } + + async fn delete( + &self, + who: &ResourceCaller, + key: &str, + expected: u64, + ) -> Result { + let key = key.to_owned(); + self.storage + .run(who, |_| true, move |ns| ns.delete(&key, expected, &allow())) + .await + } + + async fn usage(&self, who: &ResourceCaller, durability: Durability) -> u64 { + self.storage + .run(who, |_| true, move |ns| ns.usage(durability)) + .await + .unwrap() + } + + fn files(&self) -> Vec { + fn walk(dir: &Path, out: &mut Vec) { + let Ok(entries) = std::fs::read_dir(dir) else { + return; + }; + for entry in entries.flatten() { + let path = entry.path(); + if path.is_dir() { + walk(&path, out); + } else { + out.push(path); + } + } + } + let mut out = Vec::new(); + walk(&self.root, &mut out); + out + } +} + +fn applied(outcome: PutOutcome) -> u64 { + match outcome { + PutOutcome::Applied { revision, .. } => revision, + other => panic!("expected Applied, got {other:?}"), + } +} + +use Durability::{Persistent, SessionOnly}; + +#[tokio::test] +async fn values_keep_the_durability_they_were_written_with() { + let host = Host::new(); + let who = plugin(); + applied( + host.put(&who, "durable", b"d", Persistent, 0, 0) + .await + .unwrap(), + ); + applied( + host.put(&who, "volatile", b"v", SessionOnly, 0, 0) + .await + .unwrap(), + ); + + let durable = host.get(&who, "durable").await.unwrap().unwrap(); + assert_eq!( + (durable.value.as_slice(), durable.durability), + (&b"d"[..], Persistent) + ); + let volatile = host.get(&who, "volatile").await.unwrap().unwrap(); + assert_eq!( + (volatile.value.as_slice(), volatile.durability), + (&b"v"[..], SessionOnly) + ); + assert!(host.get(&who, "absent").await.unwrap().is_none()); + // Only the durable value touched the disk. + assert_eq!(host.files().len(), 1); +} + +#[tokio::test] +async fn a_key_lives_in_one_layer_and_moves_with_its_new_durability() { + let host = Host::new(); + let who = plugin(); + let first = applied(host.put(&who, "k", b"one", Persistent, 0, 0).await.unwrap()); + let moved = applied( + host.put(&who, "k", b"two", SessionOnly, 0, first) + .await + .unwrap(), + ); + assert!(moved > first); + let found = host.get(&who, "k").await.unwrap().unwrap(); + assert_eq!( + (found.value.as_slice(), found.durability), + (&b"two"[..], SessionOnly) + ); + assert_eq!( + host.usage(&who, Persistent).await, + 0, + "the durable copy is gone" + ); + + // And back: after a restart nothing of the volatile copy remains, durable one is current. + let back = applied( + host.put(&who, "k", b"three", Persistent, 0, moved) + .await + .unwrap(), + ); + assert_eq!( + host.usage(&who, SessionOnly).await, + 0, + "the volatile copy is gone" + ); + let mut host = host; + host.restart(); + let found = host.get(&who, "k").await.unwrap().unwrap(); + assert_eq!( + (found.value.as_slice(), found.revision), + (&b"three"[..], back) + ); +} + +#[tokio::test] +async fn a_keys_revisions_never_repeat_across_deletes_layers_and_restarts() { + let mut host = Host::new(); + let who = plugin(); + let mut seen = vec![applied( + host.put(&who, "k", b"1", Persistent, 0, 0).await.unwrap(), + )]; + let DeleteOutcome::Deleted { revision } = host.delete(&who, "k", seen[0]).await.unwrap() else { + panic!("not deleted"); + }; + assert_eq!(revision, seen[0]); + // Recreating the key never repeats a revision a stale writer could still hold. + seen.push(applied( + host.put(&who, "k", b"2", Persistent, 0, 0).await.unwrap(), + )); + // Moving it to the volatile layer and back keeps counting. + seen.push(applied( + host.put(&who, "k", b"3", SessionOnly, 0, seen[1]) + .await + .unwrap(), + )); + seen.push(applied( + host.put(&who, "k", b"4", Persistent, 0, seen[2]) + .await + .unwrap(), + )); + host.restart(); + seen.push(applied( + host.put(&who, "k", b"5", Persistent, 0, seen[3]) + .await + .unwrap(), + )); + assert!(seen.windows(2).all(|pair| pair[0] < pair[1]), "{seen:?}"); +} + +#[tokio::test] +async fn a_put_or_delete_needs_the_current_revision_and_a_conflict_changes_nothing() { + let host = Host::new(); + let who = plugin(); + // A key that does not exist is revision 0. + assert_eq!( + host.put(&who, "k", b"x", SessionOnly, 0, 7).await.unwrap(), + PutOutcome::Conflict { current: 0 } + ); + let revision = applied(host.put(&who, "k", b"one", Persistent, 0, 0).await.unwrap()); + // Creating again with 0 conflicts too. + assert_eq!( + host.put(&who, "k", b"two", Persistent, 0, 0).await.unwrap(), + PutOutcome::Conflict { current: revision } + ); + assert_eq!( + host.delete(&who, "k", revision + 1).await.unwrap(), + DeleteOutcome::Conflict { current: revision } + ); + let found = host.get(&who, "k").await.unwrap().unwrap(); + assert_eq!( + (found.value.as_slice(), found.revision), + (&b"one"[..], revision) + ); + // Deleting what is not there is already done, whatever revision is named. + assert_eq!( + host.delete(&who, "nothing", 9).await.unwrap(), + DeleteOutcome::Absent + ); +} + +#[tokio::test] +async fn exceeding_the_quota_is_resource_exhausted_and_keeps_every_stored_value() { + for durability in [SessionOnly, Persistent] { + let host = Host::new(); + let who = plugin(); + let big = vec![7u8; MAX_VALUE_BYTES]; + let mut stored = 0; + // Fill up with 1 MiB values until the next one would not fit. + while stored < 40 { + let key = format!("big-{stored}"); + match host.put(&who, &key, &big, durability, 0, 0).await { + Ok(outcome) => { + applied(outcome); + stored += 1; + } + Err(status) => { + assert_eq!( + status.code(), + tonic::Code::ResourceExhausted, + "{durability:?}" + ); + break; + } + } + } + assert!( + (14..=15).contains(&stored), + "{durability:?}: {stored} values of 1 MiB fit in {QUOTA_BYTES}" + ); + let usage = host.usage(&who, durability).await; + assert!(usage <= QUOTA_BYTES); + + // A replacement that would no longer fit fails whole: the old value stays. + let status = host + .put(&who, "big-0", &vec![1u8; MAX_VALUE_BYTES], durability, 0, 0) + .await + .map(|_| ()) + .err(); + // (expected revision 0 conflicts first; use the real one) + assert!(status.is_none()); + let current = host.get(&who, "big-0").await.unwrap().unwrap(); + // Growing in place past the quota: fill the remainder first, then try to grow. + let rest = QUOTA_BYTES - host.usage(&who, durability).await; + let filler = + vec![0u8; (rest as usize).saturating_sub(durable::charge("filler", 0) as usize)]; + applied( + host.put(&who, "filler", &filler, durability, 0, 0) + .await + .unwrap(), + ); + let before = host.usage(&who, durability).await; + let status = host + .put( + &who, + "filler", + &vec![0u8; filler.len() + 1], + durability, + 0, + host.get(&who, "filler").await.unwrap().unwrap().revision, + ) + .await + .unwrap_err(); + assert_eq!(status.code(), tonic::Code::ResourceExhausted); + assert_eq!(host.usage(&who, durability).await, before, "{durability:?}"); + assert_eq!( + host.get(&who, "filler").await.unwrap().unwrap().value.len(), + filler.len() + ); + assert_eq!( + host.get(&who, "big-0").await.unwrap().unwrap().revision, + current.revision + ); + } +} + +#[tokio::test] +async fn the_layers_have_independent_quotas() { + let host = Host::new(); + let who = plugin(); + let big = vec![1u8; MAX_VALUE_BYTES]; + for index in 0..14 { + applied( + host.put(&who, &format!("s{index}"), &big, SessionOnly, 0, 0) + .await + .unwrap(), + ); + } + // A full volatile layer does not take space from the durable one. + applied(host.put(&who, "d", &big, Persistent, 0, 0).await.unwrap()); +} + +#[tokio::test] +async fn values_expire_after_their_ttl_and_free_their_space() { + let host = Host::new(); + let who = plugin(); + let PutOutcome::Applied { expires_at, .. } = host + .put(&who, "short", b"x", Persistent, 60, 0) + .await + .unwrap() + else { + panic!() + }; + assert_eq!(expires_at, Some(START + 60)); + applied( + host.put(&who, "volatile", b"y", SessionOnly, 120, 0) + .await + .unwrap(), + ); + applied( + host.put(&who, "forever", b"z", Persistent, 0, 0) + .await + .unwrap(), + ); + + host.clock.store(START + 59, Ordering::SeqCst); + assert!(host.get(&who, "short").await.unwrap().is_some()); + host.clock.store(START + 60, Ordering::SeqCst); + assert!(host.get(&who, "short").await.unwrap().is_none()); + assert!(host.get(&who, "volatile").await.unwrap().is_some()); + host.clock.store(START + 120, Ordering::SeqCst); + assert!(host.get(&who, "volatile").await.unwrap().is_none()); + assert_eq!(host.usage(&who, SessionOnly).await, 0); + assert_eq!( + host.usage(&who, Persistent).await, + durable::charge("forever", 1) + ); + // An expired key is a key that does not exist: it is created with revision 0. + applied( + host.put(&who, "short", b"again", Persistent, 0, 0) + .await + .unwrap(), + ); +} + +#[tokio::test] +async fn session_only_values_end_with_the_last_open_session() { + let host = Host::new(); + let first = caller( + "org.example.plugin", + "publisher-a", + "profile-1", + 1, + "session-1", + ); + let second = caller( + "org.example.plugin", + "publisher-a", + "profile-1", + 1, + "session-2", + ); + let open = |ids: &'static [&'static str]| move |id: &str| ids.contains(&id); + async fn get_while_open( + host: &Host, + who: &ResourceCaller, + ids: &'static [&'static str], + ) -> Option { + host.storage + .run(who, move |id: &str| ids.contains(&id), |ns| ns.get("k")) + .await + .unwrap() + } + + host.storage + .run(&first, open(&["session-1"]), |ns| { + ns.put("k", b"v".to_vec(), SessionOnly, 0, 0, &allow()) + }) + .await + .unwrap(); + // Another open session of the same plugin shares the namespace. + assert!( + get_while_open(&host, &second, &["session-1", "session-2"]) + .await + .is_some() + ); + // The first one closes; the second is still using it. + assert!( + get_while_open(&host, &second, &["session-2"]) + .await + .is_some() + ); + // All sessions closed: a session that starts later finds an empty namespace. + let third = caller( + "org.example.plugin", + "publisher-a", + "profile-1", + 1, + "session-3", + ); + assert!( + get_while_open(&host, &third, &["session-3"]) + .await + .is_none() + ); +} + +#[tokio::test] +async fn namespaces_are_separated_by_plugin_publisher_and_profile() { + let host = Host::new(); + let base = plugin(); + let others = [ + caller("org.example.other", "publisher-a", "profile-1", 1, "s"), + caller("org.example.plugin", "publisher-b", "profile-1", 1, "s"), + caller("org.example.plugin", "publisher-a", "profile-2", 1, "s"), + ]; + applied( + host.put(&base, "k", b"secret", Persistent, 0, 0) + .await + .unwrap(), + ); + applied( + host.put(&base, "m", b"secret", SessionOnly, 0, 0) + .await + .unwrap(), + ); + for other in &others { + assert!(host.get(other, "k").await.unwrap().is_none()); + assert!(host.get(other, "m").await.unwrap().is_none()); + assert_eq!(host.usage(other, Persistent).await, 0); + assert_eq!( + host.delete(other, "k", 1).await.unwrap(), + DeleteOutcome::Absent + ); + // Their own writes and deletions never reach the first namespace. + applied( + host.put(other, "k", b"theirs", Persistent, 0, 0) + .await + .unwrap(), + ); + } + assert_eq!( + host.get(&base, "k").await.unwrap().unwrap().value, + b"secret" + ); + assert_eq!( + host.get(&base, "m").await.unwrap().unwrap().value, + b"secret" + ); + assert_eq!(host.files().len(), 4, "one private file per namespace"); +} + +#[tokio::test] +async fn a_new_profile_epoch_discards_session_values_and_rejects_stale_callers() { + let host = Host::new(); + let before = plugin(); + applied( + host.put(&before, "k", b"durable", Persistent, 0, 0) + .await + .unwrap(), + ); + applied( + host.put(&before, "v", b"volatile", SessionOnly, 0, 0) + .await + .unwrap(), + ); + + // The same account signs in again: a later epoch, the same persistent namespace. + let after = caller( + "org.example.plugin", + "publisher-a", + "profile-1", + 2, + "session-1", + ); + assert_eq!( + host.get(&after, "k").await.unwrap().unwrap().value, + b"durable" + ); + assert!(host.get(&after, "v").await.unwrap().is_none()); + // A caller of the earlier epoch can no longer reach the namespace. + let status = host.get(&before, "k").await.unwrap_err(); + assert_eq!(status.code(), tonic::Code::FailedPrecondition); +} + +#[tokio::test] +async fn callers_without_a_namespace_are_refused() { + let host = Host::new(); + let mut official = plugin(); + official.namespace = None; + let status = host.get(&official, "k").await.unwrap_err(); + assert_eq!(status.code(), tonic::Code::FailedPrecondition); + assert!(host.files().is_empty()); +} + +#[tokio::test] +async fn reading_never_creates_files_and_a_missing_data_folder_only_blocks_durable_writes() { + let host = Host::new(); + let who = plugin(); + assert!(host.get(&who, "k").await.unwrap().is_none()); + assert!(host.delete(&who, "k", 0).await.unwrap() == DeleteOutcome::Absent); + assert!(!host.root.exists(), "nothing was created by reading"); + + let storage = PluginStorage::default(); + let put = |key: &'static str, durability| { + storage.run( + &who, + |_| true, + move |ns| ns.put(key, b"v".to_vec(), durability, 0, 0, &allow()), + ) + }; + applied(put("volatile", SessionOnly).await.unwrap()); + assert_eq!( + put("durable", Persistent).await.unwrap_err().code(), + tonic::Code::Unavailable + ); +} + +#[tokio::test] +async fn a_failed_commit_check_changes_nothing() { + let host = Host::new(); + let who = plugin(); + let revision = applied(host.put(&who, "k", b"one", Persistent, 0, 0).await.unwrap()); + let denied = Arc::new(AtomicBool::new(true)); + let guard = || -> CommitGuard { + let denied = denied.clone(); + Box::new(move || { + if denied.load(Ordering::SeqCst) { + Err(Status::permission_denied("revoked")) + } else { + Ok(()) + } + }) + }; + for durability in [SessionOnly, Persistent] { + let status = host + .storage + .run(&who, |_| true, { + let guard = guard(); + move |ns| ns.put("k", b"two".to_vec(), durability, 0, revision, &guard) + }) + .await + .unwrap_err(); + assert_eq!(status.code(), tonic::Code::PermissionDenied); + } + let status = host + .storage + .run(&who, |_| true, { + let guard = guard(); + move |ns| ns.delete("k", revision, &guard) + }) + .await + .unwrap_err(); + assert_eq!(status.code(), tonic::Code::PermissionDenied); + let found = host.get(&who, "k").await.unwrap().unwrap(); + assert_eq!( + (found.value.as_slice(), found.revision, found.durability), + (&b"one"[..], revision, Persistent) + ); +} + +#[tokio::test] +async fn an_unusable_store_is_unavailable_without_leaking_where_it_is() { + let host = Host::new(); + let who = plugin(); + std::fs::create_dir_all(host.root.parent().unwrap()).unwrap(); + // A file where the plugin-data folder should be. + std::fs::write(&host.root, b"in the way").unwrap(); + let status = host + .put(&who, "k", b"v", Persistent, 0, 0) + .await + .unwrap_err(); + assert_eq!(status.code(), tonic::Code::Unavailable); + let message = status.message().to_owned(); + assert!(!message.contains("plugin-data"), "{message}"); + assert!(!message.contains(host.root.to_str().unwrap()), "{message}"); +} + +#[tokio::test] +async fn host_cleanup_keeps_protected_entries_and_reclaims_only_the_owner() { + let host = Host::new(); + let owner = plugin(); + let other = caller( + "org.example.other", + "publisher-a", + "profile-1", + 1, + "session-2", + ); + let resolver = |plugin: &str| { + ExternalNamespaceResolver::new( + PluginIdentity { + plugin_id: plugin.into(), + publisher_fingerprint: "publisher-a".into(), + profile_id: "profile-1".into(), + }, + Some("provider".into()), + 1, + ) + .unwrap() + }; + + applied( + host.put(&owner, "keep", b"protected", Persistent, 0, 0) + .await + .unwrap(), + ); + applied( + host.put(&owner, "expiring", b"old", Persistent, 10, 0) + .await + .unwrap(), + ); + applied( + host.put(&other, "other", b"still here", Persistent, 0, 0) + .await + .unwrap(), + ); + assert!( + host.storage + .set_persistence_protected(&resolver("org.example.plugin"), 1, "keep", true) + .await + .unwrap() + ); + + host.clock.store(START + 20, Ordering::SeqCst); + let cleaned = host + .storage + .cleanup_persistence(&resolver("org.example.plugin"), 1) + .await + .unwrap(); + assert_eq!(cleaned.removed_records, 1); + assert_eq!(cleaned.reclaimed_bytes, durable::charge("expiring", 3)); + assert!(host.get(&owner, "keep").await.unwrap().is_some()); + assert!(host.get(&owner, "expiring").await.unwrap().is_none()); + assert!( + host.get(&other, "other").await.unwrap().is_some(), + "another owner's store is untouched" + ); +} + +#[tokio::test] +async fn archived_private_entries_are_inert_until_a_reviewed_reuse() { + let host = Host::new(); + let owner = plugin(); + let resolver = |plugin: &str| { + ExternalNamespaceResolver::new( + PluginIdentity { + plugin_id: plugin.into(), + publisher_fingerprint: "publisher-a".into(), + profile_id: "profile-1".into(), + }, + Some("provider".into()), + 1, + ) + .unwrap() + }; + + applied( + host.put(&owner, "kept", b"old", Persistent, 0, 0) + .await + .unwrap(), + ); + let archived = host + .storage + .archive_persistence(&resolver("org.example.plugin"), 1) + .await + .unwrap(); + assert_eq!(archived.records, 1); + assert_eq!(archived.logical_bytes, durable::charge("kept", 3)); + + // Ordinary reads, lists and usage skip archived rows, and a reinstall cannot silently + // replace or infer them. + assert!(host.get(&owner, "kept").await.unwrap().is_none()); + let usage = host + .storage + .private_usage(&resolver("org.example.plugin"), 1) + .await + .unwrap() + .unwrap(); + assert_eq!(usage.logical_bytes, 0); + assert_eq!(usage.archived_records, 1); + let status = host + .put(&owner, "kept", b"new", Persistent, 0, 0) + .await + .unwrap_err(); + assert_eq!(status.code(), tonic::Code::FailedPrecondition); + assert!( + status.message().contains("reviewed reuse"), + "{}", + status.message() + ); + + // The host review is the only path that restores the value. + let restored = host + .storage + .reuse_archived_persistence(&resolver("org.example.plugin"), 1) + .await + .unwrap(); + assert_eq!(restored.records, 1); + let found = host.get(&owner, "kept").await.unwrap().unwrap(); + assert_eq!(found.value, b"old"); +} + +#[tokio::test] +async fn deleting_a_private_namespace_touches_one_profile_and_no_game_files() { + let host = Host::new(); + let owner = plugin(); + let second_profile = caller( + "org.example.plugin", + "publisher-a", + "profile-2", + 1, + "session-2", + ); + let resolver = |profile: &str| { + ExternalNamespaceResolver::new( + PluginIdentity { + plugin_id: "org.example.plugin".into(), + publisher_fingerprint: "publisher-a".into(), + profile_id: profile.into(), + }, + Some("provider".into()), + 1, + ) + .unwrap() + }; + + applied( + host.put(&owner, "kept", b"first", Persistent, 0, 0) + .await + .unwrap(), + ); + applied( + host.put(&second_profile, "kept", b"second", Persistent, 0, 0) + .await + .unwrap(), + ); + let save = host.root.parent().unwrap().join("saves/slot-1.sav"); + std::fs::create_dir_all(save.parent().unwrap()).unwrap(); + std::fs::write(&save, b"game save").unwrap(); + let backup = host.root.parent().unwrap().join("backups/slot-1.zip"); + std::fs::create_dir_all(backup.parent().unwrap()).unwrap(); + std::fs::write(&backup, b"backup archive").unwrap(); + + let removed = host + .storage + .remove_persistence_namespace(&resolver("profile-1"), 1) + .await + .unwrap(); + assert_eq!(removed.records, 1); + assert_eq!(removed.logical_bytes, durable::charge("kept", 5)); + assert!( + !durable::namespace_dir(&host.root, "publisher-a", "org.example.plugin", "profile-1") + .is_dir() + ); + assert_eq!(std::fs::read(&save).unwrap(), b"game save"); + assert_eq!(std::fs::read(&backup).unwrap(), b"backup archive"); + + let other = host.get(&second_profile, "kept").await.unwrap().unwrap(); + assert_eq!(other.value, b"second", "another profile is untouched"); +} diff --git a/crates/app/src/plugin_host/updates.rs b/crates/app/src/plugin_host/updates.rs new file mode 100644 index 000000000..352675e22 --- /dev/null +++ b/crates/app/src/plugin_host/updates.rs @@ -0,0 +1,6108 @@ +//! Feed-driven updates for managed third-party packages. +//! +//! A selected feed release is downloaded to inert bytes, checked against the signed feed and +//! package integrity metadata, extracted with the local-import allowlist, then sent through the +//! ordinary compatibility and registry installation path. Calling `apply_approved_release` +//! represents the user's explicit approval; this module never starts plugin code. + +use super::{ + grants::PluginIdentity, + managed_packages::{ManagedPackageLifecycle, PackageCandidateReport, PackageLifecycleError}, + package::{Manifest, PlaytimeCapabilities}, + profile::{PluginProfiles, PluginStateLayout}, +}; +use gamenode_platform::{ + plugin_bundle_db::{BundleRecord, SqlitePluginBundleStore}, + plugin_environment::EmulationPolicy, + plugin_network::FetchClient, + plugin_packages::stage_package_archive, + plugin_registry::{InstalledPluginVersion, PluginPackageRegistry}, + plugin_updates::{ + UpdateError, UpdateIndex, UpdateIndexVerifier, UpdateRelease, VerifiedUpdateIndex, + }, +}; +use semver::Version; +use sha2::Digest; +use std::{ + collections::{BTreeMap, BTreeSet, HashMap}, + fs, io, + path::{Path, PathBuf}, + time::{SystemTime, UNIX_EPOCH}, +}; +use thiserror::Error; +use tokio::sync::Mutex as AsyncMutex; + +#[derive(Debug, Error)] +pub enum ManagedUpdateError { + #[error(transparent)] + Feed(#[from] UpdateError), + #[error(transparent)] + Package(#[from] PackageLifecycleError), + #[error("plugin has no active version to update")] + NoActiveVersion, + #[error("update index does not match the installed plugin")] + PluginIdentityMismatch, + #[error("requested version is not present in the signed update index")] + ReleaseNotFound, + #[error("update feeds cannot silently downgrade or reinstall the active version")] + Downgrade, + #[error("downloaded ZIP is not a package for the indexed plugin version")] + PackageIdentityMismatch, + #[error("temporary update staging failed: {0}")] + Staging(String), + #[error("update worker failed")] + WorkerFailed, +} + +/// A static, user-reviewable comparison between the installed and candidate manifests. This is +/// produced from signed package metadata only; it does not load or start either plugin binary. +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct UpdateReview { + pub plugin_id: String, + pub installed_version: String, + pub candidate_version: String, + pub added_permissions: Vec, + pub removed_permissions: Vec, + pub changed_permissions: Vec, + pub permission_changes: Vec, + pub added_native_access: Vec, + pub removed_native_access: Vec, + pub api_changed: bool, + pub installed_api: String, + pub candidate_api: String, + pub license_changed: bool, + pub installed_license: String, + pub candidate_license: String, + pub installed_license_files: Vec, + pub candidate_license_files: Vec, + pub installed_license_notices: Vec, + pub candidate_license_notices: Vec, + pub installed_playtime: PlaytimeCapabilities, + pub candidate_playtime: PlaytimeCapabilities, + pub playtime_changed: bool, + pub publisher_changed: bool, + pub installed_publisher_key_id: String, + pub candidate_publisher_key_id: String, + pub publisher_fingerprint: String, + /// Namespaced private-data contracts whose declared version differs. The host does not + /// migrate or delete their stored values during package activation. + pub changed_data_schemas: Vec, + pub preserves_prior_data: bool, + pub is_downgrade: bool, + pub requires_manual_approval: bool, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub compatibility_details: Option, + /// The command bridge populates choices from the active account's library. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub extension_targets: Option>, +} + +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct PermissionChange { + pub id: String, + pub installed_scope: String, + pub candidate_scope: String, + pub installed_required: bool, + pub candidate_required: bool, +} + +impl UpdateReview { + pub fn compare(installed: &Manifest, candidate: &Manifest) -> Self { + let permission_map = |manifest: &Manifest| -> BTreeMap { + manifest + .permissions + .iter() + .map(|permission| { + ( + permission.id.clone(), + (permission.scope.clone(), permission.required), + ) + }) + .collect() + }; + let before = permission_map(installed); + let after = permission_map(candidate); + let before_ids: BTreeSet<_> = before.keys().cloned().collect(); + let after_ids: BTreeSet<_> = after.keys().cloned().collect(); + let added_permissions: Vec = after_ids.difference(&before_ids).cloned().collect(); + let removed_permissions: Vec = before_ids.difference(&after_ids).cloned().collect(); + let changed_permissions: Vec = before_ids + .intersection(&after_ids) + .filter(|id| before[*id] != after[*id]) + .cloned() + .collect(); + let permission_changes = changed_permissions + .iter() + .map(|id| { + let (installed_scope, installed_required) = &before[id]; + let (candidate_scope, candidate_required) = &after[id]; + PermissionChange { + id: id.clone(), + installed_scope: installed_scope.clone(), + candidate_scope: candidate_scope.clone(), + installed_required: *installed_required, + candidate_required: *candidate_required, + } + }) + .collect(); + let old_native: BTreeSet<_> = installed.native_access.iter().cloned().collect(); + let new_native: BTreeSet<_> = candidate.native_access.iter().cloned().collect(); + let added_native_access: Vec = + new_native.difference(&old_native).cloned().collect(); + let removed_native_access: Vec = + old_native.difference(&new_native).cloned().collect(); + let installed_api = format!("{} – {}", installed.api.min, installed.api.max); + let candidate_api = format!("{} – {}", candidate.api.min, candidate.api.max); + let playtime_changed = installed.playtime != candidate.playtime; + let installed_license = installed.license.expression.clone(); + let candidate_license = candidate.license.expression.clone(); + let api_changed = installed_api != candidate_api; + let license_changed = installed.license != candidate.license; + // Key ID labels are package metadata. Re-trust is tied only to the actual key bytes. + let publisher_changed = installed.publisher.public_key != candidate.publisher.public_key; + let schema_versions = |manifest: &Manifest| -> BTreeMap> { + let mut versions = BTreeMap::new(); + for schema in &manifest.schemas { + versions + .entry(schema.namespace.clone()) + .or_insert_with(BTreeSet::new) + .insert(schema.version.clone()); + } + versions + }; + let old_schemas = schema_versions(installed); + let new_schemas = schema_versions(candidate); + let changed_data_schemas: Vec = old_schemas + .keys() + .chain(new_schemas.keys()) + .collect::>() + .into_iter() + .filter(|namespace| old_schemas.get(*namespace) != new_schemas.get(*namespace)) + .cloned() + .collect(); + // Every version activation is a user decision. The diff is disclosure; it never mutates + // the separate permission grant store, even when all requested permissions are unchanged. + let requires_manual_approval = true; + Self { + plugin_id: candidate.id.clone(), + installed_version: installed.version.clone(), + candidate_version: candidate.version.clone(), + added_permissions, + removed_permissions, + changed_permissions, + permission_changes, + added_native_access, + removed_native_access, + api_changed, + installed_api, + candidate_api, + license_changed, + installed_license, + candidate_license, + installed_license_files: installed.license.files.clone(), + candidate_license_files: candidate.license.files.clone(), + installed_license_notices: installed.license.notices.clone(), + candidate_license_notices: candidate.license.notices.clone(), + installed_playtime: installed.playtime, + candidate_playtime: candidate.playtime, + playtime_changed, + publisher_changed, + installed_publisher_key_id: installed.publisher.key_id.clone(), + candidate_publisher_key_id: candidate.publisher.key_id.clone(), + publisher_fingerprint: String::new(), + // Package activation changes no storage namespace and performs no data migration or + // cleanup. Values remain available to a compatible version selected later. + preserves_prior_data: true, + is_downgrade: Version::parse(&candidate.version) + .ok() + .zip(Version::parse(&installed.version).ok()) + .is_some_and(|(candidate, installed)| candidate < installed), + changed_data_schemas, + requires_manual_approval, + compatibility_details: None, + extension_targets: (installed.kind == super::package::PluginKind::Extension + && candidate.kind == super::package::PluginKind::Extension) + .then(Vec::new), + } + } +} + +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct AvailablePluginUpdate { + pub plugin_id: String, + pub name: String, + pub installed_version: String, + pub versions: Vec, +} + +/// A signed bundle release offered by a component's update feed. The release version is the +/// bundle's distribution version; component versions remain independent. +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct AvailableBundleUpdate { + pub bundle_id: String, + pub name: String, + pub installed_version: String, + pub versions: Vec, +} + +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct AvailableBundleRollback { + pub bundle_id: String, + pub name: String, + pub active_version: String, + pub versions: Vec, +} + +/// One component's old/new facts in a bundle update or rollback review. Produced from signed +/// metadata only: the candidate package is staged and inspected, never executed. +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct BundleComponentUpdateReview { + pub plugin_id: String, + pub kind: String, + pub installed_version: String, + pub candidate_version: String, + pub added_permissions: Vec, + pub removed_permissions: Vec, + pub changed_permissions: Vec, + pub permission_changes: Vec, + pub added_native_access: Vec, + pub removed_native_access: Vec, + pub api_changed: bool, + pub installed_api: String, + pub candidate_api: String, + pub availability: super::bundles::BundleComponentAvailability, + pub compatibility: String, + pub compatibility_reason: Option, + pub compatibility_details: super::managed_packages::PackageCompatibilityReview, + pub publisher_changed: bool, + pub is_downgrade: bool, +} + +/// The grouped review of one signed bundle release: the bundle hash from the update index and each +/// component's old/new version, compatibility verdict and permission diff. +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct BundleUpdateReview { + pub bundle_id: String, + pub name: String, + pub installed_version: String, + pub candidate_version: String, + /// Lowercase SHA-256 of the exact signed `bundle.json` bytes the update index committed to. + pub bundle_sha256: String, + pub publisher_fingerprint: String, + pub components: Vec, + /// Distinct union over the components, for a one-line summary. + pub added_permissions: Vec, + pub removed_permissions: Vec, + pub changed_permissions: Vec, + pub requires_manual_approval: bool, + pub is_downgrade: bool, + pub is_rollback: bool, +} + +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct AvailablePluginRollback { + pub plugin_id: String, + pub name: String, + pub active_version: String, + pub versions: Vec, +} + +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct PluginUpdatePreferences { + pub periodic_checks: bool, +} + +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct PluginImportReview { + pub token: String, + /// The same review a bundle component carries, produced by the same builder. + #[serde(flatten)] + pub package: PackageImportReview, +} + +/// Everything an import review shows about one package. A standalone import adds the staging +/// token above; a bundle component embeds this unchanged beside its kind and availability. +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct PackageImportReview { + pub plugin_id: String, + pub provider_id: Option, + pub name: String, + pub version: String, + pub publisher_key_id: String, + pub publisher_fingerprint: String, + pub pinned_fingerprint: Option, + pub trust: String, + pub license: String, + pub license_files: Vec, + pub license_notices: Vec, + pub permission_ids: Vec, + pub requested_permissions: Vec, + pub native_access: Vec, + /// Signed content platforms, such as `gamecube` or `wii`. Empty for manifests that predate + /// the declaration. + pub supported_platforms: Vec, + /// Signed playtime behavior shown before the package is installed. + pub playtime: PlaytimeCapabilities, + pub compatibility: String, + pub compatibility_reason: Option, + pub compatibility_details: super::managed_packages::PackageCompatibilityReview, +} + +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct ImportPermissionReview { + pub id: String, + pub required: bool, + pub scope: String, + pub reason: String, + /// Signed disclosure of what the plugin loses when this optional permission is denied. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub impact_if_disabled: Option, +} + +/// One component inside a bundle import review. The embedded review is exactly what importing the +/// component alone would show, so no manifest, license or permission detail is parsed twice. +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct BundleComponentReview { + /// `provider` or `extension`, from the verified bundle manifest. + pub kind: String, + /// Platform/API compatibility verdict; an unavailable component stays in the review but is + /// not activated by the install. + pub availability: super::bundles::BundleComponentAvailability, + pub review: PackageImportReview, +} + +/// One component's license declarations, attributed to the plugin that ships them. +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct BundleComponentLicense { + pub plugin_id: String, + pub expression: String, + pub files: Vec, + pub notices: Vec, +} + +/// The bundle-wide license view: distinct expressions plus every component's declared files and +/// notices, so one header can show what the whole distribution ships. +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct BundleLicenseSummary { + /// Distinct license expressions in component order. + pub expressions: Vec, + pub components: Vec, +} + +/// The aggregated review of one bundle: one identity and publisher decision, with the ordinary +/// per-package review embedded for every component. +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct BundleImportReview { + pub token: String, + pub bundle: super::bundles::BundleIdentity, + /// `trusted`, `changed` or `untrusted` for the bundle publisher key. Every component shares + /// the verified key, so this is the single publisher decision the review asks for. + pub trust: String, + /// The previously pinned fingerprint when the bundle publisher changed. + pub pinned_fingerprint: Option, + pub license: BundleLicenseSummary, + pub components: Vec, +} + +/// One component's optional permissions the user disabled in a grouped import review. The host +/// validates the ids against that component's reviewed requests before installing anything. +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct BundleComponentDeniedPermissions { + pub plugin_id: String, + pub denied_permission_ids: Vec, +} + +/// One component's permission decisions submitted from a grouped review. The expected values are +/// the ones the review displayed; the host rechecks them before saving. +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct BundleComponentPermissionSubmission { + pub plugin_id: String, + pub expected_profile_id: String, + pub expected_publisher_fingerprint: String, + pub expected_revision: u64, + pub decisions: Vec, +} + +/// What happened to one component of a grouped permission submission. A rejection is reported per +/// component so a stale revision or a denied permission never hides its siblings' outcome. +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct BundleComponentPermissionOutcome { + pub plugin_id: String, + pub snapshot: Option, + pub error: Option, +} + +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct BundlePermissionResult { + pub components: Vec, +} + +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct PluginPlaytimeInfo { + pub plugin_id: String, + pub name: String, + pub version: String, + pub playtime: PlaytimeCapabilities, + pub accounting_enabled: bool, +} + +struct PendingCandidate { + work: Option, + version: String, + installed_version: String, + publisher_key: [u8; 32], + candidate_publisher_key: [u8; 32], + confirmed_retrust: bool, + is_rollback: bool, + installed_manifest: Manifest, + candidate_manifest: Manifest, + review: UpdateReview, +} + +struct PendingImport { + _work: UpdateWorkDir, + package_path: PathBuf, + publisher_key: [u8; 32], + review: PluginImportReview, + created_at: std::time::Instant, +} + +struct PendingBundleImport { + /// The verified bundle publisher key; the single pin this review confirms. + publisher_key: [u8; 32], + review: BundleImportReview, + /// The reviewed archive and the exact component inspection the review showed. Installation + /// re-verifies the archive and compares it with this report, so the approved bytes are the + /// installed bytes. + archive_path: PathBuf, + report: super::bundles::BundleCandidateReport, + created_at: std::time::Instant, +} + +/// The result of installing one reviewed bundle. Every component is listed with the version this +/// install published or adopted, and whether it was activated on this host. +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct BundleImportInstallOutcome { + pub bundle_id: String, + pub components: Vec, +} + +/// The result of one explicitly accepted standalone import. The package stays installed even when +/// activation fails; `activation_error` then explains why it is not running. +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct PluginImportInstallOutcome { + pub plugin_id: String, + pub activated: bool, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub activation_error: Option, +} + +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct BundleImportInstalledComponent { + pub plugin_id: String, + pub kind: String, + pub version: String, + pub active: bool, + /// Whether the host enabled this component for the active profile right after installing it. + pub activated: bool, + /// Present when a compatible component stayed installed but could not be activated. Every + /// sibling still reports its own outcome. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub activation_error: Option, + /// Present when this component was installed but its reviewed permission decisions could not + /// be saved. Every sibling still reports its own outcome. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub permission_error: Option, +} + +/// A reviewed bundle release ready to install. The work directory holds the exact downloaded +/// archive, which the update primitive re-verifies before any registry write. +struct PendingBundleUpdate { + /// Owns the private staging directory for as long as the reviewed archive is needed. + _work: UpdateWorkDir, + archive_path: PathBuf, + report: super::bundles::BundleCandidateReport, + installed: BundleRecord, + release_version: String, + publisher_key: [u8; 32], + review: BundleUpdateReview, + created_at: std::time::Instant, +} + +/// A reviewed rollback target. Approval re-reads the archived mapping and revalidates every +/// component, so this only records that the user saw the version. +struct PendingBundleRollback { + version: String, + created_at: std::time::Instant, +} + +fn read_inert_license(package_path: &Path, file: &str) -> Result { + const MAX_LICENSE_BYTES: u64 = 256 * 1024; + if Path::new(file) + .components() + .any(|component| !matches!(component, std::path::Component::Normal(_))) + { + return Err("license file path is not package-relative".into()); + } + let root = fs::canonicalize(package_path).map_err(|error| error.to_string())?; + let requested = package_path.join(file); + let metadata = fs::symlink_metadata(&requested).map_err(|error| error.to_string())?; + if !metadata.is_file() + || metadata.file_type().is_symlink() + || metadata.len() > MAX_LICENSE_BYTES + { + return Err("license file is not a bounded regular file".to_owned()); + } + let path = fs::canonicalize(&requested).map_err(|error| error.to_string())?; + if !path.starts_with(&root) { + return Err("license file escapes the validated package".into()); + } + let bytes = fs::read(path).map_err(|error| error.to_string())?; + if bytes.len() as u64 > MAX_LICENSE_BYTES { + return Err("license file exceeds the size limit".to_owned()); + } + String::from_utf8(bytes).map_err(|_| "license file is not valid UTF-8".to_owned()) +} + +/// Builds the review fields for one staged, validated package. Standalone imports and bundle +/// components both call this, so manifest, license, permission and compatibility parsing exists +/// once and a bundle can never present different facts than the component would alone. +fn package_import_review( + report: &PackageCandidateReport, + trust: &super::publisher_trust::PublisherTrustStore, + publisher_key: &[u8; 32], +) -> Result { + super::grants::manifest_permission_requests(&report.manifest.permissions) + .map_err(|error| format!("plugin declares unsupported permission scopes: {error}"))?; + let compatibility_details = report.compatibility_review(); + let (compatibility, compatibility_reason) = match report.selected_target() { + Ok(_) => ("compatible".to_owned(), None), + Err(error) => ( + if compatibility_details.state + == super::compatibility::CompatibilityState::Indeterminate + { + "unknown" + } else { + "incompatible" + } + .to_owned(), + Some(error.to_string()), + ), + }; + let manifest = &report.manifest; + let (trust, publisher_fingerprint, pinned_fingerprint) = match trust + .inspect(&manifest.id, publisher_key) + .map_err(|error| format!("publisher trust status is unavailable: {error}"))? + { + super::publisher_trust::KeyStatus::Trusted { fingerprint } => { + ("trusted".to_owned(), fingerprint, None) + } + super::publisher_trust::KeyStatus::Untrusted { + presented_fingerprint, + } => ("untrusted".to_owned(), presented_fingerprint, None), + super::publisher_trust::KeyStatus::Changed { + pinned_fingerprint, + presented_fingerprint, + } => ( + "changed".to_owned(), + presented_fingerprint, + Some(pinned_fingerprint), + ), + }; + Ok(PackageImportReview { + plugin_id: manifest.id.clone(), + provider_id: manifest.provider_id.clone(), + name: manifest.name.clone(), + version: manifest.version.clone(), + publisher_key_id: manifest.publisher.key_id.clone(), + publisher_fingerprint, + pinned_fingerprint, + trust, + license: manifest.license.expression.clone(), + license_files: manifest.license.files.clone(), + license_notices: manifest.license.notices.clone(), + permission_ids: manifest + .permissions + .iter() + .map(|item| item.id.clone()) + .collect(), + requested_permissions: manifest + .permissions + .iter() + .map(|item| ImportPermissionReview { + id: item.id.clone(), + required: item.required, + scope: item.scope.clone(), + reason: item.reason.clone(), + impact_if_disabled: item.impact_if_disabled.clone(), + }) + .collect(), + native_access: manifest.native_access.clone(), + supported_platforms: manifest.supported_platforms.clone(), + playtime: manifest.playtime, + compatibility, + compatibility_reason, + compatibility_details, + }) +} + +/// The single publisher decision a bundle review asks for. Every component shares the verified +/// bundle key, so the bundle is trusted only when each component's pin already accepts it. +fn bundle_trust_state<'a>( + components: impl IntoIterator, +) -> (String, Option) { + let mut pinned = None; + let mut all_trusted = true; + for component in components { + match component.trust.as_str() { + "trusted" => {} + "changed" => { + all_trusted = false; + if pinned.is_none() { + pinned = component.pinned_fingerprint.clone(); + } + } + _ => all_trusted = false, + } + } + if all_trusted { + ("trusted".to_owned(), None) + } else if pinned.is_some() { + ("changed".to_owned(), pinned) + } else { + ("untrusted".to_owned(), None) + } +} + +/// Build one component's old/new review from signed package metadata. Both manifests were parsed +/// from verified packages; nothing here executes package code. +fn bundle_component_update_review( + installed: &Manifest, + candidate: &Manifest, + candidate_report: &PackageCandidateReport, + installed_version: &str, + candidate_version: &str, +) -> BundleComponentUpdateReview { + let comparison = UpdateReview::compare(installed, candidate); + let details = candidate_report.compatibility_review(); + let (compatibility, compatibility_reason) = match candidate_report.selected_target() { + Ok(_) => ("compatible".to_owned(), None), + Err(error) => ( + if details.state == super::compatibility::CompatibilityState::Indeterminate { + "unknown" + } else { + "incompatible" + } + .to_owned(), + Some(error.to_string()), + ), + }; + BundleComponentUpdateReview { + plugin_id: candidate.id.clone(), + kind: match candidate.kind { + super::package::PluginKind::Provider => "provider".to_owned(), + super::package::PluginKind::Extension => "extension".to_owned(), + }, + installed_version: installed_version.to_owned(), + candidate_version: candidate_version.to_owned(), + added_permissions: comparison.added_permissions, + removed_permissions: comparison.removed_permissions, + changed_permissions: comparison.changed_permissions, + permission_changes: comparison.permission_changes, + added_native_access: comparison.added_native_access, + removed_native_access: comparison.removed_native_access, + api_changed: comparison.api_changed, + installed_api: comparison.installed_api, + candidate_api: comparison.candidate_api, + availability: super::bundles::availability(candidate_report), + compatibility, + compatibility_reason, + compatibility_details: details, + publisher_changed: comparison.publisher_changed, + is_downgrade: comparison.is_downgrade, + } +} + +fn union_permissions( + components: &[BundleComponentUpdateReview], + pick: impl Fn(&BundleComponentUpdateReview) -> &Vec, +) -> Vec { + let mut union = Vec::new(); + for component in components { + for permission in pick(component) { + if !union.contains(permission) { + union.push(permission.clone()); + } + } + } + union +} + +fn bundle_license_summary(components: &[BundleComponentReview]) -> BundleLicenseSummary { + let mut expressions: Vec = Vec::new(); + let mut licenses = Vec::with_capacity(components.len()); + for component in components { + let review = &component.review; + if !expressions.contains(&review.license) { + expressions.push(review.license.clone()); + } + licenses.push(BundleComponentLicense { + plugin_id: review.plugin_id.clone(), + expression: review.license.clone(), + files: review.license_files.clone(), + notices: review.license_notices.clone(), + }); + } + BundleLicenseSummary { + expressions, + components: licenses, + } +} + +/// Validates the optional permissions a user disabled in one package review. The ids must name +/// that package's reviewed requests; a required permission can never be denied, and a repeated id +/// is rejected rather than silently collapsed. Nothing is written here. +fn denied_permission_set( + requested: &[ImportPermissionReview], + denied: &[String], +) -> Result, String> { + let mut denied_set = BTreeSet::new(); + for id in denied { + let Some(permission) = requested.iter().find(|permission| &permission.id == id) else { + return Err(format!( + "permission `{id}` is not requested by this package and cannot be denied" + )); + }; + if permission.required { + return Err(format!( + "required permission `{id}` cannot be denied or disabled" + )); + } + if !denied_set.insert(id.clone()) { + return Err(format!("permission `{id}` is denied more than once")); + } + } + Ok(denied_set) +} + +/// One just-installed package's reviewed decisions, expressed in the host's typed grant scopes so +/// they can be submitted through the ordinary permission-review path. +struct ImportPermissionPlan { + profile_id: String, + publisher_fingerprint: String, + grant_revision: u64, + decisions: Vec, +} + +/// User-facing updater. Periodic checks only fetch and authenticate feed metadata. Package +/// contents remain inert through staging and review; activation is a separate user command. +#[derive(Clone)] +pub struct PluginUpdateService { + registry: PluginPackageRegistry, + packages: ManagedPackageLifecycle, + verifier: UpdateIndexVerifier, + client: std::sync::Arc, + trust_dir: PathBuf, + grant_layout: PluginStateLayout, + profiles: std::sync::Arc>>>, + preferences_path: PathBuf, + available_path: PathBuf, + preferences: std::sync::Arc>, + available: std::sync::Arc>>, + indexes: std::sync::Arc>>, + bundle_indexes: std::sync::Arc>>, + bundle_available: std::sync::Arc>>, + checks: std::sync::Arc>, + activations: std::sync::Arc>, + pending: std::sync::Arc>>, + pending_bundles: std::sync::Arc>>, + pending_rollbacks: std::sync::Arc>>, + imports: std::sync::Arc>>, + bundle_imports: std::sync::Arc>>, + /// The bundle mapping on the application database connection. It is set at startup; when it is + /// absent (tests of standalone packages), the inventory never groups components. + bundles: std::sync::Arc>>, + lifecycle: std::sync::Arc< + std::sync::RwLock>>, + >, +} + +impl PluginUpdateService { + pub fn open(paths: &gamenode_platform::paths::DataPaths) -> Result { + PluginStateLayout::refuse_legacy_layouts(paths).map_err(|error| error.to_string())?; + let registry = PluginPackageRegistry::open(paths).map_err(|error| error.to_string())?; + let verifier = + UpdateIndexVerifier::open(paths.plugin_packages_dir().join("update-sequences")) + .map_err(|error| error.to_string())?; + let client = FetchClient::new().map_err(|error| error.to_string())?; + let private_dir = paths.private_dir(); + let grant_layout = + PluginStateLayout::prepare_managed(paths).map_err(|error| error.to_string())?; + fs::create_dir_all(&private_dir).map_err(|error| error.to_string())?; + // Import and runtime share this store. The private directory only holds update metadata. + let trust_dir = grant_layout.trust_dir(); + let preferences_path = private_dir.join("plugin-update-preferences.json"); + let preferences = read_preferences(&preferences_path)?; + let available_path = private_dir.join("plugin-updates-cache.json"); + let available = read_available(&available_path)?; + Ok(Self { + packages: ManagedPackageLifecycle::new(registry.clone()), + registry, + verifier, + client: std::sync::Arc::new(client), + trust_dir, + grant_layout, + profiles: Default::default(), + preferences_path, + available_path, + preferences: std::sync::Arc::new(std::sync::Mutex::new(preferences)), + available: std::sync::Arc::new(std::sync::Mutex::new(available)), + indexes: Default::default(), + bundle_indexes: Default::default(), + bundle_available: Default::default(), + checks: Default::default(), + activations: Default::default(), + pending: Default::default(), + pending_bundles: Default::default(), + pending_rollbacks: Default::default(), + imports: Default::default(), + bundle_imports: Default::default(), + bundles: Default::default(), + lifecycle: Default::default(), + }) + } + + /// Shares the application's bundle mapping with the inventory. Startup calls this once the + /// settings store is open, so the inventory and uninstall observe the same connection. + pub fn set_bundle_store(&self, bundles: SqlitePluginBundleStore) { + *self + .bundles + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(bundles); + } + + fn bundle_store(&self) -> Option { + self.bundles + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .clone() + } + + pub fn set_lifecycle( + &self, + lifecycle: std::sync::Arc, + ) { + *self + .lifecycle + .write() + .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(lifecycle); + } + + /// The connected managed runtime, if the host composed one. + #[cfg(test)] + pub(crate) fn lifecycle( + &self, + ) -> Option> { + self.lifecycle + .read() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .clone() + } + + /// Re-reads one installed package through the same registry and publisher pin the startup + /// composition uses. A command that accepts an import calls this afterwards so the new + /// provider joins the running library and becomes scannable without a restart. + pub async fn library_provider( + &self, + plugin_id: &str, + ) -> Result, String> { + let platform = gamenode_core::provider::Platform::current() + .ok_or_else(|| "GameNode Desktop supports Windows and Linux only".to_owned())?; + super::startup::installed_provider_from_registry( + platform, + self.registry.clone(), + self.trust_dir.clone(), + plugin_id, + ) + .await + } + + /// Stages and validates a user-selected local archive without executing plugin code. + pub async fn import_review(&self, archive_path: PathBuf) -> Result { + const MAX_PENDING_IMPORTS: usize = 8; + const IMPORT_REVIEW_TTL: std::time::Duration = std::time::Duration::from_secs(15 * 60); + let mut imports = self.imports.lock().await; + imports.retain(|_, pending| pending.created_at.elapsed() < IMPORT_REVIEW_TTL); + if imports.len() >= MAX_PENDING_IMPORTS { + return Err("too many plugin packages are awaiting review".into()); + } + let work = tokio::task::spawn_blocking(UpdateWorkDir::create) + .await + .map_err(|_| "plugin import staging worker failed".to_owned())? + .map_err(|error| error.to_string())?; + let staged = work.path.join("package"); + let work_path = work.path.clone(); + let staged_for_worker = staged.clone(); + let (publisher_key, _manifest) = tokio::task::spawn_blocking(move || { + let metadata = + fs::symlink_metadata(&archive_path).map_err(|error| error.to_string())?; + if !metadata.is_file() || metadata.file_type().is_symlink() { + return Err("selected plugin package is not a regular file".to_owned()); + } + let key = package_archive_key(&archive_path) + .map_err(|error| format!("selected plugin archive: {error}"))?; + let archive_copy = work_path.join("selected.gnplugin"); + fs::copy(&archive_path, &archive_copy) + .map_err(|error| format!("could not stage selected plugin archive: {error}"))?; + stage_package_archive(&archive_copy, &staged_for_worker, &key) + .map_err(|error| format!("selected plugin archive failed validation: {error}"))?; + let manifest_path = staged_for_worker.join("plugin.json"); + let manifest_bytes = fs::read(manifest_path) + .map_err(|error| format!("validated plugin manifest is unavailable: {error}"))?; + let manifest = Manifest::parse_json(&manifest_bytes) + .map_err(|error| error.to_string())? + .manifest() + .clone(); + Ok::<_, String>((key, manifest)) + }) + .await + .map_err(|_| "plugin import validation worker failed".to_owned())??; + let report = self + .packages + .inspect_candidate(&staged, publisher_key, EmulationPolicy::RequireNative) + .await + .map_err(|error| format!("staged plugin package is invalid: {error}"))?; + let private_dir = self.trust_dir.clone(); + let key = publisher_key; + let package = tokio::task::spawn_blocking(move || { + let trust = super::publisher_trust::PublisherTrustStore::open(private_dir) + .map_err(|error| format!("publisher trust store is unavailable: {error}"))?; + package_import_review(&report, &trust, &key) + }) + .await + .map_err(|_| "plugin trust worker failed".to_owned())??; + let mut nonce = [0; 16]; + getrandom::fill(&mut nonce).map_err(|error| error.to_string())?; + let token = nonce + .iter() + .map(|byte| format!("{byte:02x}")) + .collect::(); + let review = PluginImportReview { + token: token.clone(), + package, + }; + imports.insert( + token, + PendingImport { + _work: work, + package_path: staged, + publisher_key, + review: review.clone(), + created_at: std::time::Instant::now(), + }, + ); + Ok(review) + } + + /// Pins or explicitly re-trusts the exact key fingerprint shown by the staged review. + pub async fn import_confirm_publisher( + &self, + token: &str, + confirmed_fingerprint: &str, + ) -> Result { + self.lifecycle + .read() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .clone() + .ok_or_else(|| "managed plugin runtime is unavailable".to_owned())? + .require_active_profile() + .map_err(|error| error.message().to_owned())?; + let mut imports = self.imports.lock().await; + let pending = imports + .get_mut(token) + .ok_or_else(|| "plugin import review expired".to_owned())?; + if pending.created_at.elapsed() >= std::time::Duration::from_secs(15 * 60) { + imports.remove(token); + return Err("plugin import review expired".into()); + } + if pending.review.package.publisher_fingerprint != confirmed_fingerprint { + return Err("publisher fingerprint confirmation does not match".into()); + } + let private_dir = self.trust_dir.clone(); + let plugin_id = pending.review.package.plugin_id.clone(); + let publisher_key = pending.publisher_key; + let fingerprint = confirmed_fingerprint.to_owned(); + let trust_status = pending.review.package.trust.clone(); + let pinned = tokio::task::spawn_blocking(move || { + let _publisher = super::managed_packages::lock_publisher_identity(); + let mut trust = super::publisher_trust::PublisherTrustStore::open(private_dir) + .map_err(|error| error.to_string())?; + match trust + .inspect(&plugin_id, &publisher_key) + .map_err(|error| error.to_string())? + { + super::publisher_trust::KeyStatus::Trusted { + fingerprint: current, + } if current == fingerprint => Ok(current), + super::publisher_trust::KeyStatus::Untrusted { .. } + if trust_status == "untrusted" => + { + trust + .confirm_first_key(&plugin_id, &publisher_key, &fingerprint) + .map_err(|error| error.to_string()) + } + super::publisher_trust::KeyStatus::Changed { .. } if trust_status == "changed" => { + trust + .retrust_key(&plugin_id, &publisher_key, &fingerprint) + .map_err(|error| error.to_string()) + } + _ => Err("publisher trust changed; review the package again".to_owned()), + } + }) + .await + .map_err(|_| "publisher trust worker failed".to_owned())??; + pending.review.package.trust = "trusted".into(); + pending.review.package.pinned_fingerprint = None; + pending.review.package.publisher_fingerprint = pinned; + Ok(pending.review.clone()) + } + + /// Reads a declared license or notice from the inert, validated import staging directory. + /// The frontend supplies only the exact manifest path; arbitrary filesystem paths are denied. + pub async fn import_license_text(&self, token: &str, file: &str) -> Result { + let imports = self.imports.lock().await; + let pending = imports + .get(token) + .ok_or_else(|| "plugin import review expired".to_owned())?; + if pending.created_at.elapsed() >= std::time::Duration::from_secs(15 * 60) { + return Err("plugin import review expired".into()); + } + if !pending + .review + .package + .license_files + .iter() + .any(|path| path == file) + && !pending + .review + .package + .license_notices + .iter() + .any(|path| path == file) + { + return Err("file is not a declared license or notice".into()); + } + let package_path = pending.package_path.clone(); + let file = file.to_owned(); + drop(imports); + tokio::task::spawn_blocking(move || read_inert_license(&package_path, &file)) + .await + .map_err(|_| "license viewer worker failed".to_owned())? + } + + /// Imports a reviewed, compatible package as the selected version and applies the review's + /// optional-permission decisions to the active profile. Every optional permission is granted + /// unless the user denied it and every required permission is granted. No process is registered + /// or executed by this operation. + pub async fn import_install( + &self, + token: &str, + native_code_consent: bool, + denied_permission_ids: &[String], + ) -> Result { + let lifecycle = self + .lifecycle + .read() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .clone() + .ok_or_else(|| "managed plugin runtime is unavailable".to_owned())?; + lifecycle + .require_active_profile() + .map_err(|error| error.message().to_owned())?; + let mut imports = self.imports.lock().await; + let pending = imports + .get(token) + .ok_or_else(|| "plugin import review expired".to_owned())?; + if pending.created_at.elapsed() >= std::time::Duration::from_secs(15 * 60) { + imports.remove(token); + return Err("plugin import review expired".into()); + } + if pending.review.package.compatibility != "compatible" { + return Err("incompatible plugin packages cannot be imported".into()); + } + if pending.review.package.trust != "trusted" { + return Err("confirm the publisher fingerprint before importing".into()); + } + if !pending.review.package.native_access.is_empty() && !native_code_consent { + return Err("explicit native-code consent is required for this package".into()); + } + // Unknown or required denials are rejected before any registry write. + let denied = denied_permission_set( + &pending.review.package.requested_permissions, + denied_permission_ids, + )?; + let registry = self.registry.clone(); + let plugin_lookup = pending.review.package.plugin_id.clone(); + let already_installed = + tokio::task::spawn_blocking(move || registry.active(&plugin_lookup)) + .await + .map_err(|_| "plugin registry worker failed".to_owned())? + .map_err(|error| error.to_string())? + .is_some(); + if already_installed { + return Err("plugin is already installed; use its update review to replace it".into()); + } + let private_dir = self.trust_dir.clone(); + let package_id = pending.review.package.plugin_id.clone(); + let key = pending.publisher_key; + let key_is_pinned = tokio::task::spawn_blocking(move || { + super::publisher_trust::PublisherTrustStore::open(private_dir) + .and_then(|trust| trust.is_pinned(&package_id, &key)) + .map_err(|error| error.to_string()) + }) + .await + .map_err(|_| "publisher trust worker failed".to_owned())??; + if !key_is_pinned { + return Err("publisher trust changed; review the package again".into()); + } + let package_path = pending.package_path.clone(); + let plugin_id = pending.review.package.plugin_id.clone(); + let publisher_fingerprint = pending.review.package.publisher_fingerprint.clone(); + let reviewed_permissions = !pending.review.package.requested_permissions.is_empty(); + self.packages + .install_candidate(package_path, key, EmulationPolicy::RequireNative, true) + .await + .map_err(|error| error.to_string())?; + imports.remove(token); + drop(imports); + if reviewed_permissions { + self.apply_install_permission_review(&plugin_id, &publisher_fingerprint, &denied) + .await?; + } + // Registration and activation happen now, not on the next composition. A failure leaves + // the installed package and its reviewed grants in place and is reported to the caller. + let activation = + Self::register_and_activate_installed(&lifecycle, std::slice::from_ref(&plugin_id)) + .await; + let outcome = activation.get(&plugin_id).cloned().unwrap_or(Ok(())); + Ok(PluginImportInstallOutcome { + plugin_id, + activated: outcome.is_ok(), + activation_error: outcome.err(), + }) + } + + /// Resolves reviewed optional-permission decisions into the host's typed grant scopes for one + /// just-installed package in the active profile. Required permissions are always granted and a + /// denied optional permission is never silently re-granted. + async fn import_permission_plan( + &self, + plugin_id: &str, + publisher_fingerprint: &str, + denied: &BTreeSet, + ) -> Result { + let lifecycle = self + .lifecycle + .read() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .clone() + .ok_or_else(|| "managed plugin runtime is unavailable".to_owned())?; + let snapshot = lifecycle + .installed_permission_snapshot(plugin_id.to_owned(), publisher_fingerprint.to_owned()) + .await + .map_err(|error| error.message().to_owned())?; + let mut decisions = Vec::new(); + for request in &snapshot.requested_permissions { + // A host-unknown optional permission has no enforceable scope, so it stays + // unsupported rather than being presented as granted. + if request.allowed_scopes.is_empty() { + continue; + } + let granted = request.required || !denied.contains(&request.permission_id); + for scope in &request.allowed_scopes { + decisions.push(super::grants::PermissionDecision { + permission_id: request.permission_id.clone(), + scope: scope.clone(), + granted, + }); + } + } + Ok(ImportPermissionPlan { + profile_id: snapshot.profile_id, + publisher_fingerprint: snapshot.publisher_fingerprint, + grant_revision: snapshot.grant_revision, + decisions, + }) + } + + /// Submits one package's reviewed decisions through the same permission-review path the + /// activation review uses. A failure is reported instead of leaving a denied permission + /// granted. + async fn apply_install_permission_review( + &self, + plugin_id: &str, + publisher_fingerprint: &str, + denied: &BTreeSet, + ) -> Result<(), String> { + let plan = self + .import_permission_plan(plugin_id, publisher_fingerprint, denied) + .await + .map_err(|error| { + format!( + "plugin {plugin_id} was installed but its permission review failed: {error}" + ) + })?; + if plan.decisions.is_empty() { + return Ok(()); + } + let lifecycle = self + .lifecycle + .read() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .clone() + .ok_or_else(|| "managed plugin runtime is unavailable".to_owned())?; + lifecycle + .replace_installed_permissions( + &self.activations, + plugin_id.to_owned(), + plan.profile_id, + plan.publisher_fingerprint, + plan.grant_revision, + plan.decisions, + ) + .await + .map(|_| ()) + .map_err(|error| { + format!( + "plugin {plugin_id} was installed but its permission decisions were not saved: {}", + error.message() + ) + }) + } + + /// Registers just-installed packages with the live host and enables each one for the active + /// profile. Every failure is reported per plugin; the installed package and its grants remain. + async fn register_and_activate_installed( + lifecycle: &std::sync::Arc, + plugin_ids: &[String], + ) -> BTreeMap> { + let registration = match lifecycle.register_installed_packages().await { + Ok(outcomes) => outcomes, + Err(error) => { + let message = format!( + "the installed package runtime could not be registered: {}", + error.message() + ); + return plugin_ids + .iter() + .map(|plugin_id| (plugin_id.clone(), Err(message.clone()))) + .collect(); + } + }; + let mut results = BTreeMap::new(); + for plugin_id in plugin_ids { + if let Some(error) = registration + .iter() + .find(|outcome| outcome.plugin_id == *plugin_id) + .and_then(|outcome| outcome.error.as_deref()) + { + results.insert( + plugin_id.clone(), + Err(format!( + "the installed package runtime could not be registered: {error}" + )), + ); + continue; + } + if !lifecycle.is_registered(plugin_id) { + results.insert( + plugin_id.clone(), + Err("the installed package is not registered for this host".to_owned()), + ); + continue; + } + results.insert( + plugin_id.clone(), + lifecycle + .enable(plugin_id.clone()) + .await + .map_err(|error| format!("activation failed: {}", error.message())), + ); + } + results + } + + /// Stages, verifies and reviews a user-selected bundle without executing component code. + /// + /// The bundle envelope and every component are validated by the bundle verifier and the + /// ordinary package inspection, then each component's review is built by the same + /// [`package_import_review`] a standalone import uses. No permission is granted here; the + /// single publisher decision is [`Self::bundle_import_confirm_publisher`]. + pub async fn bundle_import_review( + &self, + archive_path: PathBuf, + ) -> Result { + const MAX_PENDING_IMPORTS: usize = 8; + const IMPORT_REVIEW_TTL: std::time::Duration = std::time::Duration::from_secs(15 * 60); + { + let mut imports = self.bundle_imports.lock().await; + imports.retain(|_, pending| pending.created_at.elapsed() < IMPORT_REVIEW_TTL); + if imports.len() >= MAX_PENDING_IMPORTS { + return Err("too many plugin bundles are awaiting review".into()); + } + } + let selected = archive_path.clone(); + tokio::task::spawn_blocking(move || { + let metadata = fs::symlink_metadata(&selected).map_err(|error| error.to_string())?; + if !metadata.is_file() || metadata.file_type().is_symlink() { + return Err("selected plugin bundle is not a regular file".to_owned()); + } + Ok::<_, String>(()) + }) + .await + .map_err(|_| "plugin bundle import staging worker failed".to_owned())??; + let candidate = + super::bundles::inspect_bundle_review(&archive_path, EmulationPolicy::RequireNative) + .await + .map_err(|error| format!("selected plugin bundle failed validation: {error}"))?; + let super::bundles::BundleReviewCandidate { + bundle, + publisher_key, + components: staged, + } = candidate; + let report = super::bundles::BundleCandidateReport { + bundle: bundle.clone(), + components: staged + .iter() + .map(|component| component.inspection.clone()) + .collect(), + }; + let private_dir = self.trust_dir.clone(); + let key = publisher_key; + let components = tokio::task::spawn_blocking(move || { + let trust = super::publisher_trust::PublisherTrustStore::open(private_dir) + .map_err(|error| format!("publisher trust store is unavailable: {error}"))?; + staged + .into_iter() + .map(|component| { + let review = package_import_review(&component.report, &trust, &key)?; + Ok(BundleComponentReview { + kind: component.inspection.kind, + availability: component.inspection.availability, + review, + }) + }) + .collect::, String>>() + }) + .await + .map_err(|_| "plugin bundle trust worker failed".to_owned())??; + let (trust, pinned_fingerprint) = + bundle_trust_state(components.iter().map(|component| &component.review)); + let license = bundle_license_summary(&components); + let mut nonce = [0; 16]; + getrandom::fill(&mut nonce).map_err(|error| error.to_string())?; + let token = nonce + .iter() + .map(|byte| format!("{byte:02x}")) + .collect::(); + let review = BundleImportReview { + token: token.clone(), + bundle, + trust, + pinned_fingerprint, + license, + components, + }; + self.bundle_imports.lock().await.insert( + token, + PendingBundleImport { + publisher_key, + review: review.clone(), + archive_path, + report, + created_at: std::time::Instant::now(), + }, + ); + Ok(review) + } + + /// Pins the bundle publisher key for every component in one write after the user confirms the + /// exact fingerprint the review displayed. This is one publisher decision: either every + /// component accepts the key or none does, and no permission is granted. + pub async fn bundle_import_confirm_publisher( + &self, + token: &str, + confirmed_fingerprint: &str, + ) -> Result { + self.lifecycle + .read() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .clone() + .ok_or_else(|| "managed plugin runtime is unavailable".to_owned())? + .require_active_profile() + .map_err(|error| error.message().to_owned())?; + let mut imports = self.bundle_imports.lock().await; + let pending = imports + .get_mut(token) + .ok_or_else(|| "plugin bundle import review expired".to_owned())?; + if pending.created_at.elapsed() >= std::time::Duration::from_secs(15 * 60) { + imports.remove(token); + return Err("plugin bundle import review expired".into()); + } + if pending.review.bundle.publisher_fingerprint != confirmed_fingerprint { + return Err("publisher fingerprint confirmation does not match".into()); + } + let private_dir = self.trust_dir.clone(); + let publisher_key = pending.publisher_key; + let plugin_ids = pending + .review + .components + .iter() + .map(|component| component.review.plugin_id.clone()) + .collect::>(); + let fingerprint = confirmed_fingerprint.to_owned(); + let pinned = tokio::task::spawn_blocking(move || { + let _publisher = super::managed_packages::lock_publisher_identity(); + let mut trust = super::publisher_trust::PublisherTrustStore::open(private_dir) + .map_err(|error| error.to_string())?; + trust + .confirm_publishers(&plugin_ids, &publisher_key, &fingerprint) + .map_err(|error| error.to_string()) + }) + .await + .map_err(|_| "publisher trust worker failed".to_owned())??; + pending.review.trust = "trusted".into(); + pending.review.pinned_fingerprint = None; + for component in &mut pending.review.components { + component.review.trust = "trusted".into(); + component.review.pinned_fingerprint = None; + component.review.publisher_fingerprint.clone_from(&pinned); + } + Ok(pending.review.clone()) + } + + /// Installs one reviewed bundle through the ordinary staged registry path. This is the + /// approved step behind the single review: the publisher must be pinned for every component, + /// native-code consent must cover a component that declares native access, and the archive on + /// disk is re-verified against the reviewed component report before any registry write. The + /// safety rules match [`Self::import_install`]; the difference is only that one bundle approval + /// installs all components atomically and then applies each component's optional-permission + /// decisions to the active profile. + pub async fn bundle_import_install( + &self, + token: &str, + native_code_consent: bool, + component_denied_permissions: &[BundleComponentDeniedPermissions], + ) -> Result { + let lifecycle = self + .lifecycle + .read() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .clone() + .ok_or_else(|| "managed plugin runtime is unavailable".to_owned())?; + lifecycle + .require_active_profile() + .map_err(|error| error.message().to_owned())?; + let bundles = self + .bundle_store() + .ok_or_else(|| "plugin bundle mapping is unavailable".to_owned())?; + let mut imports = self.bundle_imports.lock().await; + let pending = imports + .get(token) + .ok_or_else(|| "plugin bundle import review expired".to_owned())?; + if pending.created_at.elapsed() >= std::time::Duration::from_secs(15 * 60) { + imports.remove(token); + return Err("plugin bundle import review expired".into()); + } + if pending.review.trust != "trusted" { + return Err("confirm the bundle publisher fingerprint before importing".into()); + } + if pending + .review + .components + .iter() + .any(|component| !component.review.native_access.is_empty()) + && !native_code_consent + { + return Err("explicit native-code consent is required for this bundle".into()); + } + // Every component denial names a reviewed component, and every denied id is one of that + // component's optional requests. This runs before any registry write. + let mut denials: BTreeMap> = BTreeMap::new(); + for submission in component_denied_permissions { + let Some(component) = pending + .review + .components + .iter() + .find(|component| component.review.plugin_id == submission.plugin_id) + else { + return Err(format!( + "plugin `{}` is not part of this bundle review", + submission.plugin_id + )); + }; + if denials.contains_key(&submission.plugin_id) { + return Err(format!( + "component {} appears more than once in one grouped import review", + submission.plugin_id + )); + } + let denied = denied_permission_set( + &component.review.requested_permissions, + &submission.denied_permission_ids, + )?; + denials.insert(submission.plugin_id.clone(), denied); + } + let private_dir = self.trust_dir.clone(); + let plugin_ids = pending + .review + .components + .iter() + .map(|component| component.review.plugin_id.clone()) + .collect::>(); + let key = pending.publisher_key; + let all_pinned = tokio::task::spawn_blocking(move || { + let trust = super::publisher_trust::PublisherTrustStore::open(private_dir) + .map_err(|error| error.to_string())?; + for plugin_id in plugin_ids { + if !trust + .is_pinned(&plugin_id, &key) + .map_err(|error| error.to_string())? + { + return Ok::<_, String>(false); + } + } + Ok(true) + }) + .await + .map_err(|_| "publisher trust worker failed".to_owned())??; + if !all_pinned { + return Err("publisher trust changed; review the bundle again".into()); + } + let installed_at = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_err(|error| error.to_string())? + .as_secs() as i64; + let installed = super::bundles::install_bundle_candidate( + &pending.archive_path, + pending.report.clone(), + self.registry.clone(), + bundles, + EmulationPolicy::RequireNative, + installed_at, + ) + .await + .map_err(|error| error.to_string())?; + let reviewed_components = pending.review.components.clone(); + imports.remove(token); + drop(imports); + let mut permission_errors = BTreeMap::new(); + let mut submissions = Vec::new(); + for component in &installed.components { + let Some(reviewed) = reviewed_components + .iter() + .find(|reviewed| reviewed.review.plugin_id == component.plugin_id) + else { + continue; + }; + if reviewed.review.requested_permissions.is_empty() { + continue; + } + let denied = denials + .get(&component.plugin_id) + .cloned() + .unwrap_or_default(); + if !component.active { + if !denied.is_empty() { + permission_errors.insert( + component.plugin_id.clone(), + "the component is installed but not active on this host; its permission decisions cannot be saved yet" + .to_owned(), + ); + } + continue; + } + match self + .import_permission_plan( + &component.plugin_id, + &reviewed.review.publisher_fingerprint, + &denied, + ) + .await + { + Ok(plan) if plan.decisions.is_empty() => {} + Ok(plan) => submissions.push(BundleComponentPermissionSubmission { + plugin_id: component.plugin_id.clone(), + expected_profile_id: plan.profile_id, + expected_publisher_fingerprint: plan.publisher_fingerprint, + expected_revision: plan.grant_revision, + decisions: plan.decisions, + }), + Err(error) => { + permission_errors.insert( + component.plugin_id.clone(), + format!("permission review failed: {error}"), + ); + } + } + } + if !submissions.is_empty() { + let result = self.apply_installed_bundle_permissions(submissions).await?; + for outcome in result.components { + if let Some(error) = outcome.error { + permission_errors.insert( + outcome.plugin_id, + format!("permission decisions were not saved: {error}"), + ); + } + } + } + // Enable every compatible component for the active profile now. Unavailable components + // stay installed without a runtime; an activation failure keeps the component installed + // and is reported instead of pretending it runs. + let compatible_ids = installed + .components + .iter() + .filter(|component| component.active) + .map(|component| component.plugin_id.clone()) + .collect::>(); + let mut activation = + Self::register_and_activate_installed(&lifecycle, &compatible_ids).await; + Ok(BundleImportInstallOutcome { + bundle_id: installed.bundle.bundle_id, + components: installed + .components + .into_iter() + .map(|component| { + let outcome = component + .active + .then(|| activation.remove(&component.plugin_id)) + .flatten(); + let (activated, activation_error) = match outcome { + Some(Ok(())) => (true, None), + Some(Err(error)) => (false, Some(error)), + None => (false, None), + }; + BundleImportInstalledComponent { + permission_error: permission_errors.remove(&component.plugin_id), + plugin_id: component.plugin_id, + kind: component.kind, + version: component.version, + active: component.active, + activated, + activation_error, + } + }) + .collect(), + }) + } + + /// Applies per-component permission decisions from one grouped review through the ordinary + /// per-plugin grant path. Each component is independent: a rejected decision (including a + /// stale grant revision) is reported for that component only and its siblings are still + /// saved. This command itself grants nothing; every grant is an explicit component decision. + pub async fn apply_bundle_permissions( + &self, + submissions: Vec, + ) -> Result { + self.apply_bundle_permissions_with(submissions, true).await + } + + /// The same per-component application for components a reviewed bundle import just installed + /// and pinned. Their providers are registered only when the host next composes the runtime, + /// so the installed-and-trusted package verification stands in for the registration check. + async fn apply_installed_bundle_permissions( + &self, + submissions: Vec, + ) -> Result { + self.apply_bundle_permissions_with(submissions, false).await + } + + async fn apply_bundle_permissions_with( + &self, + submissions: Vec, + require_registration: bool, + ) -> Result { + const MAX_COMPONENTS: usize = 8; + if submissions.is_empty() { + return Err("a grouped permission review requires at least one component".into()); + } + if submissions.len() > MAX_COMPONENTS { + return Err( + "a grouped permission review cannot exceed the bundle component limit".into(), + ); + } + let mut seen = BTreeSet::new(); + for submission in &submissions { + if !seen.insert(submission.plugin_id.as_str()) { + return Err(format!( + "component {} appears more than once in one grouped review", + submission.plugin_id + )); + } + } + let lifecycle = self + .lifecycle + .read() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .clone() + .ok_or_else(|| "managed plugin runtime is unavailable".to_owned())?; + let mut components = Vec::with_capacity(submissions.len()); + for submission in submissions { + let result = if require_registration { + self.replace_permissions( + submission.plugin_id.clone(), + submission.expected_profile_id, + submission.expected_publisher_fingerprint, + submission.expected_revision, + submission.decisions, + ) + .await + } else { + lifecycle + .replace_installed_permissions( + &self.activations, + submission.plugin_id.clone(), + submission.expected_profile_id, + submission.expected_publisher_fingerprint, + submission.expected_revision, + submission.decisions, + ) + .await + }; + let outcome = match result { + Ok(snapshot) => BundleComponentPermissionOutcome { + plugin_id: submission.plugin_id, + snapshot: Some(snapshot), + error: None, + }, + Err(status) => BundleComponentPermissionOutcome { + plugin_id: submission.plugin_id, + snapshot: None, + error: Some(status.message().to_owned()), + }, + }; + components.push(outcome); + } + Ok(BundlePermissionResult { components }) + } + + pub async fn permission_snapshot( + &self, + plugin_id: String, + ) -> Result { + let lifecycle = self + .lifecycle + .read() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .clone() + .ok_or_else(|| tonic::Status::unavailable("managed plugin runtime is unavailable"))?; + lifecycle.permission_snapshot(plugin_id).await + } + + pub async fn replace_permissions( + &self, + plugin_id: String, + expected_profile_id: String, + expected_publisher_fingerprint: String, + expected_revision: u64, + decisions: Vec, + ) -> Result { + // Package activation and permission review must agree on the active signed manifest. + let lifecycle = self + .lifecycle + .read() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .clone() + .ok_or_else(|| tonic::Status::unavailable("managed plugin runtime is unavailable"))?; + lifecycle + .replace_permissions( + &self.activations, + plugin_id, + expected_profile_id, + expected_publisher_fingerprint, + expected_revision, + decisions, + ) + .await + } + + pub async fn configuration_state( + &self, + plugin_id: String, + ) -> Result { + let lifecycle = self + .lifecycle + .read() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .clone() + .ok_or_else(|| tonic::Status::unavailable("managed plugin runtime is unavailable"))?; + lifecycle.configuration_state(plugin_id).await + } + + pub fn preferences(&self) -> PluginUpdatePreferences { + self.preferences + .lock() + .unwrap_or_else(|poison| poison.into_inner()) + .clone() + } + + /// Connects profile-scoped grants once the authenticated plugin profile source is created. + pub fn set_profiles(&self, profiles: std::sync::Arc) { + *self + .profiles + .lock() + .unwrap_or_else(|poison| poison.into_inner()) = Some(profiles); + } + + pub fn set_periodic_checks(&self, enabled: bool) -> Result { + let next = PluginUpdatePreferences { + periodic_checks: enabled, + }; + let mut preferences = self + .preferences + .lock() + .unwrap_or_else(|poison| poison.into_inner()); + write_preferences(&self.preferences_path, &next)?; + *preferences = next.clone(); + Ok(next) + } + + pub fn available_updates(&self) -> Vec { + self.available + .lock() + .unwrap_or_else(|poison| poison.into_inner()) + .clone() + } + + /// Returns inert metadata for installed, publisher-pinned packages. Signature and compatibility + /// inspection use the package lifecycle worker; this inventory never starts plugin code. + /// + /// Installed bundles are aggregated: their components become one `bundle` entry that carries + /// each component's own status, while standalone packages keep one entry each. Grouping comes + /// from the registry mapping, never from matching names or publishers. + pub async fn managed_inventory(&self) -> Result, String> { + let registry = self.registry.clone(); + let trust_dir = self.trust_dir.clone(); + let installed = tokio::task::spawn_blocking(move || { + registry + .active_versions() + .map_err(|error| error.to_string()) + }) + .await + .map_err(|_| "plugin registry worker failed".to_owned())??; + let bundles: Vec = match self.bundle_store() { + Some(store) => tokio::task::spawn_blocking(move || { + store.bundles().map_err(|error| error.to_string()) + }) + .await + .map_err(|_| "plugin bundle mapping worker failed".to_owned())??, + None => Vec::new(), + }; + let trust = tokio::task::spawn_blocking(move || { + super::publisher_trust::PublisherTrustStore::open(trust_dir) + .map_err(|error| error.to_string()) + }) + .await + .map_err(|_| "publisher trust worker failed".to_owned())??; + let lifecycle = self + .lifecycle + .read() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .clone(); + let bundled: BTreeSet<&str> = bundles + .iter() + .flat_map(|bundle| bundle.components.iter()) + .map(|component| component.plugin_id.as_str()) + .collect(); + let mut inventory = Vec::new(); + for package in installed { + if bundled.contains(package.plugin_id.as_str()) { + continue; + } + let key = match package_key(&package.package_path) { + Ok(key) => key, + Err(_) => continue, + }; + if !trust + .is_pinned(&package.plugin_id, &key) + .map_err(|error| error.to_string())? + { + continue; + } + let inspection = self + .packages + .inspect_candidate(&package.package_path, key, EmulationPolicy::RequireNative) + .await; + let Ok(report) = inspection else { continue }; + if report.manifest.id != package.plugin_id || report.manifest.version != package.version + { + continue; + } + let plugin_kind = match report.manifest.kind { + super::package::PluginKind::Provider => "provider", + super::package::PluginKind::Extension => "extension", + }; + let is_extension = plugin_kind == "extension"; + let compatible = report.selected_target().is_ok(); + let runtime_available = compatible + && (!is_extension + || lifecycle.as_ref().is_some_and(|lifecycle| { + lifecycle.extension_runtime_available(&package.plugin_id) + })); + let enabled = match &lifecycle { + Some(lifecycle) if is_extension => lifecycle + .enabled(package.plugin_id.clone()) + .await + .unwrap_or(false), + _ => false, + }; + inventory.push(super::PluginInfo { + provider_id: report.manifest.provider_id.clone().unwrap_or_default(), + plugin_id: report.manifest.id.clone(), + plugin_kind: plugin_kind.to_owned(), + name: report.manifest.name.clone(), + source: "community".to_owned(), + status: "installed".to_owned(), + capabilities: Vec::new(), + session: "stopped".to_owned(), + native_access: report.manifest.native_access.clone(), + version: package.version, + enabled: Some(enabled), + runtime_available: Some(runtime_available), + compatibility_details: Some(report.compatibility_review()), + publisher_fingerprint: Some(super::publisher_trust::key_fingerprint(&key)), + bundle_id: None, + bundle_name: None, + bundle_version: None, + bundle_component_kind: None, + bundle_publisher_fingerprint: None, + bundle_components: None, + }); + } + for bundle in bundles { + inventory.push(self.bundle_entry(&bundle, &trust, lifecycle.as_ref()).await); + } + Ok(inventory) + } + + /// Builds the single inventory entry for one installed bundle from its mapping. Each component + /// is inspected at the exact version the mapping recorded, so an installed-but-inactive + /// component (for example an unavailable extension) is reported with its real status instead + /// of disappearing from the inventory. + async fn bundle_entry( + &self, + bundle: &BundleRecord, + trust: &super::publisher_trust::PublisherTrustStore, + lifecycle: Option<&std::sync::Arc>, + ) -> super::PluginInfo { + let mut components = Vec::with_capacity(bundle.components.len()); + for component in &bundle.components { + components.push( + self.bundle_component_entry(component, trust, lifecycle) + .await, + ); + } + let status = if components + .iter() + .any(|component| component.status == "installed") + { + "installed" + } else if components + .iter() + .any(|component| component.status == "failed") + { + "failed" + } else if components + .iter() + .any(|component| component.status == "unavailable") + { + "unavailable" + } else if components + .iter() + .any(|component| component.status == "incompatible") + { + "incompatible" + } else { + "missing" + }; + let session = if components + .iter() + .any(|component| component.session == "active") + { + "active" + } else { + "stopped" + }; + let mut native_access = Vec::new(); + for component in &components { + for access in &component.native_access { + if !native_access.contains(access) { + native_access.push(access.clone()); + } + } + } + super::PluginInfo { + provider_id: String::new(), + plugin_id: bundle.bundle_id.clone(), + plugin_kind: "bundle".to_owned(), + name: bundle.name.clone(), + version: bundle.version.clone(), + source: "community".to_owned(), + status: status.to_owned(), + capabilities: Vec::new(), + session: session.to_owned(), + native_access, + enabled: None, + runtime_available: None, + publisher_fingerprint: None, + compatibility_details: None, + bundle_id: Some(bundle.bundle_id.clone()), + bundle_name: Some(bundle.name.clone()), + bundle_version: Some(bundle.version.clone()), + bundle_component_kind: None, + bundle_publisher_fingerprint: Some(bundle.publisher_fingerprint.clone()), + bundle_components: Some(components), + } + } + + async fn bundle_component_entry( + &self, + component: &gamenode_platform::plugin_bundle_db::BundleComponentRecord, + trust: &super::publisher_trust::PublisherTrustStore, + lifecycle: Option<&std::sync::Arc>, + ) -> super::PluginBundleComponent { + let missing = |status: &str| super::PluginBundleComponent { + plugin_id: component.plugin_id.clone(), + plugin_kind: component.kind.clone(), + name: component.plugin_id.clone(), + version: component.package_version.clone(), + status: status.to_owned(), + session: "stopped".to_owned(), + enabled: None, + runtime_available: None, + publisher_fingerprint: None, + compatibility_details: None, + native_access: Vec::new(), + }; + let registry = self.registry.clone(); + let lookup_id = component.plugin_id.clone(); + let lookup_version = component.package_version.clone(); + let installed = tokio::task::spawn_blocking(move || registry.versions(&lookup_id)) + .await + .ok() + .and_then(Result::ok) + .and_then(|versions| { + versions + .into_iter() + .find(|installed| installed.version == lookup_version) + }); + let Some(installed) = installed else { + return missing("missing"); + }; + let Ok(key) = package_key(&installed.package_path) else { + return missing("failed"); + }; + if !trust.is_pinned(&installed.plugin_id, &key).unwrap_or(false) { + return missing("failed"); + } + let Ok(report) = self + .packages + .inspect_candidate(&installed.package_path, key, EmulationPolicy::RequireNative) + .await + else { + return missing("failed"); + }; + if report.manifest.id != installed.plugin_id + || report.manifest.version != installed.version + || !matches!( + (report.manifest.kind, component.kind.as_str()), + (super::package::PluginKind::Provider, "provider") + | (super::package::PluginKind::Extension, "extension") + ) + { + return missing("failed"); + } + let plugin_kind = match report.manifest.kind { + super::package::PluginKind::Provider => "provider", + super::package::PluginKind::Extension => "extension", + }; + let compatible = report.selected_target().is_ok(); + let runtime_available = compatible + && (plugin_kind == "provider" + || lifecycle.is_some_and(|lifecycle| { + lifecycle.extension_runtime_available(&installed.plugin_id) + })); + let status = if !compatible { + "incompatible" + } else if plugin_kind == "extension" && !runtime_available { + "unavailable" + } else { + "installed" + }; + let enabled = match lifecycle { + Some(lifecycle) if plugin_kind == "extension" => lifecycle + .enabled(installed.plugin_id.clone()) + .await + .unwrap_or(false), + _ => false, + }; + super::PluginBundleComponent { + plugin_id: installed.plugin_id.clone(), + plugin_kind: plugin_kind.to_owned(), + name: report.manifest.name.clone(), + version: installed.version, + status: status.to_owned(), + session: "stopped".to_owned(), + enabled: Some(enabled), + runtime_available: Some(runtime_available), + publisher_fingerprint: Some(super::publisher_trust::key_fingerprint(&key)), + compatibility_details: Some(report.compatibility_review()), + native_access: report.manifest.native_access.clone(), + } + } + + /// Returns signed declarations for currently active, publisher-pinned third-party packages. + /// Package reads and signature checks run on a blocking worker. + pub async fn playtime_inventory(&self) -> Result, String> { + let registry = self.registry.clone(); + let trust_dir = self.trust_dir.clone(); + tokio::task::spawn_blocking(move || { + let (active, trust) = { + let _publisher = super::managed_packages::lock_publisher_identity(); + let active = registry + .active_versions() + .map_err(|error| error.to_string())?; + let trust = super::publisher_trust::PublisherTrustStore::open(trust_dir) + .map_err(|error| error.to_string())?; + (active, trust) + }; + let mut inventory = Vec::new(); + for installed in active { + let key = match package_key(&installed.package_path) { + Ok(key) => key, + Err(_) => continue, + }; + if !trust + .is_pinned(&installed.plugin_id, &key) + .map_err(|error| error.to_string())? + { + continue; + } + let _integrity = match gamenode_platform::plugin_packages::verify_package_directory( + &installed.package_path, + &key, + ) { + Ok(integrity) => integrity, + Err(_) => continue, + }; + let bytes = match fs::read(installed.package_path.join("plugin.json")) { + Ok(bytes) => bytes, + Err(_) => continue, + }; + let manifest = match Manifest::parse_json(&bytes) { + Ok(manifest) => manifest.manifest().clone(), + Err(_) => continue, + }; + if manifest.id != installed.plugin_id || manifest.version != installed.version { + continue; + } + // Only a package that declares a playtime capability belongs in this inventory. + // Every other trusted package stays installed without a playtime row. + if !manifest.playtime.declares_support() { + continue; + } + inventory.push(PluginPlaytimeInfo { + plugin_id: manifest.id, + name: manifest.name, + version: manifest.version, + playtime: manifest.playtime, + accounting_enabled: true, + }); + } + Ok::<_, String>(inventory) + }) + .await + .map_err(|_| "plugin inventory worker failed".to_owned())? + } + + /// Check every active package with an update URL. This method verifies signed metadata only; + /// no candidate archive is downloaded and no plugin code is executed. + pub async fn check_updates(&self) -> Result, String> { + let _check = self.checks.lock().await; + let registry = self.registry.clone(); + let active = tokio::task::spawn_blocking(move || registry.active_versions()) + .await + .map_err(|_| "plugin registry worker failed".to_owned())? + .map_err(|error| error.to_string())?; + let bundled_ids: BTreeSet = match self.bundle_store() { + Some(store) => tokio::task::spawn_blocking(move || store.bundles()) + .await + .map_err(|_| "plugin bundle mapping worker failed".to_owned())? + .map_err(|error| error.to_string())? + .into_iter() + .flat_map(|bundle| bundle.components) + .map(|component| component.plugin_id) + .collect(), + None => BTreeSet::new(), + }; + let mut updates = Vec::new(); + for installed in active { + // A bundle component updates only as part of its bundle; offering a standalone update + // here would mix the two installation models. + if bundled_ids.contains(&installed.plugin_id) { + continue; + } + let current = self + .packages + .inspect_candidate( + &installed.package_path, + package_key(&installed.package_path)?, + EmulationPolicy::RequireNative, + ) + .await + .map_err(|error| error.to_string())?; + let Some(feed_url) = current.manifest.update_url.as_deref() else { + continue; + }; + let key = decode_publisher_key(¤t.manifest.publisher.public_key)?; + let trust = super::publisher_trust::PublisherTrustStore::open(&self.trust_dir) + .map_err(|error| error.to_string())?; + if !trust + .is_pinned(&installed.plugin_id, &key) + .map_err(|error| error.to_string())? + { + continue; + } + let feed_origin = url::Url::parse(feed_url) + .map_err(|error| error.to_string())? + .origin() + .ascii_serialization(); + let verified = ManagedPluginUpdater::new(self.registry.clone()) + .check_feed( + &self.verifier, + &self.client, + &installed.plugin_id, + feed_url, + key, + move |origin| origin == feed_origin, + ) + .await + .map_err(|error| error.to_string())?; + let current_version = + Version::parse(&installed.version).map_err(|error| error.to_string())?; + let mut versions: Vec = verified + .index() + .releases + .iter() + .filter_map(|release| { + if release.bundle_sha256.is_some() { + return None; + } + Version::parse(&release.version) + .ok() + .filter(|version| version > ¤t_version) + .map(|_| release.version.clone()) + }) + .collect(); + if versions.is_empty() { + continue; + } + versions + .sort_by(|left, right| Version::parse(right).ok().cmp(&Version::parse(left).ok())); + self.indexes + .lock() + .unwrap_or_else(|poison| poison.into_inner()) + .insert(installed.plugin_id.clone(), verified); + updates.push(AvailablePluginUpdate { + plugin_id: installed.plugin_id, + name: current.manifest.name, + installed_version: installed.version, + versions, + }); + } + write_available(&self.available_path, &updates)?; + *self + .available + .lock() + .unwrap_or_else(|poison| poison.into_inner()) = updates.clone(); + Ok(updates) + } + + pub async fn review(&self, plugin_id: &str, version: &str) -> Result { + let index = self + .indexes + .lock() + .unwrap_or_else(|poison| poison.into_inner()) + .get(plugin_id) + .cloned() + .ok_or_else(|| "check for updates first".to_owned())?; + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_err(|error| error.to_string())? + .as_secs(); + if index.index().expires_at <= now { + return Err("the signed update index expired; check for updates again".into()); + } + let registry = self.registry.clone(); + let id = plugin_id.to_owned(); + let active = tokio::task::spawn_blocking(move || registry.active(&id)) + .await + .map_err(|_| "plugin registry worker failed".to_owned())? + .map_err(|error| error.to_string())? + .ok_or_else(|| "plugin is not installed".to_owned())?; + if let Some(store) = self.bundle_store() { + let lookup = plugin_id.to_owned(); + let mapped = tokio::task::spawn_blocking(move || store.bundle_for_plugin(&lookup)) + .await + .map_err(|_| "plugin bundle mapping worker failed".to_owned())? + .map_err(|error| error.to_string())?; + if mapped.is_some() { + return Err( + "this plugin belongs to a bundle; review the bundle update instead".into(), + ); + } + } + let current = self + .packages + .inspect_candidate( + &active.package_path, + package_key(&active.package_path)?, + EmulationPolicy::RequireNative, + ) + .await + .map_err(|error| error.to_string())?; + let feed_origin = current + .manifest + .update_url + .as_deref() + .and_then(|url| url::Url::parse(url).ok()) + .map(|url| url.origin().ascii_serialization()) + .ok_or_else(|| "plugin update URL is invalid".to_owned())?; + let release = index + .index() + .releases + .iter() + .find(|release| release.version == version) + .cloned() + .ok_or_else(|| "release is no longer available".to_owned())?; + if release.bundle_sha256.is_some() { + return Err( + "this index release is a signed bundle; use the bundle update review".into(), + ); + } + let current_version = Version::parse(&active.version).map_err(|error| error.to_string())?; + let candidate_version = + Version::parse(&release.version).map_err(|error| error.to_string())?; + if candidate_version <= current_version { + return Err("update is no longer newer than the active version".into()); + } + let release_origin = url::Url::parse(&release.package_url) + .map_err(|error| error.to_string())? + .origin() + .ascii_serialization(); + let archive = self + .verifier + .download_release(&self.client, &release, move |origin| { + origin == feed_origin || origin == release_origin + }) + .await + .map_err(|error| error.to_string())?; + self.review_downloaded_release(active, current.manifest, &index, &release, archive) + .await + } + + async fn review_downloaded_release( + &self, + active: InstalledPluginVersion, + current: Manifest, + index: &VerifiedUpdateIndex, + release: &UpdateRelease, + archive: Vec, + ) -> Result { + let publisher_key = decode_publisher_key(¤t.publisher.public_key)?; + let (work, report, candidate_key) = ManagedPluginUpdater::new(self.registry.clone()) + .stage_review_candidate(index, release, archive, publisher_key) + .await + .map_err(|error| error.to_string())?; + let compatibility_details = report.compatibility_review(); + let candidate_manifest = report.manifest; + // An update can widen or malform `network.fetch`; reject unsupported scopes at review + // time, as import does, rather than after activation breaks the permission screen. + super::grants::manifest_permission_requests(&candidate_manifest.permissions) + .map_err(|error| format!("plugin declares unsupported permission scopes: {error}"))?; + let mut review = UpdateReview::compare(¤t, &candidate_manifest); + review.compatibility_details = Some(compatibility_details); + review.publisher_fingerprint = super::publisher_trust::key_fingerprint(&candidate_key); + self.pending.lock().await.insert( + active.plugin_id, + PendingCandidate { + work: Some(work), + version: release.version.clone(), + installed_version: active.version, + publisher_key, + candidate_publisher_key: candidate_key, + confirmed_retrust: false, + is_rollback: false, + installed_manifest: current, + candidate_manifest, + review: review.clone(), + }, + ); + Ok(review) + } + + /// Installed versions older than the active version. Feed results never include these. + pub async fn rollback_versions(&self, plugin_id: &str) -> Result, String> { + let registry = self.registry.clone(); + let id = plugin_id.to_owned(); + let (active, versions) = tokio::task::spawn_blocking(move || { + let active = registry + .active(&id) + .map_err(|error| error.to_string())? + .ok_or_else(|| "plugin is not installed".to_owned())?; + let versions = registry.versions(&id).map_err(|error| error.to_string())?; + Ok::<_, String>((active, versions)) + }) + .await + .map_err(|_| "plugin registry worker failed".to_owned())??; + let active_version = Version::parse(&active.version).map_err(|error| error.to_string())?; + let mut versions: Vec<_> = versions + .into_iter() + .filter_map(|installed| { + Version::parse(&installed.version) + .ok() + .filter(|version| version < &active_version) + .map(|_| installed.version) + }) + .collect(); + versions.sort_by(|left, right| Version::parse(right).ok().cmp(&Version::parse(left).ok())); + Ok(versions) + } + + pub async fn available_rollbacks(&self) -> Result, String> { + let registry = self.registry.clone(); + let active = tokio::task::spawn_blocking(move || registry.active_versions()) + .await + .map_err(|_| "plugin registry worker failed".to_owned())? + .map_err(|error| error.to_string())?; + let mut available = Vec::new(); + for installed in active { + let manifest = self + .packages + .inspect_candidate( + &installed.package_path, + package_key(&installed.package_path)?, + EmulationPolicy::RequireNative, + ) + .await + .map_err(|error| error.to_string())? + .manifest; + let versions = self.rollback_versions(&installed.plugin_id).await?; + if !versions.is_empty() { + available.push(AvailablePluginRollback { + plugin_id: installed.plugin_id, + name: manifest.name, + active_version: installed.version, + versions, + }); + } + } + Ok(available) + } + + /// Bundle releases cached by the last check. Unlike standalone updates these are not persisted: + /// the index verifier's replay state is the durable part, and a review always re-downloads. + pub fn bundle_update_available(&self) -> Vec { + self.bundle_available + .lock() + .unwrap_or_else(|poison| poison.into_inner()) + .clone() + } + + /// Fetch each installed bundle's component feed and list releases that carry a bundle hash. + /// Components mapped to a bundle are never listed as standalone updates, and a standalone + /// plugin's feed releases without a bundle hash remain ordinary package updates. + pub async fn check_bundle_updates(&self) -> Result, String> { + let _check = self.checks.lock().await; + let Some(store) = self.bundle_store() else { + return Ok(Vec::new()); + }; + let bundles = tokio::task::spawn_blocking(move || store.bundles()) + .await + .map_err(|_| "plugin bundle mapping worker failed".to_owned())? + .map_err(|error| error.to_string())?; + let trust = super::publisher_trust::PublisherTrustStore::open(&self.trust_dir) + .map_err(|error| error.to_string())?; + let mut available = Vec::new(); + for bundle in bundles { + let Some((installed, current)) = self.bundle_feed_manifest(&bundle).await? else { + continue; + }; + let Some(feed_url) = current.manifest.update_url.as_deref() else { + continue; + }; + let key = decode_publisher_key(¤t.manifest.publisher.public_key)?; + if !trust + .is_pinned(&installed.plugin_id, &key) + .map_err(|error| error.to_string())? + { + continue; + } + let feed_origin = url::Url::parse(feed_url) + .map_err(|error| error.to_string())? + .origin() + .ascii_serialization(); + let verified = ManagedPluginUpdater::new(self.registry.clone()) + .check_feed( + &self.verifier, + &self.client, + &installed.plugin_id, + feed_url, + key, + move |origin| origin == feed_origin, + ) + .await + .map_err(|error| error.to_string())?; + let installed_version = + Version::parse(&bundle.version).map_err(|error| error.to_string())?; + let mut versions: Vec = verified + .index() + .releases + .iter() + .filter(|release| release.bundle_sha256.is_some()) + .filter_map(|release| { + Version::parse(&release.version) + .ok() + .filter(|version| version > &installed_version) + .map(|_| release.version.clone()) + }) + .collect(); + if versions.is_empty() { + continue; + } + versions + .sort_by(|left, right| Version::parse(right).ok().cmp(&Version::parse(left).ok())); + self.bundle_indexes + .lock() + .unwrap_or_else(|poison| poison.into_inner()) + .insert(bundle.bundle_id.clone(), verified); + available.push(AvailableBundleUpdate { + bundle_id: bundle.bundle_id, + name: bundle.name, + installed_version: bundle.version, + versions, + }); + } + *self + .bundle_available + .lock() + .unwrap_or_else(|poison| poison.into_inner()) = available.clone(); + Ok(available) + } + + /// The first bundle component whose active feed can carry a bundle release. Components are + /// inspected at the exact version the mapping records, never at an unrelated standalone version. + async fn bundle_feed_manifest( + &self, + bundle: &BundleRecord, + ) -> Result, String> { + for component in &bundle.components { + let registry = self.registry.clone(); + let plugin_id = component.plugin_id.clone(); + let version = component.package_version.clone(); + let installed = tokio::task::spawn_blocking(move || { + registry.versions(&plugin_id).map(|versions| { + versions + .into_iter() + .find(|installed| installed.version == version) + }) + }) + .await + .map_err(|_| "plugin registry worker failed".to_owned())? + .map_err(|error| error.to_string())? + .ok_or_else(|| { + format!( + "bundle component {} version {} is no longer installed", + component.plugin_id, component.package_version + ) + })?; + let key = package_key(&installed.package_path)?; + let report = self + .packages + .inspect_candidate(&installed.package_path, key, EmulationPolicy::RequireNative) + .await + .map_err(|error| error.to_string())?; + if report.manifest.update_url.is_some() { + return Ok(Some((installed, report))); + } + } + Ok(None) + } + + /// Reviews one signed bundle release from the feed. The downloaded archive must hash to the + /// bundle hash the index committed to and to the same bundle identity, publisher and component + /// set as the installed mapping; every component is staged and inspected without executing it. + pub async fn review_bundle_update( + &self, + bundle_id: &str, + version: &str, + ) -> Result { + let Some(store) = self.bundle_store() else { + return Err("plugin bundle mapping is unavailable".into()); + }; + let lookup = bundle_id.to_owned(); + let installed = tokio::task::spawn_blocking(move || store.bundle(&lookup)) + .await + .map_err(|_| "plugin bundle mapping worker failed".to_owned())? + .map_err(|error| error.to_string())? + .ok_or_else(|| "plugin bundle is not installed".to_owned())?; + let index = self + .bundle_indexes + .lock() + .unwrap_or_else(|poison| poison.into_inner()) + .get(bundle_id) + .cloned() + .ok_or_else(|| "check for bundle updates first".to_owned())?; + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_err(|error| error.to_string())? + .as_secs(); + if index.index().expires_at <= now { + return Err("the signed update index expired; check for updates again".into()); + } + let release = index + .index() + .releases + .iter() + .find(|release| release.version == version) + .cloned() + .ok_or_else(|| "release is no longer available".to_owned())?; + if release.bundle_sha256.is_none() { + return Err( + "this index release is a single package, not a bundle; use the package update review" + .into(), + ); + } + let Some((_feed_installed, current)) = self.bundle_feed_manifest(&installed).await? else { + return Err("the bundle has no component with an update feed".into()); + }; + let feed_origin = current + .manifest + .update_url + .as_deref() + .and_then(|url| url::Url::parse(url).ok()) + .map(|url| url.origin().ascii_serialization()) + .ok_or_else(|| "bundle update URL is invalid".to_owned())?; + let release_origin = url::Url::parse(&release.package_url) + .map_err(|error| error.to_string())? + .origin() + .ascii_serialization(); + let archive = self + .verifier + .download_release(&self.client, &release, move |origin| { + origin == feed_origin || origin == release_origin + }) + .await + .map_err(|error| error.to_string())?; + let work = tokio::task::spawn_blocking(UpdateWorkDir::create) + .await + .map_err(|_| "bundle update staging worker failed".to_owned())? + .map_err(|error| error.to_string())?; + let archive_path = work.path.join("bundle.gnbundle"); + let write_path = archive_path.clone(); + tokio::task::spawn_blocking(move || fs::write(&write_path, archive)) + .await + .map_err(|_| "bundle update staging worker failed".to_owned())? + .map_err(|error| error.to_string())?; + let (review, report) = self + .bundle_update_review_from_archive(&installed, &release, &archive_path) + .await?; + if review.components.is_empty() { + return Err("the bundle release has no components".into()); + } + let first = installed + .components + .first() + .ok_or_else(|| "the bundle mapping has no components".to_owned())?; + let installed_report = self + .inspect_installed_version(&first.plugin_id, &first.package_version) + .await?; + let publisher_key = decode_publisher_key(&installed_report.manifest.publisher.public_key)?; + self.pending_bundles.lock().await.insert( + bundle_id.to_owned(), + PendingBundleUpdate { + _work: work, + archive_path, + report, + installed, + release_version: version.to_owned(), + publisher_key, + review: review.clone(), + created_at: std::time::Instant::now(), + }, + ); + Ok(review) + } + + /// Build the grouped bundle review from one downloaded archive. Factored from the feed path so + /// the review can be exercised without a network and is the single place that decides which + /// bundle releases are compatible with an installed mapping. + pub(super) async fn bundle_update_review_from_archive( + &self, + installed: &BundleRecord, + release: &UpdateRelease, + archive_path: &Path, + ) -> Result<(BundleUpdateReview, super::bundles::BundleCandidateReport), String> { + let bundle_sha256 = release + .bundle_sha256 + .as_deref() + .ok_or_else(|| "the index release is not a signed bundle".to_owned())?; + let archive_for_worker = archive_path.to_owned(); + let verified = tokio::task::spawn_blocking(move || { + gamenode_platform::plugin_bundles::verify_bundle_archive(&archive_for_worker) + }) + .await + .map_err(|_| "bundle verification worker failed".to_owned())? + .map_err(|error| error.to_string())?; + if verified.manifest_sha256 != bundle_sha256 { + return Err("the downloaded bundle does not match the index bundle hash".into()); + } + if verified.manifest.id != installed.bundle_id { + return Err("the bundle release belongs to another bundle".into()); + } + let publisher_key = verified + .manifest + .publisher_key() + .map_err(|e| e.to_string())?; + if super::publisher_trust::key_fingerprint(&publisher_key) + != installed.publisher_fingerprint + { + return Err("a bundle update cannot change the bundle publisher".into()); + } + if release.version != verified.manifest.version { + return Err("the index release version does not match the bundle version".into()); + } + let installed_version = + Version::parse(&installed.version).map_err(|error| error.to_string())?; + let candidate_version = + Version::parse(&verified.manifest.version).map_err(|error| error.to_string())?; + if candidate_version <= installed_version { + return Err("update is no longer newer than the installed bundle version".into()); + } + let candidate = + super::bundles::inspect_bundle_review(archive_path, EmulationPolicy::RequireNative) + .await + .map_err(|error| format!("selected bundle update failed validation: {error}"))?; + let mapped = installed + .components + .iter() + .map(|component| (component.plugin_id.as_str(), component.kind.as_str())) + .collect::>(); + let candidate_set = candidate + .components + .iter() + .map(|component| { + ( + component.inspection.plugin_id.as_str(), + component.inspection.kind.as_str(), + ) + }) + .collect::>(); + if mapped != candidate_set || candidate.components.len() != installed.components.len() { + return Err("a bundle update cannot add, remove or re-kind a component".into()); + } + let mut components = Vec::with_capacity(candidate.components.len()); + for staged in &candidate.components { + let previous = installed + .components + .iter() + .find(|component| component.plugin_id == staged.inspection.plugin_id) + .ok_or_else(|| "a bundle update cannot add a component".to_owned())?; + let installed_report = self + .inspect_installed_version(&previous.plugin_id, &previous.package_version) + .await?; + components.push(bundle_component_update_review( + &installed_report.manifest, + &staged.report.manifest, + &staged.report, + &previous.package_version, + &staged.inspection.version, + )); + } + let added_permissions = + union_permissions(&components, |component| &component.added_permissions); + let removed_permissions = + union_permissions(&components, |component| &component.removed_permissions); + let changed_permissions = + union_permissions(&components, |component| &component.changed_permissions); + let review = BundleUpdateReview { + bundle_id: candidate.bundle.id.clone(), + name: candidate.bundle.name.clone(), + installed_version: installed.version.clone(), + candidate_version: candidate.bundle.version.clone(), + bundle_sha256: bundle_sha256.to_owned(), + publisher_fingerprint: candidate.bundle.publisher_fingerprint.clone(), + components, + added_permissions, + removed_permissions, + changed_permissions, + requires_manual_approval: true, + is_downgrade: false, + is_rollback: false, + }; + let report = super::bundles::BundleCandidateReport { + bundle: candidate.bundle, + components: candidate + .components + .iter() + .map(|component| component.inspection.clone()) + .collect(), + }; + Ok((review, report)) + } + + async fn inspect_installed_version( + &self, + plugin_id: &str, + version: &str, + ) -> Result { + let registry = self.registry.clone(); + let lookup_id = plugin_id.to_owned(); + let wanted = version.to_owned(); + let installed = tokio::task::spawn_blocking(move || registry.versions(&lookup_id)) + .await + .map_err(|_| "plugin registry worker failed".to_owned())? + .map_err(|error| error.to_string())? + .into_iter() + .find(|installed| installed.version == wanted) + .ok_or_else(|| { + format!("plugin {plugin_id} version {version} is no longer installed") + })?; + let key = package_key(&installed.package_path)?; + self.packages + .inspect_candidate(&installed.package_path, key, EmulationPolicy::RequireNative) + .await + .map_err(|error| error.to_string()) + } + + /// Reviews an archived bundle version. The archived mapping is read from the bundle history, + /// every component's installed package is inspected, and the review shows the current→target + /// version and permission differences without executing anything. + pub async fn review_bundle_rollback( + &self, + bundle_id: &str, + version: &str, + ) -> Result { + let Some(store) = self.bundle_store() else { + return Err("plugin bundle mapping is unavailable".into()); + }; + let lookup = bundle_id.to_owned(); + let wanted = version.to_owned(); + let (current, target) = tokio::task::spawn_blocking(move || { + let current = store + .bundle(&lookup) + .map_err(|error| error.to_string())? + .ok_or_else(|| "plugin bundle is not installed".to_owned())?; + let target = store + .previous_bundle(&lookup, &wanted) + .map_err(|error| error.to_string())? + .ok_or_else(|| "that bundle version is not available for rollback".to_owned())?; + Ok::<_, String>((current, target)) + }) + .await + .map_err(|_| "plugin bundle mapping worker failed".to_owned())??; + if target.components.len() != current.components.len() { + return Err("the archived bundle version has a different component set".into()); + } + let mut components = Vec::with_capacity(target.components.len()); + for archived in &target.components { + let current_component = current + .components + .iter() + .find(|component| component.plugin_id == archived.plugin_id) + .ok_or_else(|| { + "the archived bundle version has a different component set".to_owned() + })?; + if current_component.kind != archived.kind { + return Err("the archived bundle version has a different component set".into()); + } + let current_report = self + .inspect_installed_version( + ¤t_component.plugin_id, + ¤t_component.package_version, + ) + .await?; + let target_report = self + .inspect_installed_version(&archived.plugin_id, &archived.package_version) + .await?; + let mut review = bundle_component_update_review( + ¤t_report.manifest, + &target_report.manifest, + &target_report, + ¤t_component.package_version, + &archived.package_version, + ); + review.is_downgrade = true; + components.push(review); + } + let added_permissions = + union_permissions(&components, |component| &component.added_permissions); + let removed_permissions = + union_permissions(&components, |component| &component.removed_permissions); + let changed_permissions = + union_permissions(&components, |component| &component.changed_permissions); + let review = BundleUpdateReview { + bundle_id: target.bundle_id.clone(), + name: target.name.clone(), + installed_version: current.version.clone(), + candidate_version: target.version.clone(), + bundle_sha256: target.manifest_sha256.clone(), + publisher_fingerprint: target.publisher_fingerprint.clone(), + components, + added_permissions, + removed_permissions, + changed_permissions, + requires_manual_approval: true, + is_downgrade: true, + is_rollback: true, + }; + self.pending_rollbacks.lock().await.insert( + bundle_id.to_owned(), + PendingBundleRollback { + version: version.to_owned(), + created_at: std::time::Instant::now(), + }, + ); + Ok(review) + } + + pub async fn available_bundle_rollbacks(&self) -> Result, String> { + let Some(store) = self.bundle_store() else { + return Ok(Vec::new()); + }; + let bundles = tokio::task::spawn_blocking(move || store.bundles()) + .await + .map_err(|_| "plugin bundle mapping worker failed".to_owned())? + .map_err(|error| error.to_string())?; + let store = self.bundle_store().expect("bundle store was checked"); + let mut available = Vec::new(); + for bundle in bundles { + let id = bundle.bundle_id.clone(); + let lookup_store = store.clone(); + let versions = tokio::task::spawn_blocking(move || lookup_store.previous_versions(&id)) + .await + .map_err(|_| "plugin bundle mapping worker failed".to_owned())? + .map_err(|error| error.to_string())?; + if !versions.is_empty() { + available.push(AvailableBundleRollback { + bundle_id: bundle.bundle_id, + name: bundle.name, + active_version: bundle.version, + versions, + }); + } + } + Ok(available) + } + + /// Approves the reviewed bundle update. Every component is staged, installed and activated + /// together; the archive is re-verified against the reviewed report first, so a changed file + /// installs nothing. A failure keeps the previous set active. + pub async fn approve_bundle_update( + &self, + bundle_id: &str, + version: &str, + ) -> Result { + let _activation = self.activations.lock().await; + let lifecycle = self + .lifecycle + .read() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .clone() + .ok_or_else(|| "managed plugin runtime is unavailable".to_owned())?; + lifecycle + .require_active_profile() + .map_err(|error| error.message().to_owned())?; + let bundles = self + .bundle_store() + .ok_or_else(|| "plugin bundle mapping is unavailable".to_owned())?; + let profiles = self + .profiles + .lock() + .unwrap_or_else(|poison| poison.into_inner()) + .clone() + .ok_or_else(|| "plugin profiles are unavailable".to_owned())?; + let mut pending = self.pending_bundles.lock().await; + let reviewed = pending + .remove(bundle_id) + .ok_or_else(|| "review the bundle update before approving it".to_owned())?; + drop(pending); + if reviewed.release_version != version || reviewed.review.candidate_version != version { + return Err("the reviewed bundle update changed; review it again".into()); + } + if reviewed.installed.version != self.current_bundle_version(bundle_id).await? { + return Err( + "the installed bundle changed after review; review the update again".into(), + ); + } + if reviewed.created_at.elapsed() >= std::time::Duration::from_secs(15 * 60) { + return Err("the bundle update review expired; review it again".into()); + } + let private_dir = self.trust_dir.clone(); + let plugin_ids = reviewed + .installed + .components + .iter() + .map(|component| component.plugin_id.clone()) + .collect::>(); + let key = reviewed.publisher_key; + let all_pinned = tokio::task::spawn_blocking(move || { + let trust = super::publisher_trust::PublisherTrustStore::open(private_dir) + .map_err(|error| error.to_string())?; + for plugin_id in plugin_ids { + if !trust + .is_pinned(&plugin_id, &key) + .map_err(|error| error.to_string())? + { + return Ok::<_, String>(false); + } + } + Ok(true) + }) + .await + .map_err(|_| "publisher trust worker failed".to_owned())??; + if !all_pinned { + return Err("publisher trust changed; review the bundle update again".into()); + } + let installed_at = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_err(|error| error.to_string())? + .as_secs() as i64; + let grants = super::bundles::BundleGrantContext { + layout: self.grant_layout.clone(), + profiles, + }; + let result = super::bundles::apply_bundle_update( + &reviewed.archive_path, + reviewed.report, + reviewed.installed, + self.registry.clone(), + bundles, + lifecycle.as_ref(), + grants, + EmulationPolicy::RequireNative, + installed_at, + ) + .await + .map_err(|error| error.to_string()); + if result.is_ok() { + self.bundle_available + .lock() + .unwrap_or_else(|poison| poison.into_inner()) + .retain(|update| update.bundle_id != bundle_id); + } + result + } + + async fn current_bundle_version(&self, bundle_id: &str) -> Result { + let store = self + .bundle_store() + .ok_or_else(|| "plugin bundle mapping is unavailable".to_owned())?; + let lookup = bundle_id.to_owned(); + tokio::task::spawn_blocking(move || store.bundle(&lookup)) + .await + .map_err(|_| "plugin bundle mapping worker failed".to_owned())? + .map_err(|error| error.to_string())? + .map(|bundle| bundle.version) + .ok_or_else(|| "plugin bundle is not installed".to_owned()) + } + + /// Approves a reviewed rollback only after explicit confirmation. The archived versions and + /// mapping are restored together and grants are intersected with the archived manifests. + pub async fn approve_bundle_rollback( + &self, + bundle_id: &str, + version: &str, + confirmed: bool, + ) -> Result { + if !confirmed { + return Err("rollback requires explicit user confirmation".into()); + } + let _activation = self.activations.lock().await; + let lifecycle = self + .lifecycle + .read() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .clone() + .ok_or_else(|| "managed plugin runtime is unavailable".to_owned())?; + lifecycle + .require_active_profile() + .map_err(|error| error.message().to_owned())?; + let bundles = self + .bundle_store() + .ok_or_else(|| "plugin bundle mapping is unavailable".to_owned())?; + let profiles = self + .profiles + .lock() + .unwrap_or_else(|poison| poison.into_inner()) + .clone() + .ok_or_else(|| "plugin profiles are unavailable".to_owned())?; + let mut pending = self.pending_rollbacks.lock().await; + let reviewed = pending + .remove(bundle_id) + .ok_or_else(|| "review the bundle rollback before approving it".to_owned())?; + drop(pending); + if reviewed.version != version + || reviewed.created_at.elapsed() >= std::time::Duration::from_secs(15 * 60) + { + return Err("the reviewed bundle rollback changed; review it again".into()); + } + let archived_at = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_err(|error| error.to_string())? + .as_secs() as i64; + let grants = super::bundles::BundleGrantContext { + layout: self.grant_layout.clone(), + profiles, + }; + super::bundles::rollback_bundle_version( + bundle_id, + version, + self.registry.clone(), + bundles, + lifecycle.as_ref(), + grants, + EmulationPolicy::RequireNative, + archived_at, + ) + .await + .map_err(|error| error.to_string()) + } + + pub async fn decline_bundle_update(&self, bundle_id: &str) { + let candidate = self.pending_bundles.lock().await.remove(bundle_id); + if let Some(candidate) = candidate { + let _ = tokio::task::spawn_blocking(move || drop(candidate)).await; + } + self.pending_rollbacks.lock().await.remove(bundle_id); + } + + /// Reviews an already installed, verified package as an explicit rollback candidate. + pub async fn review_rollback( + &self, + plugin_id: &str, + version: &str, + ) -> Result { + let registry = self.registry.clone(); + let id = plugin_id.to_owned(); + let wanted = version.to_owned(); + let (active, selected) = tokio::task::spawn_blocking(move || { + let active = registry + .active(&id) + .map_err(|error| error.to_string())? + .ok_or_else(|| "plugin is not installed".to_owned())?; + let selected = registry + .versions(&id) + .map_err(|error| error.to_string())? + .into_iter() + .find(|item| item.version == wanted) + .ok_or_else(|| "rollback version is not installed".to_owned())?; + Ok::<_, String>((active, selected)) + }) + .await + .map_err(|_| "plugin registry worker failed".to_owned())??; + if Version::parse(version).map_err(|error| error.to_string())? + >= Version::parse(&active.version).map_err(|error| error.to_string())? + { + return Err("rollback must select a version older than the active version".into()); + } + let current = self + .packages + .inspect_candidate( + &active.package_path, + package_key(&active.package_path)?, + EmulationPolicy::RequireNative, + ) + .await + .map_err(|error| error.to_string())?; + let current_key = decode_publisher_key(¤t.manifest.publisher.public_key)?; + let candidate_key = package_key(&selected.package_path)?; + let candidate = self + .packages + .inspect_candidate( + &selected.package_path, + candidate_key, + EmulationPolicy::RequireNative, + ) + .await + .map_err(|error| error.to_string())?; + if candidate.manifest.id != plugin_id || candidate.manifest.version != version { + return Err("rollback package identity does not match the selected version".into()); + } + // An incompatible target is reviewable (the verdict is shown) but cannot be approved. + super::grants::manifest_permission_requests(&candidate.manifest.permissions) + .map_err(|error| format!("plugin declares unsupported permission scopes: {error}"))?; + let mut review = UpdateReview::compare(¤t.manifest, &candidate.manifest); + review.compatibility_details = Some(candidate.compatibility_review()); + review.publisher_fingerprint = super::publisher_trust::key_fingerprint(&candidate_key); + if !review.is_downgrade { + return Err("selected package is not older than the active version".into()); + } + self.pending.lock().await.insert( + plugin_id.to_owned(), + PendingCandidate { + work: None, + version: version.to_owned(), + installed_version: active.version, + publisher_key: current_key, + candidate_publisher_key: candidate_key, + confirmed_retrust: false, + is_rollback: true, + installed_manifest: current.manifest, + candidate_manifest: candidate.manifest, + review: review.clone(), + }, + ); + Ok(review) + } + + pub async fn approve( + &self, + plugin_id: &str, + version: &str, + target: Option, + ) -> Result { + self.approve_reviewed(plugin_id, version, false, false, target) + .await + } + + /// Activates a rollback only after a separate explicit user confirmation. + pub async fn approve_rollback( + &self, + plugin_id: &str, + version: &str, + confirmed: bool, + target: Option, + ) -> Result { + if !confirmed { + return Err("rollback requires explicit user confirmation".into()); + } + self.approve_reviewed(plugin_id, version, true, true, target) + .await + } + + async fn approve_reviewed( + &self, + plugin_id: &str, + version: &str, + is_rollback: bool, + explicit_downgrade: bool, + target: Option, + ) -> Result { + let _activation = self.activations.lock().await; + let candidate = self + .pending + .lock() + .await + .remove(plugin_id) + .ok_or_else(|| "review the update before approving it".to_owned())?; + if candidate.version != version || candidate.review.plugin_id != plugin_id { + return Err("the reviewed update changed; review it again".into()); + } + if candidate.is_rollback != is_rollback { + return Err("reviewed package does not match the requested action".into()); + } + if candidate + .review + .compatibility_details + .as_ref() + .is_some_and(|details| { + details.state != super::compatibility::CompatibilityState::Compatible + }) + { + return Err("the reviewed package has no compatible target".into()); + } + if candidate.review.extension_targets.is_some() != target.is_some() { + self.pending + .lock() + .await + .insert(plugin_id.to_owned(), candidate); + return Err("extension approval requires a selected game".into()); + } + // Refuse a stale review before installing anything; the activation worker re-checks + // under the publisher lock. + let registry = self.registry.clone(); + let id = plugin_id.to_owned(); + let active = tokio::task::spawn_blocking(move || registry.active(&id)) + .await + .map_err(|_| "plugin registry worker failed".to_owned())? + .map_err(|error| error.to_string())? + .ok_or_else(|| "plugin is no longer installed".to_owned())?; + if active.version != candidate.installed_version { + return Err("the active plugin changed after review; review the update again".into()); + } + // New and rescaled requests never receive a grant from package activation. + if candidate.review.publisher_changed && !candidate.confirmed_retrust { + self.pending + .lock() + .await + .insert(plugin_id.to_owned(), candidate); + return Err("the changed publisher key must be re-trusted separately".into()); + } + + if candidate.is_rollback && (!candidate.review.is_downgrade || !explicit_downgrade) { + return Err("the reviewed package is not a downgrade".into()); + } + let version = self + .activate_selected_candidate(plugin_id, candidate, target) + .await?; + let mut available = self + .available + .lock() + .unwrap_or_else(|poison| poison.into_inner()); + available.retain(|item| item.plugin_id != plugin_id); + let _ = write_available(&self.available_path, &available); + Ok(version) + } + + /// Confirms only the exact publisher key fingerprint shown by the current review. This + /// records the separate user decision in the pending review. The new key is persisted only + /// after the reviewed package passes signature and compatibility checks at activation. + pub async fn confirm_publisher_retrust( + &self, + plugin_id: &str, + version: &str, + confirmed_fingerprint: &str, + ) -> Result<(), String> { + let mut pending = self.pending.lock().await; + let candidate = pending + .get_mut(plugin_id) + .ok_or_else(|| "review the package before re-trusting its publisher".to_owned())?; + if candidate.version != version || !candidate.review.publisher_changed { + return Err("the reviewed package has no publisher-key change".into()); + } + if candidate.review.publisher_fingerprint != confirmed_fingerprint { + return Err("publisher fingerprint does not match the reviewed key".into()); + } + candidate.confirmed_retrust = true; + Ok(()) + } + + async fn activate_selected_candidate( + &self, + plugin_id: &str, + candidate: PendingCandidate, + target: Option, + ) -> Result { + use super::package::PluginKind; + let extension = candidate.installed_manifest.kind == PluginKind::Extension + || candidate.candidate_manifest.kind == PluginKind::Extension; + if extension && candidate.installed_manifest.kind != candidate.candidate_manifest.kind { + return Err("an update cannot change the extension's registration kind".into()); + } + if extension && candidate.review.publisher_changed { + return Err("the extension must be installed and granted access under its new publisher identity".into()); + } + let key = candidate.candidate_publisher_key; + let version = candidate.version.clone(); + let retained = if extension || candidate.work.is_none() { + let registry = self.registry.clone(); + let id = plugin_id.to_owned(); + let wanted = version.clone(); + tokio::task::spawn_blocking(move || { + registry + .versions(&id) + .map(|versions| versions.into_iter().find(|item| item.version == wanted)) + .map_err(|error| error.to_string()) + }) + .await + .map_err(|_| "plugin registry worker failed".to_owned())?? + } else { + None + }; + let installed = match (candidate.work, retained) { + (Some(work), Some(installed)) => { + // A failed readiness check retains the inactive package. Reuse it on retry + // only if it contains the same authenticated payload the user just reviewed. + let root = installed.package_path.clone(); + tokio::task::spawn_blocking(move || { + use gamenode_platform::plugin_packages::verify_package_directory; + let staged = verify_package_directory(&work.path.join("package"), &key) + .map_err(|error| error.to_string())?; + let retained = + verify_package_directory(&root, &key).map_err(|error| error.to_string())?; + if staged.files.0 != retained.files.0 { + return Err( + "an installed version differs from the reviewed package".to_owned() + ); + } + Ok(()) + }) + .await + .map_err(|_| "plugin package worker failed".to_owned())??; + installed + } + (Some(work), None) => self + .packages + .install_candidate( + work.path.join("package"), + key, + EmulationPolicy::RequireNative, + false, + ) + .await + .map_err(|error| error.to_string())?, + (None, Some(installed)) => installed, + (None, None) => return Err("rollback package was removed after review".into()), + }; + let verified = self + .packages + .inspect_candidate(&installed.package_path, key, EmulationPolicy::RequireNative) + .await + .map_err(|error| error.to_string())?; + if verified.manifest.id != plugin_id || verified.manifest.version != version { + return Err("installed package no longer matches the reviewed version".into()); + } + // Network revocation and grant intersection below use the reviewed manifest, so the + // package being activated must declare exactly the permissions the user reviewed. + if verified.manifest.permissions != candidate.candidate_manifest.permissions { + return Err( + "installed package permissions differ from the reviewed package; review again" + .into(), + ); + } + verified + .selected_target() + .map_err(|error| error.to_string())?; + if extension { + let lifecycle = self + .lifecycle + .read() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .clone() + .ok_or_else(|| "extension runtime is unavailable".to_owned())?; + if verified.manifest != candidate.candidate_manifest { + return Err("the extension package changed after review".into()); + } + let mut config = super::runtime::managed_process_config(&installed, &verified, key) + .map_err(|error| error.message().to_owned())?; + config.blocked_capabilities = candidate.review.removed_permissions; + config.blocked_capabilities.extend( + candidate + .review + .permission_changes + .into_iter() + .filter(|change| change.installed_scope != change.candidate_scope) + .map(|change| change.id), + ); + let plugin_id = plugin_id.to_owned(); + let active_version = candidate.installed_version; + tokio::spawn(async move { + lifecycle + .activate_update(plugin_id, active_version, installed, config, target) + .await + }) + .await + .map_err(|_| "extension update task failed".to_owned())? + .map_err(|error| error.message().to_owned())?; + return Ok(version); + } + + let registry = self.registry.clone(); + let trust_dir = self.trust_dir.clone(); + let changed_key = candidate.review.publisher_changed; + let previous_version = candidate.installed_version; + let previous_key = candidate.publisher_key; + let fingerprint = candidate.review.publisher_fingerprint; + let profiles = self + .profiles + .lock() + .unwrap_or_else(|poison| poison.into_inner()) + .clone(); + let profile = profiles.as_ref().and_then(|profiles| profiles.current()); + let layout = self.grant_layout.clone(); + let installed_id = plugin_id.to_owned(); + let publisher = super::publisher_trust::key_fingerprint(&candidate.publisher_key); + let selected_publisher = super::publisher_trust::key_fingerprint(&key); + let previous = candidate.installed_manifest; + let selected = candidate.candidate_manifest; + fn network_scope(manifest: &Manifest) -> Option<&str> { + manifest + .permissions + .iter() + .find(|permission| { + permission.id == gamenode_plugin_protocol::capability::NETWORK_FETCH + }) + .map(|permission| permission.scope.as_str()) + } + tokio::task::spawn_blocking(move || { + let _publisher = super::managed_packages::lock_publisher_identity(); + let active = registry + .active(&installed_id) + .map_err(|error| error.to_string())? + .ok_or_else(|| "plugin is no longer installed".to_owned())?; + if active.version != previous_version || package_key(&active.package_path)? != previous_key { + return Err("the active plugin changed during approval; review again".into()); + } + let mut trust = super::publisher_trust::PublisherTrustStore::open(trust_dir) + .map_err(|error| error.to_string())?; + if !trust.is_pinned(&installed_id, &previous_key).map_err(|error| error.to_string())? { + return Err("the installed package publisher key is no longer trusted; review again".into()); + } + + let changed_network = network_scope(&previous) != network_scope(&selected); + if changed_network || changed_key { + layout + .revoke_network_for_package(&installed_id, &publisher) + .map_err(|error| error.to_string())?; + } + if changed_key { + layout + .revoke_network_for_package(&installed_id, &selected_publisher) + .map_err(|error| error.to_string())?; + } + if (changed_network || changed_key) + && let Some(profiles) = &profiles + { + profiles.notify_permissions_changed(); + } + if let (Some(profiles), Some(profile)) = (profiles, profile) { + let identity = PluginIdentity { + plugin_id: installed_id.clone(), + publisher_fingerprint: publisher, + profile_id: profile.profile_id().to_owned(), + }; + let mut grants = layout + .open_grants(&profile) + .map_err(|error| error.to_string())?; + let before = grants.revision(&identity); + let after = grants + .intersect_with_selected_manifest(&identity, &previous, &selected) + .map_err(|error| error.to_string())?; + if after != before { + profiles.notify_permissions_changed(); + } + } + registry + .set_active(&installed_id, &version) + .map_err(|error| error.to_string())?; + if changed_key + && let Err(trust_error) = trust.retrust_key(&installed_id, &key, &fingerprint) + { + registry + .set_active(&installed_id, &previous_version) + .map_err(|rollback_error| { + format!( + "publisher re-trust failed ({trust_error}); restoring the prior package also failed ({rollback_error})" + ) + })?; + return Err(trust_error.to_string()); + } + Ok(version) + }) + .await + .map_err(|_| "plugin activation worker failed".to_owned())? + } + + #[cfg(all(test, target_os = "linux"))] + pub(super) async fn stage_extension_update_for_test( + &self, + previous: &InstalledPluginVersion, + candidate: &Path, + ) { + let work = UpdateWorkDir::create().unwrap(); + let package = work.path.join("package"); + fs::create_dir(&package).unwrap(); + for entry in fs::read_dir(candidate).unwrap() { + let entry = entry.unwrap(); + fs::copy(entry.path(), package.join(entry.file_name())).unwrap(); + } + let read = |root: &Path| { + Manifest::parse_json(&fs::read(root.join("plugin.json")).unwrap()) + .unwrap() + .manifest() + .clone() + }; + let installed_manifest = read(&previous.package_path); + let candidate_manifest = read(&package); + let review = UpdateReview::compare(&installed_manifest, &candidate_manifest); + self.pending.lock().await.insert( + previous.plugin_id.clone(), + PendingCandidate { + work: Some(work), + version: candidate_manifest.version.clone(), + installed_version: previous.version.clone(), + publisher_key: package_key(&previous.package_path).unwrap(), + candidate_publisher_key: package_key(&package).unwrap(), + confirmed_retrust: false, + is_rollback: false, + installed_manifest, + candidate_manifest, + review, + }, + ); + } + + pub async fn decline(&self, plugin_id: &str) { + let candidate = self.pending.lock().await.remove(plugin_id); + if let Some(candidate) = candidate { + let _ = tokio::task::spawn_blocking(move || drop(candidate)).await; + } + } +} + +pub(crate) fn package_key(path: &Path) -> Result<[u8; 32], String> { + let manifest_path = path.join("plugin.json"); + let metadata = fs::symlink_metadata(&manifest_path).map_err(|error| error.to_string())?; + if !metadata.is_file() || metadata.file_type().is_symlink() || metadata.len() > 4 * 1024 * 1024 + { + return Err("plugin manifest is not a bounded regular file".into()); + } + let bytes = fs::read(manifest_path).map_err(|error| error.to_string())?; + let manifest = Manifest::parse_json(&bytes).map_err(|error| error.to_string())?; + decode_publisher_key(&manifest.manifest().publisher.public_key) +} + +fn package_archive_key(path: &Path) -> Result<[u8; 32], String> { + use std::io::Read as _; + let metadata = fs::symlink_metadata(path).map_err(|error| error.to_string())?; + if !metadata.is_file() + || metadata.file_type().is_symlink() + || metadata.len() > gamenode_platform::plugin_packages::MAX_COMPRESSED_BYTES + { + return Err("selected plugin archive is not a bounded regular file".into()); + } + let mut archive = + zip::ZipArchive::new(fs::File::open(path).map_err(|error| error.to_string())?) + .map_err(|error| error.to_string())?; + if archive.len() > gamenode_platform::plugin_packages::MAX_ENTRIES { + return Err("plugin archive contains too many entries".into()); + } + let manifest_file = archive + .by_name("plugin.json") + .map_err(|error| error.to_string())?; + if manifest_file.size() > 4 * 1024 * 1024 { + return Err("plugin manifest exceeds the metadata size limit".into()); + } + let mut bytes = Vec::with_capacity(manifest_file.size() as usize); + manifest_file + .take(4 * 1024 * 1024 + 1) + .read_to_end(&mut bytes) + .map_err(|error| error.to_string())?; + if bytes.len() > 4 * 1024 * 1024 { + return Err("plugin manifest exceeds the metadata size limit".into()); + } + let manifest = Manifest::parse_json(&bytes).map_err(|error| error.to_string())?; + decode_publisher_key(&manifest.manifest().publisher.public_key) +} + +fn decode_publisher_key(encoded: &str) -> Result<[u8; 32], String> { + use base64::Engine as _; + base64::engine::general_purpose::STANDARD + .decode(encoded) + .map_err(|error| error.to_string())? + .try_into() + .map_err(|_| "publisher public key must contain 32 bytes".to_owned()) +} + +fn read_preferences(path: &Path) -> Result { + match fs::read(path) { + Ok(bytes) => serde_json::from_slice(&bytes).map_err(|error| error.to_string()), + Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(PluginUpdatePreferences { + periodic_checks: false, + }), + Err(error) => Err(error.to_string()), + } +} + +fn read_available(path: &Path) -> Result, String> { + match fs::read(path) { + Ok(bytes) => serde_json::from_slice(&bytes).map_err(|error| error.to_string()), + Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(Vec::new()), + Err(error) => Err(error.to_string()), + } +} + +fn write_preferences(path: &Path, preferences: &PluginUpdatePreferences) -> Result<(), String> { + let bytes = serde_json::to_vec(preferences).map_err(|error| error.to_string())?; + let parent = path + .parent() + .ok_or_else(|| "update preferences path is invalid".to_owned())?; + fs::create_dir_all(parent).map_err(|error| error.to_string())?; + let temp = parent.join("plugin-update-preferences.json.tmp"); + fs::write(&temp, bytes).map_err(|error| error.to_string())?; + fs::rename(temp, path).map_err(|error| error.to_string()) +} + +fn write_available(path: &Path, available: &[AvailablePluginUpdate]) -> Result<(), String> { + let bytes = serde_json::to_vec(available).map_err(|error| error.to_string())?; + let parent = path + .parent() + .ok_or_else(|| "update cache path is invalid".to_owned())?; + fs::create_dir_all(parent).map_err(|error| error.to_string())?; + let temp = parent.join("plugin-updates-cache.json.tmp"); + fs::write(&temp, bytes).map_err(|error| error.to_string())?; + fs::rename(temp, path).map_err(|error| error.to_string()) +} + +#[cfg(test)] +mod review_tests { + use super::*; + use crate::plugin_host::package::{ + ApiRange, LicenseNotice, Manifest, PermissionRequest, PlaytimeCapabilities, PluginKind, + Publisher, Target, + }; + + fn manifest( + version: &str, + scope: &str, + native: &[&str], + license: &str, + api_max: &str, + ) -> Manifest { + Manifest { + schema: 1, + id: "org.example.plugin".into(), + kind: PluginKind::Extension, + provider_id: None, + name: "Example".into(), + version: version.into(), + api: ApiRange { + min: "1.0.0".into(), + max: api_max.into(), + }, + permissions: vec![PermissionRequest { + id: "files.read".into(), + required: false, + scope: scope.into(), + reason: "Read selected files".into(), + impact_if_disabled: None, + }], + playtime: PlaytimeCapabilities::default(), + native_access: native.iter().map(|value| (*value).to_owned()).collect(), + supported_platforms: vec![], + targets: vec![Target { + os: "linux".into(), + arch: "x86_64".into(), + abi: "gnu".into(), + entrypoint: "plugin.bin".into(), + requires: None, + tested_on: vec![], + }], + publisher: Publisher { + key_id: "key-1".into(), + public_key: "key-bytes".into(), + }, + license: LicenseNotice { + expression: license.into(), + files: vec![], + notices: vec![], + }, + source_url: None, + update_url: None, + configuration: Default::default(), + resources: BTreeMap::new(), + schemas: vec![], + } + } + + #[test] + fn review_reports_scope_native_license_api_and_publisher_changes_without_granting() { + let before = manifest("1.0.0", "game:data", &[], "MIT", "1.4.0"); + let mut after = manifest("1.1.0", "all:data", &["process"], "GPL-3.0-only", "2.0.0"); + after.permissions.push(PermissionRequest { + id: "network.fetch".into(), + required: true, + scope: "https://example.org".into(), + reason: "Fetch metadata".into(), + impact_if_disabled: None, + }); + after.publisher.key_id = "key-2".into(); + after.publisher.public_key = "different-key".into(); + let review = UpdateReview::compare(&before, &after); + assert_eq!(review.added_permissions, ["network.fetch"]); + assert_eq!(review.changed_permissions, ["files.read"]); + assert_eq!(review.added_native_access, ["process"]); + assert!(review.api_changed && review.license_changed && review.publisher_changed); + assert!(review.requires_manual_approval); + } + + #[test] + fn review_discloses_signed_playtime_policy_changes() { + let before = manifest("1.0.0", "game:data", &[], "MIT", "1.4.0"); + let mut after = manifest("1.1.0", "game:data", &[], "MIT", "1.4.0"); + after.playtime = PlaytimeCapabilities { + identifies_gameplay: true, + identifies_pauses: false, + without_pause_detection: super::super::package::PlaytimeAccountingMode::ApplicationOpen, + }; + + let review = UpdateReview::compare(&before, &after); + assert!(review.playtime_changed); + assert_eq!(review.installed_playtime, before.playtime); + assert_eq!(review.candidate_playtime, after.playtime); + assert!(review.requires_manual_approval); + } + + #[test] + fn even_metadata_only_updates_still_require_explicit_approval() { + let before = manifest("1.0.0", "game:data", &[], "MIT", "1.4.0"); + let after = manifest("1.1.0", "game:data", &[], "MIT", "1.4.0"); + let review = UpdateReview::compare(&before, &after); + assert!(review.requires_manual_approval); + assert!(review.added_permissions.is_empty()); + assert!(review.added_native_access.is_empty()); + } + + #[test] + fn periodic_opt_in_persists_and_defaults_off() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("plugin-update-preferences.json"); + assert!(!read_preferences(&path).unwrap().periodic_checks); + let enabled = PluginUpdatePreferences { + periodic_checks: true, + }; + write_preferences(&path, &enabled).unwrap(); + assert_eq!(read_preferences(&path).unwrap(), enabled); + } + + #[test] + fn available_update_cache_survives_service_restart() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("plugin-updates-cache.json"); + let cache = vec![AvailablePluginUpdate { + plugin_id: "org.example.plugin".into(), + name: "Example".into(), + installed_version: "1.0.0".into(), + versions: vec!["1.1.0".into()], + }]; + write_available(&path, &cache).unwrap(); + assert_eq!(read_available(&path).unwrap(), cache); + } + + #[test] + fn import_decision_inputs_use_camel_case_fields_and_omit_absent_impact() { + let permission = ImportPermissionReview { + id: "network.fetch".into(), + required: false, + scope: "https://api.example.com".into(), + reason: "Fetch metadata".into(), + impact_if_disabled: Some("Metadata stays unavailable".into()), + }; + let value = serde_json::to_value(&permission).unwrap(); + assert_eq!(value["impactIfDisabled"], "Metadata stays unavailable"); + let absent = ImportPermissionReview { + impact_if_disabled: None, + ..permission + }; + assert!( + serde_json::to_value(&absent) + .unwrap() + .get("impactIfDisabled") + .is_none() + ); + + let denial = BundleComponentDeniedPermissions { + plugin_id: "org.example.plugin".into(), + denied_permission_ids: vec!["network.fetch".into()], + }; + let value = serde_json::to_value(&denial).unwrap(); + assert_eq!(value["pluginId"], "org.example.plugin"); + assert_eq!(value["deniedPermissionIds"][0], "network.fetch"); + let parsed: BundleComponentDeniedPermissions = serde_json::from_value(value).unwrap(); + assert_eq!(parsed, denial); + } +} + +/// One host-approved release and the verified sources needed to install it. +pub struct ApprovedRelease<'a, F> { + pub verifier: &'a UpdateIndexVerifier, + pub client: &'a FetchClient, + pub index: &'a VerifiedUpdateIndex, + pub version: &'a str, + pub publisher_key: [u8; 32], + pub emulation_policy: EmulationPolicy, + pub allowed_origin: F, +} + +/// Coordinates feed checks and update installs for one managed package registry. +#[derive(Clone)] +pub struct ManagedPluginUpdater { + registry: PluginPackageRegistry, + packages: ManagedPackageLifecycle, +} + +impl ManagedPluginUpdater { + pub fn new(registry: PluginPackageRegistry) -> Self { + Self { + packages: ManagedPackageLifecycle::new(registry.clone()), + registry, + } + } + + /// Check an update feed without changing the active plugin version. The caller should invoke + /// this only for an opted-in/manual check and display the returned releases for review. + pub async fn check_feed( + &self, + verifier: &UpdateIndexVerifier, + client: &FetchClient, + plugin_id: &str, + feed_url: &str, + publisher_key: [u8; 32], + allowed_origin: impl Fn(&str) -> bool + Send + Sync, + ) -> Result { + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_err(|error| ManagedUpdateError::Staging(error.to_string()))? + .as_secs(); + let verified = verifier + .check_feed(client, feed_url, &publisher_key, now, allowed_origin) + .await?; + if verified.index().plugin_id != plugin_id { + return Err(ManagedUpdateError::PluginIdentityMismatch); + } + Ok(verified) + } + + async fn stage_review_candidate( + &self, + index: &VerifiedUpdateIndex, + release: &UpdateRelease, + archive: Vec, + _publisher_key: [u8; 32], + ) -> Result< + ( + UpdateWorkDir, + super::managed_packages::PackageCandidateReport, + [u8; 32], + ), + ManagedUpdateError, + > { + if !index + .index() + .releases + .iter() + .any(|candidate| candidate == release) + || archive.len() as u64 != release.package_size + || format!("{:x}", sha2::Sha256::digest(&archive)) != release.package_sha256 + { + return Err(ManagedUpdateError::Feed(UpdateError::InvalidPackage)); + } + let work = UpdateWorkDir::create() + .map_err(|error| ManagedUpdateError::Staging(error.to_string()))?; + let archive_path = work.path.join("release.zip"); + let package_path = work.path.join("package"); + let archive_for_worker = archive_path.clone(); + let package_for_worker = package_path.clone(); + tokio::task::spawn_blocking(move || -> Result<(), ManagedUpdateError> { + fs::write(&archive_for_worker, archive) + .map_err(|error| ManagedUpdateError::Staging(error.to_string()))?; + gamenode_platform::plugin_packages::stage_package_archive_from_verified_feed( + &archive_for_worker, + &package_for_worker, + ) + .map_err(|error| ManagedUpdateError::Staging(error.to_string()))?; + Ok(()) + }) + .await + .map_err(|_| ManagedUpdateError::WorkerFailed)??; + let candidate_key = package_key(&package_path).map_err(ManagedUpdateError::Staging)?; + let report = self + .packages + .inspect_candidate(&package_path, candidate_key, EmulationPolicy::RequireNative) + .await?; + if report.manifest.id != index.index().plugin_id + || report.manifest.version != release.version + { + return Err(ManagedUpdateError::PackageIdentityMismatch); + } + Ok((work, report, candidate_key)) + } + + /// Download and install one release after caller approval. The index and package are both + /// validated before the registry can change its active pointer. Any fetch, extraction, + /// compatibility or signature failure leaves the old pointer intact. + pub async fn apply_approved_release( + &self, + release: ApprovedRelease<'_, F>, + ) -> Result + where + F: Fn(&str) -> bool + Send + Sync, + { + let ApprovedRelease { + verifier, + client, + index, + version, + publisher_key, + emulation_policy, + allowed_origin, + } = release; + let index = index.index(); + let release = index + .releases + .iter() + .find(|release| release.version == version) + .cloned() + .ok_or(ManagedUpdateError::ReleaseNotFound)?; + let lookup_id = index.plugin_id.clone(); + let registry = self.registry.clone(); + let active = tokio::task::spawn_blocking(move || { + registry + .active(&lookup_id) + .map_err(|error| ManagedUpdateError::Staging(error.to_string())) + }) + .await + .map_err(|_| ManagedUpdateError::WorkerFailed)?? + .ok_or(ManagedUpdateError::NoActiveVersion)?; + if active.plugin_id != index.plugin_id { + return Err(ManagedUpdateError::PluginIdentityMismatch); + } + let current = Version::parse(&active.version) + .map_err(|error| ManagedUpdateError::Staging(error.to_string()))?; + let candidate = Version::parse(&release.version) + .map_err(|error| ManagedUpdateError::Staging(error.to_string()))?; + if candidate <= current { + return Err(ManagedUpdateError::Downgrade); + } + + let archive = verifier + .download_release(client, &release, allowed_origin) + .await?; + self.install_verified_archive(index, &release, archive, publisher_key, emulation_policy) + .await + } + + async fn install_verified_archive( + &self, + index: &UpdateIndex, + release: &UpdateRelease, + archive: Vec, + publisher_key: [u8; 32], + emulation_policy: EmulationPolicy, + ) -> Result { + if !index.releases.iter().any(|candidate| candidate == release) + || archive.len() as u64 != release.package_size + || format!("{:x}", sha2::Sha256::digest(&archive)) != release.package_sha256 + { + return Err(ManagedUpdateError::Feed(UpdateError::InvalidPackage)); + } + let lookup_id = index.plugin_id.clone(); + let registry = self.registry.clone(); + let active = tokio::task::spawn_blocking(move || { + registry + .active(&lookup_id) + .map_err(|error| ManagedUpdateError::Staging(error.to_string())) + }) + .await + .map_err(|_| ManagedUpdateError::WorkerFailed)?? + .ok_or(ManagedUpdateError::NoActiveVersion)?; + let current = Version::parse(&active.version) + .map_err(|error| ManagedUpdateError::Staging(error.to_string()))?; + let candidate = Version::parse(&release.version) + .map_err(|error| ManagedUpdateError::Staging(error.to_string()))?; + if candidate <= current { + return Err(ManagedUpdateError::Downgrade); + } + + let work = UpdateWorkDir::create() + .map_err(|error| ManagedUpdateError::Staging(error.to_string()))?; + let archive_path = work.path.join("release.zip"); + let package_path = work.path.join("package"); + let archive_for_worker = archive_path.clone(); + let package_for_worker = package_path.clone(); + tokio::task::spawn_blocking(move || -> Result<(), ManagedUpdateError> { + fs::write(&archive_for_worker, archive) + .map_err(|error| ManagedUpdateError::Staging(error.to_string()))?; + stage_package_archive(&archive_for_worker, &package_for_worker, &publisher_key) + .map_err(|error| ManagedUpdateError::Staging(error.to_string()))?; + Ok(()) + }) + .await + .map_err(|_| ManagedUpdateError::WorkerFailed)??; + + let report = self + .packages + .inspect_candidate(&package_path, publisher_key, emulation_policy) + .await?; + if report.manifest.id != index.plugin_id || report.manifest.version != release.version { + return Err(ManagedUpdateError::PackageIdentityMismatch); + } + report.selected_target()?; + self.packages + .install_candidate(&package_path, publisher_key, emulation_policy, true) + .await + .map_err(ManagedUpdateError::from) + } +} + +struct UpdateWorkDir { + path: PathBuf, +} + +impl UpdateWorkDir { + fn create() -> io::Result { + for _ in 0..8 { + let mut nonce = [0u8; 16]; + getrandom::fill(&mut nonce).map_err(io::Error::other)?; + let name = nonce + .iter() + .map(|byte| format!("{byte:02x}")) + .collect::(); + let path = std::env::temp_dir().join(format!("gamenode-plugin-update-{name}")); + match fs::create_dir(&path) { + Ok(()) => { + restrict_private(&path)?; + return Ok(Self { path }); + } + Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue, + Err(error) => return Err(error), + } + } + Err(io::Error::new( + io::ErrorKind::AlreadyExists, + "could not reserve update staging", + )) + } +} + +impl Drop for UpdateWorkDir { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.path); + } +} + +#[cfg(unix)] +fn restrict_private(path: &Path) -> io::Result<()> { + use std::os::unix::fs::PermissionsExt; + fs::set_permissions(path, fs::Permissions::from_mode(0o700)) +} + +#[cfg(not(unix))] +fn restrict_private(_: &Path) -> io::Result<()> { + Ok(()) +} + +#[cfg(all(test, target_os = "linux"))] +pub(super) mod tests { + use super::*; + use base64::Engine as _; + use gamenode_platform::{ + plugin_packages::SIGNATURE_DOMAIN_PREFIX, + plugin_updates::{INDEX_SIGNATURE_DOMAIN, UpdateRelease}, + }; + use ring::signature::KeyPair; + use std::{ + collections::{BTreeMap, BTreeSet}, + io::Write, + }; + use zip::{ZipWriter, write::SimpleFileOptions}; + + #[test] + fn offline_license_reader_is_bounded_utf8_and_package_relative() { + let temp = tempfile::tempdir().unwrap(); + fs::create_dir_all(temp.path().join("licenses")).unwrap(); + fs::write(temp.path().join("licenses/LICENSE"), "MIT notice").unwrap(); + assert_eq!( + read_inert_license(temp.path(), "licenses/LICENSE").unwrap(), + "MIT notice" + ); + assert!(read_inert_license(temp.path(), "../outside").is_err()); + assert!(read_inert_license(temp.path(), "licenses/missing").is_err()); + fs::write(temp.path().join("licenses/binary"), [0xff, 0xfe]).unwrap(); + assert!(read_inert_license(temp.path(), "licenses/binary").is_err()); + fs::write( + temp.path().join("licenses/large"), + vec![b'x'; 256 * 1024 + 1], + ) + .unwrap(); + assert!(read_inert_license(temp.path(), "licenses/large").is_err()); + } + + #[tokio::test] + async fn import_review_returns_playtime_capabilities_from_the_signed_manifest() { + let base = tempfile::tempdir().unwrap(); + let paths = gamenode_platform::paths::DataPaths::at(base.path().join("app")); + let service = import_service(&paths); + let key = ring::signature::Ed25519KeyPair::from_seed_unchecked(&[43; 32]).unwrap(); + let package = base.path().join("playtime-disclosure"); + signed_package_with_playtime( + &package, + "1.0.0", + &key, + serde_json::json!({ + "identifies_gameplay": true, + "identifies_pauses": false, + "without_pause_detection": "application_open" + }), + ); + + let review = service + .import_review(archive_package(&package)) + .await + .unwrap(); + assert_eq!( + review.package.playtime, + PlaytimeCapabilities { + identifies_gameplay: true, + identifies_pauses: false, + without_pause_detection: + super::super::package::PlaytimeAccountingMode::ApplicationOpen, + } + ); + let serialized = serde_json::to_value(&review.package).unwrap(); + assert_eq!( + serialized["playtime"], + serde_json::json!({ + "identifiesGameplay": true, + "identifiesPauses": false, + "withoutPauseDetection": "application_open" + }) + ); + } + + fn signed_package(root: &Path, version: &str, key: &ring::signature::Ed25519KeyPair) { + signed_package_with_permissions( + root, + version, + key, + vec![serde_json::json!({ + "id": "storage.persist", "required": false, "scope": "own-provider", + "reason": "Store plugin preferences" + })], + ); + } + + /// A package that discloses content platforms and what each permission loses when disabled. + fn disclosure_permissions() -> Vec { + vec![ + serde_json::json!({ + "id": "storage.persist", "required": true, "scope": "own-provider", + "reason": "Store plugin preferences", + "impact_if_disabled": "Preferences are lost between sessions" + }), + serde_json::json!({ + "id": "network.fetch", "required": false, "scope": "https://api.example.com", + "reason": "Fetch remote metadata", + "impact_if_disabled": "Remote artwork and metadata stay unavailable" + }), + ] + } + + #[tokio::test] + async fn import_review_exposes_content_platforms_and_permission_impact() { + let base = tempfile::tempdir().unwrap(); + let paths = gamenode_platform::paths::DataPaths::at(base.path().join("app")); + let service = import_service(&paths); + let key = ring::signature::Ed25519KeyPair::from_seed_unchecked(&[44; 32]).unwrap(); + let package = base.path().join("disclosures"); + let mut manifest = fixture_manifest("1.0.0", disclosure_permissions()); + manifest["supported_platforms"] = serde_json::json!(["gamecube", "wii"]); + signed_package_from_manifest(&package, &key, &manifest); + + let review = service + .import_review(archive_package(&package)) + .await + .unwrap(); + assert_eq!(review.package.supported_platforms, ["gamecube", "wii"]); + assert_eq!( + review.package.requested_permissions[0] + .impact_if_disabled + .as_deref(), + Some("Preferences are lost between sessions") + ); + assert_eq!( + review.package.requested_permissions[1] + .impact_if_disabled + .as_deref(), + Some("Remote artwork and metadata stay unavailable") + ); + // The command surface keeps camelCase field names for the Tauri IPC boundary. + let serialized = serde_json::to_value(&review.package).unwrap(); + assert_eq!( + serialized["supportedPlatforms"], + serde_json::json!(["gamecube", "wii"]) + ); + assert_eq!( + serialized["requestedPermissions"][0]["impactIfDisabled"], + "Preferences are lost between sessions" + ); + } + + #[tokio::test] + async fn import_install_grants_reviewed_permissions_except_denied_optionals() { + use crate::plugin_host::grants::PermissionState; + + let base = tempfile::tempdir().unwrap(); + let paths = gamenode_platform::paths::DataPaths::at(base.path().join("app")); + let service = import_service(&paths); + let key = ring::signature::Ed25519KeyPair::from_seed_unchecked(&[45; 32]).unwrap(); + let package = base.path().join("reviewed-decisions"); + signed_package_from_manifest( + &package, + &key, + &fixture_manifest("1.0.0", disclosure_permissions()), + ); + let imported = import_review_and_pin(&service, &package).await; + + let plugin_id = service + .import_install(&imported.token, false, &["network.fetch".to_owned()]) + .await + .unwrap(); + assert_eq!(plugin_id.plugin_id, "org.example.update"); + + let lifecycle = service + .lifecycle + .read() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .clone() + .unwrap(); + let snapshot = lifecycle + .installed_permission_snapshot( + plugin_id.plugin_id.clone(), + imported.package.publisher_fingerprint.clone(), + ) + .await + .unwrap(); + assert!(snapshot.grant_revision > 0); + let state = |permission_id: &str| { + snapshot + .effective_grants + .iter() + .find(|grant| grant.permission_id == permission_id) + .map(|grant| grant.state.clone()) + }; + assert_eq!(state("storage.persist"), Some(PermissionState::Granted)); + assert_eq!(state("network.fetch"), Some(PermissionState::Denied)); + } + + #[tokio::test] + async fn import_install_rejects_required_and_unknown_denials_before_installing() { + let base = tempfile::tempdir().unwrap(); + let paths = gamenode_platform::paths::DataPaths::at(base.path().join("app")); + let service = import_service(&paths); + let key = ring::signature::Ed25519KeyPair::from_seed_unchecked(&[46; 32]).unwrap(); + let package = base.path().join("rejected-decisions"); + signed_package_from_manifest( + &package, + &key, + &fixture_manifest("1.0.0", disclosure_permissions()), + ); + let imported = import_review_and_pin(&service, &package).await; + for (denied, message) in [ + (vec!["storage.persist".to_owned()], "required permission"), + (vec!["files.read".to_owned()], "not requested"), + ( + vec!["network.fetch".to_owned(), "network.fetch".to_owned()], + "more than once", + ), + ] { + let error = service + .import_install(&imported.token, false, &denied) + .await + .unwrap_err(); + assert!(error.contains(message), "{error}"); + assert!( + service + .registry + .active("org.example.update") + .unwrap() + .is_none(), + "a rejected denial must not install anything" + ); + } + + // The same reviewed token still installs when the decisions are valid. + assert_eq!( + service + .import_install(&imported.token, false, &[]) + .await + .unwrap() + .plugin_id, + "org.example.update" + ); + assert!( + service + .registry + .active("org.example.update") + .unwrap() + .is_some() + ); + } + + pub(in crate::plugin_host) fn signed_package_with_permissions( + root: &Path, + version: &str, + key: &ring::signature::Ed25519KeyPair, + permissions: Vec, + ) { + signed_package_with_permissions_and_playtime(root, version, key, permissions, None); + } + + fn signed_package_with_playtime( + root: &Path, + version: &str, + key: &ring::signature::Ed25519KeyPair, + playtime: serde_json::Value, + ) { + signed_package_with_permissions_and_playtime( + root, + version, + key, + vec![serde_json::json!({ + "id": "storage.persist", "required": false, "scope": "own-provider", + "reason": "Store plugin preferences" + })], + Some(playtime), + ); + } + + fn signed_package_with_permissions_and_playtime( + root: &Path, + version: &str, + key: &ring::signature::Ed25519KeyPair, + permissions: Vec, + playtime: Option, + ) { + let mut manifest_value = fixture_manifest(version, permissions); + if let Some(playtime) = playtime { + manifest_value["playtime"] = playtime; + } + signed_package_from_manifest(root, key, &manifest_value); + } + + fn fixture_manifest(version: &str, permissions: Vec) -> serde_json::Value { + serde_json::json!({ + "schema": 1, + "id": "org.example.update", + "kind": "provider", + "provider_id": "update-fixture", + "name": "Update Fixture", + "version": version, + "api": {"min": "1.6.0", "max": "1.6.0"}, + "permissions": permissions, + "targets": [{"os": "linux", "arch": "x86_64", "abi": "gnu", "entrypoint": "bin/plugin"}], + "publisher": { + "key_id": "fixture-key", + "public_key": "" + }, + "license": {"expression": "MIT", "files": ["licenses/LICENSE"]} + }) + } + + fn extension_fixture_manifest(version: &str) -> serde_json::Value { + serde_json::json!({ + "schema": 1, + "id": "org.example.launch", + "kind": "extension", + "name": "Launch Fixture", + "version": version, + "api": {"min": "1.6.0", "max": "1.6.0"}, + "permissions": [{ + "id": "game.launch", "required": true, "scope": "selected game", + "reason": "Start the selected game" + }], + "targets": [{"os": "linux", "arch": "x86_64", "abi": "gnu", "entrypoint": "bin/plugin"}], + "publisher": { + "key_id": "fixture-key", + "public_key": "" + }, + "license": {"expression": "MIT", "files": ["licenses/LICENSE"]} + }) + } + + fn signed_package_from_manifest( + root: &Path, + key: &ring::signature::Ed25519KeyPair, + manifest_value: &serde_json::Value, + ) { + fs::create_dir_all(root.join("bin")).unwrap(); + fs::create_dir_all(root.join("licenses")).unwrap(); + fs::write(root.join("bin/plugin"), b"fixture executable").unwrap(); + fs::write(root.join("licenses/LICENSE"), b"fixture license").unwrap(); + let mut manifest_value = manifest_value.clone(); + manifest_value["publisher"]["public_key"] = serde_json::Value::String( + base64::engine::general_purpose::STANDARD.encode(key.public_key().as_ref()), + ); + let manifest = serde_json::to_vec(&manifest_value).unwrap(); + fs::write(root.join("plugin.json"), &manifest).unwrap(); + let files = [ + ("plugin.json", manifest.as_slice()), + ("bin/plugin", b"fixture executable".as_slice()), + ("licenses/LICENSE", b"fixture license".as_slice()), + ] + .into_iter() + .map(|(path, bytes)| { + ( + path.to_owned(), + format!("{:x}", sha2::Sha256::digest(bytes)), + ) + }) + .collect::>(); + let integrity = + serde_json::to_vec(&serde_json::json!({"schema": 1, "files": files})).unwrap(); + let mut signed = SIGNATURE_DOMAIN_PREFIX.to_vec(); + signed.extend_from_slice(&integrity); + fs::write(root.join("integrity.json"), integrity).unwrap(); + fs::write(root.join("signature.ed25519"), key.sign(&signed).as_ref()).unwrap(); + } + + /// Stages the real example `package/` tree as a signed fixture. The source tree contains no + /// built executable, so every target entrypoint the manifest declares is filled with inert + /// fixture bytes. Everything else — the manifest, license, notices and payload helpers — is + /// copied exactly as the pack tool would ship it. + fn signed_example_package(root: &Path, example: &str, key: &ring::signature::Ed25519KeyPair) { + fn collect(base: &Path, current: &Path, files: &mut BTreeMap>) { + for entry in fs::read_dir(current).unwrap() { + let path = entry.unwrap().path(); + if path.is_dir() { + collect(base, &path, files); + continue; + } + let relative = path + .strip_prefix(base) + .unwrap() + .to_string_lossy() + .replace('\\', "/"); + if relative == "plugin.json" { + continue; + } + files.insert(relative, fs::read(&path).unwrap()); + } + } + + let workspace = Path::new(env!("CARGO_MANIFEST_DIR")).join("../.."); + let source = workspace + .join("examples/plugins") + .join(example) + .join("package"); + let mut manifest: serde_json::Value = + serde_json::from_slice(&fs::read(source.join("plugin.json")).unwrap()).unwrap(); + manifest["publisher"]["public_key"] = serde_json::Value::String( + base64::engine::general_purpose::STANDARD.encode(key.public_key().as_ref()), + ); + let manifest = serde_json::to_vec_pretty(&manifest).unwrap(); + let mut files = BTreeMap::new(); + collect(&source, &source, &mut files); + for target in manifest_targets(&manifest) { + files.insert( + target, + b"fixture executable; never run in import test".to_vec(), + ); + } + files.insert("plugin.json".to_owned(), manifest); + + for (relative, bytes) in &files { + let path = root.join(relative); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, bytes).unwrap(); + } + let integrity = serde_json::to_vec(&serde_json::json!({ + "schema": 1, + "files": files + .iter() + .map(|(path, bytes)| (path.clone(), format!("{:x}", sha2::Sha256::digest(bytes)))) + .collect::>() + })) + .unwrap(); + let mut signed = SIGNATURE_DOMAIN_PREFIX.to_vec(); + signed.extend_from_slice(&integrity); + fs::write(root.join("integrity.json"), integrity).unwrap(); + fs::write(root.join("signature.ed25519"), key.sign(&signed).as_ref()).unwrap(); + } + + /// The entrypoints a manifest declares, read from the JSON before the typed parser runs so a + /// malformed manifest fails in the importer rather than in this fixture. + fn manifest_targets(manifest: &[u8]) -> Vec { + let value: serde_json::Value = serde_json::from_slice(manifest).unwrap(); + value["targets"] + .as_array() + .into_iter() + .flatten() + .filter_map(|target| target["entrypoint"].as_str().map(str::to_owned)) + .collect() + } + + pub(in crate::plugin_host) fn add_tree( + zip: &mut ZipWriter, + base: &Path, + current: &Path, + ) { + for entry in fs::read_dir(current).unwrap() { + let entry = entry.unwrap(); + let path = entry.path(); + if path.is_dir() { + add_tree(zip, base, &path); + } else { + let name = path + .strip_prefix(base) + .unwrap() + .to_string_lossy() + .replace('\\', "/"); + zip.start_file(name, SimpleFileOptions::default()).unwrap(); + zip.write_all(&fs::read(path).unwrap()).unwrap(); + } + } + } + + #[tokio::test] + async fn interrupted_update_archive_preserves_active_version_and_valid_zip_activates() { + let base = tempfile::tempdir().unwrap(); + let registry = PluginPackageRegistry::at(base.path().join("registry")).unwrap(); + let lifecycle = ManagedPackageLifecycle::new(registry.clone()); + let updater = ManagedPluginUpdater::new(registry.clone()); + let key = ring::signature::Ed25519KeyPair::from_seed_unchecked(&[31; 32]).unwrap(); + let publisher_key: [u8; 32] = key.public_key().as_ref().try_into().unwrap(); + + let v1 = base.path().join("v1"); + signed_package_with_playtime( + &v1, + "1.0.0", + &key, + serde_json::json!({ + "identifies_gameplay": true, + "identifies_pauses": true, + "without_pause_detection": "disabled" + }), + ); + lifecycle + .install_candidate(&v1, publisher_key, EmulationPolicy::RequireNative, true) + .await + .unwrap(); + + let verifier = UpdateIndexVerifier::open(base.path().join("update-sequences")).unwrap(); + let client = FetchClient::new().unwrap(); + let metadata = UpdateIndex { + schema: 1, + plugin_id: "org.example.update".into(), + sequence: 3, + expires_at: 10_000, + releases: vec![UpdateRelease { + version: "2.0.0".into(), + targets: vec!["linux-x86_64-gnu".into()], + api_range: ">=1.6.0, <2.0.0".into(), + package_url: "https://updates.example/v2.zip".into(), + package_size: 10, + package_sha256: "a".repeat(64), + bundle_sha256: None, + }], + }; + let signed_index = serde_json::to_vec(&metadata).unwrap(); + let mut index_message = INDEX_SIGNATURE_DOMAIN.to_vec(); + index_message.extend_from_slice(&signed_index); + let index_signature = key.sign(&index_message); + assert_eq!( + verifier.verify(&signed_index, &[0; 64], &publisher_key, 100), + Err(UpdateError::InvalidSignature) + ); + assert_eq!( + verifier.verify( + &signed_index, + index_signature.as_ref(), + &publisher_key, + 10_000 + ), + Err(UpdateError::Expired) + ); + verifier + .verify(&signed_index, index_signature.as_ref(), &publisher_key, 100) + .unwrap(); + assert_eq!( + verifier.verify(&signed_index, index_signature.as_ref(), &publisher_key, 100), + Err(UpdateError::Replay) + ); + assert_eq!( + registry + .active("org.example.update") + .unwrap() + .unwrap() + .version, + "1.0.0" + ); + assert!( + updater + .check_feed( + &verifier, + &client, + "org.example.update", + "https://updates.invalid/offline.json", + publisher_key, + |_| true + ) + .await + .is_err() + ); + assert_eq!( + registry + .active("org.example.update") + .unwrap() + .unwrap() + .version, + "1.0.0" + ); + + let v2 = base.path().join("v2"); + signed_package(&v2, "2.0.0", &key); + let archive_path = base.path().join("v2.zip"); + let mut zip = ZipWriter::new(fs::File::create(&archive_path).unwrap()); + add_tree(&mut zip, &v2, &v2); + zip.finish().unwrap(); + let archive = fs::read(&archive_path).unwrap(); + let release = UpdateRelease { + version: "2.0.0".into(), + targets: vec!["linux-x86_64-gnu".into()], + api_range: ">=1.6.0, <2.0.0".into(), + package_url: "https://updates.example/v2.zip".into(), + package_size: archive.len() as u64, + package_sha256: format!("{:x}", sha2::Sha256::digest(&archive)), + bundle_sha256: None, + }; + let index = UpdateIndex { + schema: 1, + plugin_id: "org.example.update".into(), + sequence: 1, + expires_at: u64::MAX, + releases: vec![release.clone()], + }; + + let feed_downgrade = UpdateRelease { + version: "0.9.0".into(), + ..release.clone() + }; + let downgrade_index = UpdateIndex { + releases: vec![feed_downgrade.clone()], + ..index.clone() + }; + assert!(matches!( + updater + .install_verified_archive( + &downgrade_index, + &feed_downgrade, + archive.clone(), + publisher_key, + EmulationPolicy::RequireNative, + ) + .await, + Err(ManagedUpdateError::Downgrade) + )); + + let interrupted = archive[..archive.len() / 2].to_vec(); + assert!( + updater + .install_verified_archive( + &index, + &release, + interrupted, + publisher_key, + EmulationPolicy::RequireNative + ) + .await + .is_err() + ); + assert_eq!( + registry + .active("org.example.update") + .unwrap() + .unwrap() + .version, + "1.0.0" + ); + + let installed = updater + .install_verified_archive( + &index, + &release, + archive, + publisher_key, + EmulationPolicy::RequireNative, + ) + .await + .unwrap(); + assert_eq!(installed.version, "2.0.0"); + assert_eq!( + registry + .active("org.example.update") + .unwrap() + .unwrap() + .version, + "2.0.0" + ); + } + + fn archive_package(package: &Path) -> PathBuf { + let archive = package.with_extension("gnplugin"); + let mut zip = ZipWriter::new(fs::File::create(&archive).unwrap()); + add_tree(&mut zip, package, package); + zip.finish().unwrap(); + archive + } + + fn import_service(paths: &gamenode_platform::paths::DataPaths) -> PluginUpdateService { + import_service_with_profiles(paths).0 + } + + fn import_service_with_profiles( + paths: &gamenode_platform::paths::DataPaths, + ) -> (PluginUpdateService, std::sync::Arc) { + use crate::plugin_host::{ + PluginApi, process::ProviderProcesses, runtime::ThirdPartyPluginLifecycle, + }; + + let service = PluginUpdateService::open(paths).unwrap(); + let api = PluginApi::default(); + api.set_state_layout(service.grant_layout.clone()); + let profiles = api.providers.profiles(); + profiles.update(Some("account-a"), true); + let processes = ProviderProcesses::new_for_lifecycle( + api.providers.clone(), + paths.data_dir().join("provider.sock"), + vec![], + service.grant_layout.clone(), + ) + .unwrap(); + service.set_lifecycle(std::sync::Arc::new(ThirdPartyPluginLifecycle::new( + api.providers, + processes, + service.grant_layout.clone(), + service.registry.clone(), + service.packages.clone(), + ))); + service.set_profiles(profiles.clone()); + (service, profiles) + } + + /// Stages the pending review the update/downgrade flow would build for a version that is + /// already installed. It reuses the production comparison and activation path so focused + /// tests can exercise approval without a live update feed. + async fn stage_installed_update( + service: &PluginUpdateService, + plugin_id: &str, + installed_version: &str, + candidate_version: &str, + ) -> UpdateReview { + let active = service.registry.active(plugin_id).unwrap().unwrap(); + assert_eq!(active.version, installed_version); + let candidate = service + .registry + .versions(plugin_id) + .unwrap() + .into_iter() + .find(|version| version.version == candidate_version) + .expect("candidate version is installed"); + let publisher_key = package_key(&active.package_path).unwrap(); + let candidate_publisher_key = package_key(&candidate.package_path).unwrap(); + let installed = service + .packages + .inspect_candidate( + &active.package_path, + publisher_key, + EmulationPolicy::RequireNative, + ) + .await + .unwrap(); + let selected = service + .packages + .inspect_candidate( + &candidate.package_path, + candidate_publisher_key, + EmulationPolicy::RequireNative, + ) + .await + .unwrap(); + let mut review = UpdateReview::compare(&installed.manifest, &selected.manifest); + review.compatibility_details = Some(selected.compatibility_review()); + review.publisher_fingerprint = + super::super::publisher_trust::key_fingerprint(&candidate_publisher_key); + service.pending.lock().await.insert( + plugin_id.to_owned(), + PendingCandidate { + work: None, + version: candidate_version.to_owned(), + installed_version: installed_version.to_owned(), + publisher_key, + candidate_publisher_key, + confirmed_retrust: false, + is_rollback: false, + installed_manifest: installed.manifest, + candidate_manifest: selected.manifest, + review: review.clone(), + }, + ); + review + } + + async fn import_review_and_pin( + service: &PluginUpdateService, + package: &Path, + ) -> PluginImportReview { + let review = service + .import_review(archive_package(package)) + .await + .unwrap(); + service + .import_confirm_publisher(&review.token, &review.package.publisher_fingerprint) + .await + .unwrap() + } + + #[tokio::test] + async fn mvp_example_packages_use_production_import_and_consent_validators() { + use crate::plugin_host::{ + PluginApi, grants::PermissionDecision, grants::PermissionState, + managed_packages::ManagedPackageLifecycle, process::ProviderProcesses, + profile::PluginStateLayout, runtime::HostedProviders, + runtime::ThirdPartyPluginLifecycle, + }; + use gamenode_core::library::LibraryStore; + use gamenode_platform::{ + db::{self, SqliteSettingsStore}, + paths::DataPaths, + plugin_registry::PluginPackageRegistry, + }; + + for (example, plugin_id, seed, requested) in + [("rust-sdk", "org.example.gamenode.rust-mvp", 72_u8, 4)] + { + let base = tempfile::tempdir().unwrap(); + let paths = DataPaths::at(base.path().join("app")); + let endpoint = base.path().join("plugins.sock"); + let api = PluginApi::default(); + let state = PluginStateLayout::managed(&paths); + api.set_state_layout(state.clone()); + api.providers.profiles().update(Some("account-one"), true); + let registry = PluginPackageRegistry::open(&paths).unwrap(); + let preliminary_processes = ProviderProcesses::new_for_lifecycle( + api.providers.clone(), + endpoint.clone(), + vec![], + state.clone(), + ) + .unwrap(); + let prelimary = std::sync::Arc::new(ThirdPartyPluginLifecycle::new( + api.providers.clone(), + preliminary_processes, + state, + registry.clone(), + ManagedPackageLifecycle::new(registry.clone()), + )); + let service = PluginUpdateService::open(&paths).unwrap(); + service.set_lifecycle(prelimary); + + let key = ring::signature::Ed25519KeyPair::from_seed_unchecked(&[seed; 32]).unwrap(); + let package = base.path().join(format!("{example}-package")); + signed_example_package(&package, example, &key); + let review = service + .import_review(archive_package(&package)) + .await + .unwrap(); + assert_eq!(review.package.plugin_id, plugin_id); + assert_eq!(review.package.trust, "untrusted"); + assert_eq!(review.package.compatibility, "compatible"); + assert_eq!( + review.package.license_files, + vec!["licenses/LICENSE".to_owned()] + ); + assert_eq!( + review.package.license_notices, + vec!["licenses/THIRD-PARTY-NOTICES.txt".to_owned()] + ); + assert!( + service + .import_license_text(&review.token, "licenses/LICENSE") + .await + .unwrap() + .contains("MIT License") + ); + assert!( + !service + .import_license_text(&review.token, "outside.txt") + .await + .is_ok() + ); + assert!( + service + .import_install(&review.token, false, &[]) + .await + .unwrap_err() + .contains("confirm the publisher") + ); + + let pinned = service + .import_confirm_publisher(&review.token, &review.package.publisher_fingerprint) + .await + .unwrap(); + assert_eq!(pinned.package.trust, "trusted"); + assert_eq!( + service + .import_install(&review.token, false, &[]) + .await + .unwrap() + .plugin_id, + plugin_id + ); + + // Startup composes the registry into the runtime; that composition is what registers + // the installed provider for consent review. Rebuild it here as an application + // launch would, then review permissions through the production validator. + let library: std::sync::Arc = std::sync::Arc::new( + SqliteSettingsStore::new(db::open(Path::new(":memory:")).unwrap()).library_store(), + ); + let host = HostedProviders::bundled( + api.providers.clone(), + std::sync::Arc::new(Default::default()), + Some(endpoint), + paths, + library, + None, + ) + .await + .unwrap(); + + let snapshot = host + .lifecycle() + .permission_snapshot(plugin_id.into()) + .await + .unwrap(); + assert_eq!(snapshot.requested_permissions.len(), requested); + let decisions = snapshot + .requested_permissions + .iter() + .map(|request| PermissionDecision { + permission_id: request.permission_id.clone(), + scope: request + .allowed_scopes + .iter() + .next() + .cloned() + .expect("manifest permission exposes a reviewable scope"), + granted: request.permission_id != "library.discovery", + }) + .collect(); + let reviewed = host + .lifecycle() + .replace_permissions( + &tokio::sync::Mutex::new(()), + plugin_id.into(), + snapshot.profile_id.clone(), + snapshot.publisher_fingerprint.clone(), + snapshot.grant_revision, + decisions, + ) + .await + .unwrap(); + assert!( + reviewed + .effective_grants + .iter() + .any(|grant| grant.permission_id == "library.discovery" + && grant.state == PermissionState::Denied) + ); + assert!( + reviewed + .effective_grants + .iter() + .any(|grant| grant.permission_id == "library.catalog" + && grant.state == PermissionState::Granted) + ); + } + } + + #[tokio::test] + async fn import_install_registers_and_enables_a_signed_extension_without_a_restart() { + let base = tempfile::tempdir().unwrap(); + let paths = gamenode_platform::paths::DataPaths::at(base.path().join("app")); + let (service, _profiles) = import_service_with_profiles(&paths); + let key = ring::signature::Ed25519KeyPair::from_seed_unchecked(&[47; 32]).unwrap(); + let package = base.path().join("launch-extension"); + signed_package_from_manifest(&package, &key, &extension_fixture_manifest("1.0.0")); + let imported = import_review_and_pin(&service, &package).await; + + let outcome = service + .import_install(&imported.token, false, &[]) + .await + .unwrap(); + assert!(outcome.activated, "{:?}", outcome.activation_error); + assert_eq!(outcome.plugin_id, "org.example.launch"); + + // No second lifecycle and no new HostedProviders: the same host is usable right away. + let lifecycle = service + .lifecycle + .read() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .clone() + .unwrap(); + assert!(lifecycle.is_registered("org.example.launch")); + assert!(lifecycle.has_process_slot("org.example.launch")); + assert!(lifecycle.extension_runtime_available("org.example.launch")); + assert!( + lifecycle + .enabled("org.example.launch".into()) + .await + .unwrap() + ); + + let inventory = service.managed_inventory().await.unwrap(); + let row = inventory + .iter() + .find(|plugin| plugin.plugin_id == "org.example.launch") + .expect("the imported extension is listed"); + assert_eq!(row.status, "installed"); + assert_eq!(row.runtime_available, Some(true)); + assert_eq!(row.enabled, Some(true)); + let serialized = serde_json::to_value(row).unwrap(); + assert_eq!(serialized["runtimeAvailable"], serde_json::json!(true)); + assert_eq!(serialized["enabled"], serde_json::json!(true)); + } + + #[tokio::test] + async fn import_activation_failure_keeps_the_package_installed_and_reports_the_error() { + use crate::plugin_host::grants::PermissionState; + + let base = tempfile::tempdir().unwrap(); + let paths = gamenode_platform::paths::DataPaths::at(base.path().join("app")); + let service = import_service(&paths); + let key = ring::signature::Ed25519KeyPair::from_seed_unchecked(&[48; 32]).unwrap(); + let package = base.path().join("unstartable-provider"); + // The inert fixture entrypoint cannot start, so activation must fail after installation. + signed_package(&package, "1.0.0", &key); + let imported = import_review_and_pin(&service, &package).await; + + let outcome = service + .import_install(&imported.token, true, &[]) + .await + .unwrap(); + assert!(!outcome.activated); + assert_eq!(outcome.plugin_id, "org.example.update"); + assert!( + outcome + .activation_error + .as_deref() + .unwrap_or_default() + .contains("activation failed"), + "{:?}", + outcome.activation_error + ); + + // The package and the reviewed grants are not rolled back. + assert!( + service + .registry + .active("org.example.update") + .unwrap() + .is_some() + ); + let lifecycle = service + .lifecycle + .read() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .clone() + .unwrap(); + assert!(lifecycle.is_registered("org.example.update")); + assert!(lifecycle.has_process_slot("org.example.update")); + assert!( + !lifecycle + .enabled("org.example.update".into()) + .await + .unwrap() + ); + let snapshot = lifecycle + .installed_permission_snapshot( + "org.example.update".into(), + imported.package.publisher_fingerprint.clone(), + ) + .await + .unwrap(); + assert!(snapshot.effective_grants.iter().any(|grant| { + grant.permission_id == "storage.persist" && grant.state == PermissionState::Granted + })); + + // The registration is complete, not half-applied: a later attempt skips it by identity. + let outcomes = lifecycle.register_installed_packages().await.unwrap(); + assert!( + outcomes + .iter() + .all(|outcome| outcome.plugin_id != "org.example.update") + ); + assert!(lifecycle.is_registered("org.example.update")); + } + + #[test] + fn playtime_capabilities_serialize_camel_case_and_accept_manifest_snake_case() { + let parsed: PlaytimeCapabilities = serde_json::from_value(serde_json::json!({ + "identifies_gameplay": true, + "identifies_pauses": false, + "without_pause_detection": "application_open" + })) + .unwrap(); + assert!(parsed.identifies_gameplay); + assert!(!parsed.identifies_pauses); + assert_eq!( + parsed.without_pause_detection, + super::super::package::PlaytimeAccountingMode::ApplicationOpen + ); + assert_eq!( + serde_json::to_value(parsed).unwrap(), + serde_json::json!({ + "identifiesGameplay": true, + "identifiesPauses": false, + "withoutPauseDetection": "application_open" + }) + ); + } + + #[tokio::test] + async fn playtime_inventory_lists_only_packages_that_declare_playtime() { + let base = tempfile::tempdir().unwrap(); + let paths = gamenode_platform::paths::DataPaths::at(base.path().join("app")); + let service = import_service(&paths); + let key = ring::signature::Ed25519KeyPair::from_seed_unchecked(&[49; 32]).unwrap(); + + let declaring = base.path().join("declaring-playtime"); + signed_package_with_playtime( + &declaring, + "1.0.0", + &key, + serde_json::json!({ + "identifies_gameplay": true, + "identifies_pauses": false, + "without_pause_detection": "application_open" + }), + ); + let imported = import_review_and_pin(&service, &declaring).await; + service + .import_install(&imported.token, true, &[]) + .await + .unwrap(); + + let plain = base.path().join("plain-package"); + let mut manifest = fixture_manifest("1.0.0", vec![]); + manifest["id"] = serde_json::json!("org.example.plain"); + manifest["provider_id"] = serde_json::json!("plain-fixture"); + manifest["name"] = serde_json::json!("Plain Fixture"); + signed_package_from_manifest(&plain, &key, &manifest); + let imported = import_review_and_pin(&service, &plain).await; + service + .import_install(&imported.token, true, &[]) + .await + .unwrap(); + + let inventory = service.playtime_inventory().await.unwrap(); + assert_eq!(inventory.len(), 1, "{inventory:#?}"); + assert_eq!(inventory[0].plugin_id, "org.example.update"); + let serialized = serde_json::to_value(&inventory[0]).unwrap(); + assert_eq!( + serialized["playtime"], + serde_json::json!({ + "identifiesGameplay": true, + "identifiesPauses": false, + "withoutPauseDetection": "application_open" + }) + ); + } + + #[tokio::test] + async fn imported_publisher_pin_authorizes_update_rollback_and_playtime() { + let base = tempfile::tempdir().unwrap(); + let paths = gamenode_platform::paths::DataPaths::at(base.path().join("app")); + let service = import_service(&paths); + let plugin_id = "org.example.update"; + let key = ring::signature::Ed25519KeyPair::from_seed_unchecked(&[39; 32]).unwrap(); + let v1 = base.path().join("v1"); + signed_package_with_playtime( + &v1, + "1.0.0", + &key, + serde_json::json!({ + "identifies_gameplay": true, + "identifies_pauses": true, + "without_pause_detection": "disabled" + }), + ); + let imported = import_review_and_pin(&service, &v1).await; + assert_eq!( + service + .import_install(&imported.token, true, &[]) + .await + .unwrap() + .plugin_id, + plugin_id + ); + assert_eq!( + service.playtime_inventory().await.unwrap()[0].version, + "1.0.0" + ); + + // Stage the update where the reviewed feed flow would; the pin must come from the + // import flow's trust store with no artificial entry in the legacy private directory. + let work = UpdateWorkDir::create().unwrap(); + let staged = work.path.join("package"); + signed_package_with_playtime( + &staged, + "2.0.0", + &key, + serde_json::json!({ + "identifies_gameplay": true, + "identifies_pauses": true, + "without_pause_detection": "disabled" + }), + ); + let public_key: [u8; 32] = key.public_key().as_ref().try_into().unwrap(); + let active = service.registry.active(plugin_id).unwrap().unwrap(); + let current = service + .packages + .inspect_candidate( + &active.package_path, + public_key, + EmulationPolicy::RequireNative, + ) + .await + .unwrap(); + let candidate = service + .packages + .inspect_candidate(&staged, public_key, EmulationPolicy::RequireNative) + .await + .unwrap(); + let mut review = UpdateReview::compare(¤t.manifest, &candidate.manifest); + review.publisher_fingerprint = super::super::publisher_trust::key_fingerprint(&public_key); + service.pending.lock().await.insert( + plugin_id.to_owned(), + PendingCandidate { + work: Some(work), + version: "2.0.0".into(), + installed_version: active.version, + publisher_key: public_key, + candidate_publisher_key: public_key, + confirmed_retrust: false, + is_rollback: false, + installed_manifest: current.manifest, + candidate_manifest: candidate.manifest, + review: review.clone(), + }, + ); + assert!(!review.publisher_changed); + assert_eq!( + service.approve(plugin_id, "2.0.0", None).await.unwrap(), + "2.0.0" + ); + assert_eq!( + service.playtime_inventory().await.unwrap()[0].version, + "2.0.0" + ); + + let review = service.review_rollback(plugin_id, "1.0.0").await.unwrap(); + assert!(!review.publisher_changed); + assert_eq!( + service + .approve_rollback(plugin_id, "1.0.0", true, None) + .await + .unwrap(), + "1.0.0" + ); + assert_eq!( + service.playtime_inventory().await.unwrap()[0].version, + "1.0.0" + ); + assert!(!paths.private_dir().join("publisher-keys.json").exists()); + } + + /// Installs `old_permissions` as 1.0.0 and imports a pinned 2.0.0 signed by the same key. + async fn service_with_older_version( + base: &Path, + old_permissions: Vec, + ) -> PluginUpdateService { + let paths = gamenode_platform::paths::DataPaths::at(base.join("app")); + paths.ensure_data_dir().unwrap(); + let service = import_service(&paths); + let key = ring::signature::Ed25519KeyPair::from_seed_unchecked(&[43; 32]).unwrap(); + let public: [u8; 32] = key.public_key().as_ref().try_into().unwrap(); + let old = base.join("old"); + signed_package_with_permissions(&old, "1.0.0", &key, old_permissions); + service + .packages + .install_candidate(&old, public, EmulationPolicy::RequireNative, false) + .await + .unwrap(); + let current = base.join("current"); + signed_package(¤t, "2.0.0", &key); + let imported = import_review_and_pin(&service, ¤t).await; + service + .import_install(&imported.token, true, &[]) + .await + .unwrap(); + service + } + + #[tokio::test] + async fn rollback_review_rejects_a_network_scope_that_is_not_an_exact_origin() { + let base = tempfile::tempdir().unwrap(); + let service = service_with_older_version( + base.path(), + vec![serde_json::json!({ + "id": "network.fetch", "required": false, "scope": "api.example.com", + "reason": "Fetch metadata" + })], + ) + .await; + let error = service + .review_rollback("org.example.update", "1.0.0") + .await + .unwrap_err(); + assert!(error.contains("unsupported permission scopes"), "{error}"); + assert_eq!( + service + .registry + .active("org.example.update") + .unwrap() + .unwrap() + .version, + "2.0.0" + ); + } + + #[tokio::test] + async fn approval_refuses_a_package_whose_permissions_differ_from_the_review() { + let base = tempfile::tempdir().unwrap(); + let service = service_with_older_version( + base.path(), + vec![serde_json::json!({ + "id": "storage.persist", "required": false, "scope": "own-provider", + "reason": "Store plugin preferences" + })], + ) + .await; + service + .review_rollback("org.example.update", "1.0.0") + .await + .unwrap(); + // The reviewed manifest no longer matches the verified package on disk. + service + .pending + .lock() + .await + .get_mut("org.example.update") + .unwrap() + .candidate_manifest + .permissions + .push(crate::plugin_host::package::PermissionRequest { + id: "network.fetch".into(), + required: false, + scope: "https://api.example.com".into(), + reason: "Fetch metadata".into(), + impact_if_disabled: None, + }); + let error = service + .approve_rollback("org.example.update", "1.0.0", true, None) + .await + .unwrap_err(); + assert!( + error.contains("permissions differ from the reviewed package"), + "{error}" + ); + assert_eq!( + service + .registry + .active("org.example.update") + .unwrap() + .unwrap() + .version, + "2.0.0" + ); + } + + #[tokio::test] + async fn rollback_requires_confirmation_and_exact_retrust_for_a_changed_key() { + let base = tempfile::tempdir().unwrap(); + let paths = gamenode_platform::paths::DataPaths::at(base.path().join("app")); + paths.ensure_data_dir().unwrap(); + let service = import_service(&paths); + let old_key = ring::signature::Ed25519KeyPair::from_seed_unchecked(&[41; 32]).unwrap(); + let current_key = ring::signature::Ed25519KeyPair::from_seed_unchecked(&[42; 32]).unwrap(); + let old_public: [u8; 32] = old_key.public_key().as_ref().try_into().unwrap(); + + let old_package = base.path().join("old"); + signed_package(&old_package, "1.0.0", &old_key); + service + .packages + .install_candidate( + &old_package, + old_public, + EmulationPolicy::RequireNative, + false, + ) + .await + .unwrap(); + let current_package = base.path().join("current"); + signed_package(¤t_package, "2.0.0", ¤t_key); + let imported = import_review_and_pin(&service, ¤t_package).await; + service + .import_install(&imported.token, true, &[]) + .await + .unwrap(); + assert_eq!( + service + .rollback_versions("org.example.update") + .await + .unwrap(), + ["1.0.0"] + ); + let review = service + .review_rollback("org.example.update", "1.0.0") + .await + .unwrap(); + assert!(review.is_downgrade && review.publisher_changed); + assert!( + service + .approve_rollback("org.example.update", "1.0.0", false, None) + .await + .is_err() + ); + assert_eq!( + service + .approve_rollback("org.example.update", "1.0.0", true, None) + .await + .unwrap_err(), + "the changed publisher key must be re-trusted separately" + ); + assert!( + service + .confirm_publisher_retrust("org.example.update", "1.0.0", "SHA256:wrong") + .await + .is_err() + ); + service + .confirm_publisher_retrust( + "org.example.update", + "1.0.0", + &super::super::publisher_trust::key_fingerprint(&old_public), + ) + .await + .unwrap(); + assert_eq!( + service + .approve_rollback("org.example.update", "1.0.0", true, None) + .await + .unwrap(), + "1.0.0" + ); + assert!( + super::super::publisher_trust::PublisherTrustStore::open(&service.trust_dir) + .unwrap() + .is_pinned("org.example.update", &old_public) + .unwrap() + ); + } + + /// Re-trusting a changed publisher key establishes a distinct identity. Both keys' approved + /// origins are revoked, so a stale approval recorded under either fingerprint cannot resurface, + /// and the new identity still needs its own origin review before it can fetch. + #[tokio::test] + async fn changed_publisher_key_revokes_previous_grants_and_origin_approvals() { + use crate::plugin_host::{ + grants::{ + GrantScope, PermissionDecision, PermissionState, PluginIdentity, + manifest_permission_requests, + }, + network::{OriginScopes as _, PersistedOriginScopes}, + }; + + let base = tempfile::tempdir().unwrap(); + let paths = gamenode_platform::paths::DataPaths::at(base.path().join("app")); + paths.ensure_data_dir().unwrap(); + let (service, profiles) = import_service_with_profiles(&paths); + let plugin_id = "org.example.update"; + let key_a = ring::signature::Ed25519KeyPair::from_seed_unchecked(&[61; 32]).unwrap(); + let key_b = ring::signature::Ed25519KeyPair::from_seed_unchecked(&[62; 32]).unwrap(); + let public_a: [u8; 32] = key_a.public_key().as_ref().try_into().unwrap(); + let public_b: [u8; 32] = key_b.public_key().as_ref().try_into().unwrap(); + let first_origin = "https://first.example"; + let second_origin = "https://second.example"; + let permissions = || { + vec![ + serde_json::json!({ + "id": "network.fetch", "required": false, + "scope": format!("{first_origin}, {second_origin}"), + "reason": "Fetch the plugin's service data" + }), + serde_json::json!({ + "id": "storage.persist", "required": false, "scope": "own-provider", + "reason": "Store plugin preferences" + }), + ] + }; + + let v1 = base.path().join("v1"); + signed_package_with_permissions(&v1, "1.0.0", &key_a, permissions()); + service + .packages + .install_candidate(&v1, public_a, EmulationPolicy::RequireNative, true) + .await + .unwrap(); + let fingerprint_a = super::super::publisher_trust::key_fingerprint(&public_a); + super::super::publisher_trust::PublisherTrustStore::open(&service.trust_dir) + .unwrap() + .confirm_first_key(plugin_id, &public_a, &fingerprint_a) + .unwrap(); + + let profile = profiles.current().unwrap(); + let identity_a = PluginIdentity { + plugin_id: plugin_id.into(), + publisher_fingerprint: fingerprint_a, + profile_id: profile.profile_id().to_owned(), + }; + let installed_manifest = service + .packages + .inspect_candidate(&v1, public_a, EmulationPolicy::RequireNative) + .await + .unwrap() + .manifest; + let requests = manifest_permission_requests(&installed_manifest.permissions).unwrap(); + service + .grant_layout + .open_grants(&profile) + .unwrap() + .replace_grants( + identity_a.clone(), + &requests, + &[ + PermissionDecision { + permission_id: "network.fetch".into(), + scope: GrantScope::Declared { + value: first_origin.into(), + }, + granted: true, + }, + PermissionDecision { + permission_id: "network.fetch".into(), + scope: GrantScope::Declared { + value: second_origin.into(), + }, + granted: true, + }, + PermissionDecision { + permission_id: "storage.persist".into(), + scope: GrantScope::OwnPrivateNamespace, + granted: true, + }, + ], + ) + .unwrap(); + let fingerprint_b = super::super::publisher_trust::key_fingerprint(&public_b); + let identity_b = PluginIdentity { + plugin_id: plugin_id.into(), + publisher_fingerprint: fingerprint_b.clone(), + profile_id: profile.profile_id().to_owned(), + }; + // A stale approval recorded under the incoming key (for example from an install of that + // publisher before the current one) must not resurface when the key is re-trusted. + service + .grant_layout + .open_grants(&profile) + .unwrap() + .replace_grants( + identity_b.clone(), + &requests, + &[PermissionDecision { + permission_id: "network.fetch".into(), + scope: GrantScope::Declared { + value: first_origin.into(), + }, + granted: true, + }], + ) + .unwrap(); + let scopes = PersistedOriginScopes { + profiles: profiles.clone(), + layout: service.grant_layout.clone(), + }; + assert_eq!( + scopes + .approved(&identity_a, profile.epoch()) + .await + .unwrap() + .origins, + BTreeSet::from([first_origin.to_owned(), second_origin.to_owned()]) + ); + assert_eq!( + scopes + .approved(&identity_b, profile.epoch()) + .await + .unwrap() + .origins, + BTreeSet::from([first_origin.to_owned()]) + ); + + // The update flow presents a package signed by the new key. Activation waits for the + // separate re-trust decision bound to that exact fingerprint. + let v2 = base.path().join("v2"); + signed_package_with_permissions(&v2, "2.0.0", &key_b, permissions()); + service + .packages + .install_candidate(&v2, public_b, EmulationPolicy::RequireNative, false) + .await + .unwrap(); + let review = stage_installed_update(&service, plugin_id, "1.0.0", "2.0.0").await; + assert!(review.publisher_changed); + assert!( + service + .approve(plugin_id, "2.0.0", None) + .await + .unwrap_err() + .contains("re-trusted separately") + ); + service + .confirm_publisher_retrust(plugin_id, "2.0.0", &fingerprint_b) + .await + .unwrap(); + assert_eq!( + service.approve(plugin_id, "2.0.0", None).await.unwrap(), + "2.0.0" + ); + + // Neither identity keeps a granted origin, nobody holds a granted permission under the + // new key yet (the user must review it), and only the new key remains pinned. + let grants = service.grant_layout.open_grants(&profile).unwrap(); + let previous = grants.effective_grants(&identity_a); + assert!(!previous.is_empty()); + for grant in previous.iter().filter(|grant| { + grant.permission_id == gamenode_plugin_protocol::capability::NETWORK_FETCH + }) { + assert_eq!(grant.state, PermissionState::Denied); + } + let current = grants.effective_grants(&identity_b); + assert!(!current.is_empty()); + assert!( + current + .iter() + .all(|grant| grant.state != PermissionState::Granted) + ); + assert!( + scopes + .approved(&identity_a, profile.epoch()) + .await + .unwrap() + .origins + .is_empty() + ); + let new_identity = scopes.approved(&identity_b, profile.epoch()).await.unwrap(); + assert!(new_identity.origins.is_empty()); + assert!(new_identity.revision > 0); + let trust = + super::super::publisher_trust::PublisherTrustStore::open(&service.trust_dir).unwrap(); + assert!(trust.is_pinned(plugin_id, &public_b).unwrap()); + assert!(!trust.is_pinned(plugin_id, &public_a).unwrap()); + } + + /// Removes a read-only mode on drop so a failing assertion cannot leave the test's temporary + /// registry unwritable during cleanup. + #[cfg(unix)] + struct RestoreDirectoryMode { + path: PathBuf, + restore: u32, + } + + #[cfg(unix)] + impl Drop for RestoreDirectoryMode { + fn drop(&mut self) { + use std::os::unix::fs::PermissionsExt; + let _ = fs::set_permissions(&self.path, fs::Permissions::from_mode(self.restore)); + } + } + + /// A failed active-pointer write must leave the previous version in place and usable. The + /// candidate stays installed but inactive, nothing reports it active, and a later review of + /// the same payload can activate it once the registry is writable again. + #[cfg(unix)] + #[tokio::test] + async fn failed_active_pointer_write_keeps_the_previous_version_active_and_usable() { + use std::os::unix::fs::PermissionsExt; + + let base = tempfile::tempdir().unwrap(); + let paths = gamenode_platform::paths::DataPaths::at(base.path().join("app")); + paths.ensure_data_dir().unwrap(); + let (service, _profiles) = import_service_with_profiles(&paths); + let plugin_id = "org.example.update"; + let key = ring::signature::Ed25519KeyPair::from_seed_unchecked(&[71; 32]).unwrap(); + let public: [u8; 32] = key.public_key().as_ref().try_into().unwrap(); + let fingerprint = super::super::publisher_trust::key_fingerprint(&public); + + let v1 = base.path().join("v1"); + signed_package_with_playtime( + &v1, + "1.0.0", + &key, + serde_json::json!({ + "identifies_gameplay": true, + "identifies_pauses": true, + "without_pause_detection": "disabled" + }), + ); + service + .packages + .install_candidate(&v1, public, EmulationPolicy::RequireNative, true) + .await + .unwrap(); + super::super::publisher_trust::PublisherTrustStore::open(&service.trust_dir) + .unwrap() + .confirm_first_key(plugin_id, &public, &fingerprint) + .unwrap(); + let v2 = base.path().join("v2"); + signed_package(&v2, "2.0.0", &key); + service + .packages + .install_candidate(&v2, public, EmulationPolicy::RequireNative, false) + .await + .unwrap(); + + // The reviewed update is approved while the active-pointer directory rejects writes. + let active_dir = paths.plugin_packages_dir().join("active"); + let locked = RestoreDirectoryMode { + path: active_dir.clone(), + restore: 0o700, + }; + fs::set_permissions(&active_dir, fs::Permissions::from_mode(0o500)).unwrap(); + stage_installed_update(&service, plugin_id, "1.0.0", "2.0.0").await; + let error = service.approve(plugin_id, "2.0.0", None).await.unwrap_err(); + assert!(!error.is_empty()); + + // The write failed before the pointer rename: no package reports itself active except + // the previous version, which is still intact. + let reported: Vec<_> = service + .registry + .active_versions() + .unwrap() + .into_iter() + .filter(|version| version.plugin_id == plugin_id) + .collect(); + assert_eq!(reported.len(), 1); + assert_eq!(reported[0].version, "1.0.0"); + assert_eq!( + service + .registry + .verify_active_package(plugin_id, &public) + .unwrap() + .expect("the previous version is still usable") + .version, + "1.0.0" + ); + assert!( + service + .registry + .versions(plugin_id) + .unwrap() + .iter() + .any(|version| version.version == "2.0.0"), + "the failed candidate stays installed but inactive" + ); + + // A fresh review can replace the failed candidate once the registry is writable. + drop(locked); + stage_installed_update(&service, plugin_id, "1.0.0", "2.0.0").await; + assert_eq!( + service.approve(plugin_id, "2.0.0", None).await.unwrap(), + "2.0.0" + ); + assert_eq!( + service.registry.active(plugin_id).unwrap().unwrap().version, + "2.0.0" + ); + } + + #[tokio::test] + async fn rollback_preserves_profile_data_and_does_not_restore_rescoped_grants() { + use crate::plugin_host::{ + grants::{ + GrantScope, PermissionDecision, PermissionRequest as GrantRequest, PluginIdentity, + }, + profile::{PluginProfiles, PluginStateLayout}, + }; + use gamenode_platform::plugin_storage::{ + DurableStore, PutResult, QUOTA_BYTES, namespace_dir, + }; + + let base = tempfile::tempdir().unwrap(); + let paths = gamenode_platform::paths::DataPaths::at(base.path().join("app")); + paths.ensure_data_dir().unwrap(); + let registry = PluginPackageRegistry::open(&paths).unwrap(); + let lifecycle = ManagedPackageLifecycle::new(registry.clone()); + let key = ring::signature::Ed25519KeyPair::from_seed_unchecked(&[51; 32]).unwrap(); + let public_key: [u8; 32] = key.public_key().as_ref().try_into().unwrap(); + let current_origin = "https://current.example"; + let previous_origin = "https://previous.example"; + + let previous_package = base.path().join("previous"); + signed_package_with_permissions( + &previous_package, + "1.0.0", + &key, + vec![serde_json::json!({ + "id": "network.fetch", + "required": false, + "scope": format!("{current_origin}, {previous_origin}"), + "reason": "Fetch the plugin's service data" + })], + ); + lifecycle + .install_candidate( + &previous_package, + public_key, + EmulationPolicy::RequireNative, + true, + ) + .await + .unwrap(); + + let current_package = base.path().join("current"); + signed_package_with_permissions( + ¤t_package, + "2.0.0", + &key, + vec![serde_json::json!({ + "id": "network.fetch", + "required": false, + "scope": current_origin, + "reason": "Fetch the plugin's service data" + })], + ); + lifecycle + .install_candidate( + ¤t_package, + public_key, + EmulationPolicy::RequireNative, + true, + ) + .await + .unwrap(); + let fingerprint = super::super::publisher_trust::key_fingerprint(&public_key); + super::super::publisher_trust::PublisherTrustStore::open( + PluginStateLayout::prepare_managed(&paths) + .unwrap() + .trust_dir(), + ) + .unwrap() + .confirm_first_key("org.example.update", &public_key, &fingerprint) + .unwrap(); + + let profiles = std::sync::Arc::new(PluginProfiles::default()); + profiles.update(Some("inactive-account"), true); + let inactive = profiles.current().unwrap(); + profiles.update(Some("account-a"), true); + let profile = profiles.current().unwrap(); + let identity = PluginIdentity { + plugin_id: "org.example.update".into(), + publisher_fingerprint: fingerprint.clone(), + profile_id: profile.profile_id().to_owned(), + }; + let current_scope = GrantScope::Declared { + value: current_origin.into(), + }; + let layout = PluginStateLayout::prepare_managed(&paths).unwrap(); + let inactive_identity = PluginIdentity { + profile_id: inactive.profile_id().to_owned(), + ..identity.clone() + }; + for (account, identity) in [(&profile, &identity), (&inactive, &inactive_identity)] { + layout + .open_grants(account) + .unwrap() + .replace_grants( + identity.clone(), + &[GrantRequest { + permission_id: "network.fetch".into(), + required: false, + allowed_scopes: [current_scope.clone()].into(), + }], + &[PermissionDecision { + permission_id: "network.fetch".into(), + scope: current_scope.clone(), + granted: true, + }], + ) + .unwrap(); + } + + let data_namespace = namespace_dir( + &paths.plugin_data_dir(), + &fingerprint, + "org.example.update", + profile.profile_id(), + ); + let mut data = DurableStore::open(&data_namespace).unwrap(); + assert!(matches!( + data.put( + "settings.v1", + b"shared profile value", + 1, + None, + 1, + QUOTA_BYTES, + ) + .unwrap(), + PutResult::Stored { .. } + )); + drop(data); + + let service = PluginUpdateService::open(&paths).unwrap(); + service.set_profiles(profiles); + let review = service + .review_rollback("org.example.update", "1.0.0") + .await + .unwrap(); + assert!(review.is_downgrade && review.preserves_prior_data); + service + .approve_rollback("org.example.update", "1.0.0", true, None) + .await + .unwrap(); + + assert_eq!( + registry + .active("org.example.update") + .unwrap() + .unwrap() + .version, + "1.0.0" + ); + let retained_data = DurableStore::open_existing(&data_namespace) + .unwrap() + .expect("rollback must leave the plugin/profile namespace in place"); + assert_eq!( + retained_data.get("settings.v1", 1).unwrap().unwrap().value, + b"shared profile value" + ); + let rollback_grants = layout.open_grants(&profile).unwrap(); + assert!(rollback_grants.effective_grants(&identity).is_empty()); + let inactive_grants = layout + .open_grants(&inactive) + .unwrap() + .effective_grants(&inactive_identity); + assert_eq!(inactive_grants.len(), 1); + assert_eq!( + inactive_grants[0].state, + super::super::grants::PermissionState::Denied + ); + } +} diff --git a/crates/app/src/protocol.rs b/crates/app/src/protocol.rs index 26fbb67ff..c4d440219 100644 --- a/crates/app/src/protocol.rs +++ b/crates/app/src/protocol.rs @@ -1034,6 +1034,22 @@ mod tests { assert_eq!(res.status(), StatusCode::NOT_FOUND); } + #[tokio::test] + async fn a_plugin_cover_is_served_like_any_cover_with_the_type_of_its_bytes() { + let dir = tempdir().unwrap(); + let name = "plugin-0123456789abcdef-fedcba9876543210.png"; + assert!(valid_cover_file(name)); + std::fs::write(dir.path().join(name), b"\x89PNG\r\n\x1a\nrest").unwrap(); + let res = handle_asset_uri_str( + &format!("gamenode-asset://localhost/cover/{name}"), + dir.path(), + &|_| None, + ) + .await; + assert_eq!(res.status(), StatusCode::OK); + assert_eq!(res.headers()[header::CONTENT_TYPE], "image/png"); + } + #[tokio::test] async fn return_404_for_missing_cover_file() { let dir = tempdir().unwrap(); @@ -1557,6 +1573,7 @@ mod tests { membership: Membership::NotChecked, achievement_backend: false, achievements: None, + detected_target: None, suggestions: Vec::new(), }; diff --git a/crates/app/src/providers.rs b/crates/app/src/providers.rs index 85ff434d6..2d68906f1 100644 --- a/crates/app/src/providers.rs +++ b/crates/app/src/providers.rs @@ -54,6 +54,100 @@ mod tests { } } + #[test] + fn third_party_registry_states_do_not_change_official_linux_providers() { + let platform = Platform::Linux; + let official = crate::plugin_host::backends(platform); + let expected = load_bundled_with_plugins(platform, &official); + assert!( + expected.diagnostics.is_empty(), + "{:?}", + expected.diagnostics + ); + let expected_steam = expected.get("steam").unwrap().manifest().clone(); + let expected_packagekit = expected.get("packagekit").unwrap().manifest().clone(); + + // An empty or disabled third-party registry contributes no backend. Invalid/untrusted + // entries must not be allowed to impersonate Steam, while an enabled, unrelated provider + // may add only its own backend. The host also rejects duplicate provider registrations; + // this matrix verifies the Core manifest loader preserves the official definitions for + // every backend set that can reach it. + let mut invalid = official.clone(); + invalid.push(PluginBackend { + plugin_id: "org.untrusted.replacement".into(), + provider_id: "steam".into(), + discovery: true, + catalog: true, + counter: true, + actions: true, + achievements: true, + }); + let mut enabled = official.clone(); + enabled.push(PluginBackend { + plugin_id: "org.example.third-party".into(), + provider_id: "example-store".into(), + discovery: true, + catalog: true, + counter: true, + actions: true, + achievements: true, + }); + + for (state, backends) in [ + ("empty", official.clone()), + ("invalid", invalid), + ("enabled", enabled), + ("disabled", official), + ] { + let loaded = load_bundled_with_plugins(platform, &backends); + assert!( + loaded.diagnostics.is_empty(), + "{state}: {:?}", + loaded.diagnostics + ); + let steam = loaded.get("steam").expect("Steam remains registered"); + assert_eq!( + steam.manifest(), + &expected_steam, + "Steam changed for {state}" + ); + assert_eq!( + steam.discovery_plugin(), + Some("org.gamenode.plugin.steam-discovery"), + "Steam discovery must remain plugin-backed for {state}" + ); + assert_eq!( + steam.catalog_backend(), + Some("org.gamenode.plugin.steam-discovery"), + "Steam catalog must remain plugin-backed for {state}" + ); + assert_eq!( + steam.counter_plugin(), + Some("org.gamenode.plugin.steam-discovery"), + "Steam counter must remain plugin-backed for {state}" + ); + assert_eq!( + steam.achievement_plugin(), + Some("org.gamenode.plugin.steam-discovery"), + "Steam achievements integration must remain unchanged for {state}" + ); + + let packagekit = loaded + .get("packagekit") + .expect("Linux package discovery remains registered"); + assert_eq!( + packagekit.manifest(), + &expected_packagekit, + "PackageKit changed for {state}" + ); + assert_eq!( + packagekit.discovery_plugin(), + Some("org.gamenode.plugin.packagekit-discovery"), + "Linux package discovery must remain plugin-backed for {state}" + ); + } + } + #[test] fn the_bundled_manifests_are_all_valid_on_every_platform() { for platform in [Platform::Windows, Platform::Linux] { diff --git a/crates/core/Cargo.toml b/crates/core/Cargo.toml index e182b0781..976dccc30 100644 --- a/crates/core/Cargo.toml +++ b/crates/core/Cargo.toml @@ -16,11 +16,13 @@ async-trait.workspace = true percent-encoding.workspace = true serde = { workspace = true, features = ["rc"] } serde_yaml = "0.9.34" +sha2 = "0.10.9" thiserror.workspace = true toml.workspace = true tracing.workspace = true unicode-normalization = "0.1.24" url.workspace = true +serde_json.workspace = true [dev-dependencies] serde_json.workspace = true diff --git a/crates/core/src/drm_free.rs b/crates/core/src/drm_free.rs index 876b6996d..87a4eaaec 100644 --- a/crates/core/src/drm_free.rs +++ b/crates/core/src/drm_free.rs @@ -323,6 +323,81 @@ pub enum LocalError { /// carries the map instead of `Registration`. Recipe arguments keep their order: the user's own /// arguments follow them. pub type LaunchEnvironment = std::collections::BTreeMap; +/// Explicit launch-time environment changes. Unset keys override `set` validation and may not +/// overlap it; inherited variables stay untouched unless named here. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct LaunchEnvironmentDelta { + pub set: LaunchEnvironment, + pub unset: std::collections::BTreeSet, +} + +impl LaunchEnvironmentDelta { + pub fn is_empty(&self) -> bool { + self.set.is_empty() && self.unset.is_empty() + } + + pub fn validate(&self) -> bool { + let valid_key = |key: &str| { + let upper = key.to_ascii_uppercase(); + !key.is_empty() + && key.len() <= 256 + && key + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_') + && key + .as_bytes() + .first() + .is_some_and(|byte| byte.is_ascii_alphabetic() || *byte == b'_') + && !key.contains('=') + && !key.chars().any(|ch| ch == '\0' || ch.is_control()) + && ![ + "TOKEN", + "COOKIE", + "SECRET", + "PASSWORD", + "CREDENTIAL", + "AUTHORIZATION", + "SESSION", + "API_KEY", + "ACCESS_KEY", + "PRIVATE_KEY", + ] + .iter() + .any(|sensitive| upper.contains(sensitive)) + }; + let count = self.set.len() + self.unset.len(); + let bytes = self + .set + .iter() + .map(|(key, value)| key.len().saturating_add(value.len())) + .chain(self.unset.iter().map(String::len)) + .sum::(); + let names: std::collections::BTreeSet<_> = self + .set + .keys() + .chain(self.unset.iter()) + .map(|key| key.to_ascii_lowercase()) + .collect(); + count <= 128 + && bytes <= 64 * 1024 + && names.len() == count + && self.set.iter().all(|(key, value)| { + valid_key(key) && !value.chars().any(|ch| ch == '\0') && !self.unset.contains(key) + }) + && self.unset.iter().all(|key| valid_key(key)) + } +} + +/// Fully resolved executable command passed by a trusted host adapter. Plugin-facing opaque +/// handles must be resolved and approved before one of these values is constructed. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct CustomLaunchCommand { + pub executable: String, + pub file_identity: String, + pub arguments: Vec, + pub working_directory: String, + pub environment: LaunchEnvironmentDelta, +} /// Every method may block and must run on a worker. pub trait InstallationHost: Send + Sync { fn inspect(&self, executable: &str) -> Result; @@ -340,6 +415,11 @@ pub trait InstallationHost: Send + Sync { let _ = environment; self.launch(registration) } + /// Executes a host-resolved custom command. Adapters that cannot apply every field must + /// reject it explicitly instead of silently dropping arguments, cwd or environment changes. + fn launch_custom(&self, _command: &CustomLaunchCommand) -> Result<(), LocalError> { + Err(LocalError::Unsupported) + } fn validate_registration( &self, registration: &Registration, @@ -432,12 +512,56 @@ pub struct BackupReport { pub state: JobState, pub json: String, } + +/// Host-resolved backup context. It describes a real installation of any provider without +/// registering it as a manual game or changing its library identity. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct BackupTarget { + pub installation_id: String, + pub root: String, + pub gameplay: Vec, + /// Store installations use folder containment; manual games keep explicit gameplay paths. + pub track_folder: bool, +} + +/// A plugin backup uses a host-derived namespace, an approved save profile and a frozen target. +/// Callers of this internal port must never take paths or namespaces from the plugin request. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ScopedBackupRequest { + pub owner: String, + pub target: BackupTarget, + pub job_id: Option, + pub profile: SaveProfile, + pub destination: String, + pub operation: BackupOperation, +} + +/// Worker-side checks, including after previews and while the helper runs. Restore targets must +/// be checked against current approved roots/rules before recovery or replacement writes. +pub trait BackupAuthority: Send + Sync { + fn check(&self) -> Result<(), LocalError>; + fn validate_targets(&self, files: &[String], registry: &[String]) -> Result<(), LocalError>; +} + pub trait BackupEngine: Send + Sync { fn execute( &self, request: &BackupRequest, cancelled: &std::sync::atomic::AtomicBool, ) -> Result; + + fn scoped_available(&self) -> bool { + false + } + + fn execute_scoped( + &self, + _request: &ScopedBackupRequest, + _cancelled: &std::sync::atomic::AtomicBool, + _authority: &dyn BackupAuthority, + ) -> Result { + Err(LocalError::Unsupported) + } } #[cfg(test)] diff --git a/crates/core/src/library/actions.rs b/crates/core/src/library/actions.rs index 16643bbc4..407c96abe 100644 --- a/crates/core/src/library/actions.rs +++ b/crates/core/src/library/actions.rs @@ -20,6 +20,10 @@ pub enum Reason { NothingSelected, /// The action works on one game at a time. MultipleSelected, + /// The detected executable has not been approved by the user. + TargetNeedsApproval, + /// The detected target is missing or failed host validation; repair is available in details. + TargetUnavailable, /// The provider declares no launch rule. NoLaunchRule, NoInstallRule, @@ -129,6 +133,14 @@ impl LibraryMachine { let record = entry.record(); let play = if self.running.contains_key(key) { Availability::Disabled(Reason::Running) + } else if let Some(target) = entry.target.as_ref() { + if !target.available { + Availability::Disabled(Reason::TargetUnavailable) + } else if !target.approved { + Availability::Disabled(Reason::TargetNeedsApproval) + } else { + Availability::Available + } } else { rule( provider.is_some_and(|p| p.has_launch()), diff --git a/crates/core/src/library/actions/tests.rs b/crates/core/src/library/actions/tests.rs index 9716af075..3d7166a8d 100644 --- a/crates/core/src/library/actions/tests.rs +++ b/crates/core/src/library/actions/tests.rs @@ -88,6 +88,7 @@ fn a_game_marked_as_not_on_gamenode_cannot_be_added_but_its_choice_can_change() entry_key: "steam:70".to_owned(), game_id: None, chosen_at: 1, + source: Default::default(), }, ); select(&mut machine, &["steam:70"]); @@ -146,6 +147,7 @@ fn adding_a_multi_selection_needs_at_least_one_matched_game() { entry_key: "steam:70".to_owned(), game_id: None, chosen_at: 1, + source: Default::default(), }, ); // 70 is "no game"; add an unmatched one by removing 240's automatic match. diff --git a/crates/core/src/library/add_dialog/tests.rs b/crates/core/src/library/add_dialog/tests.rs index 0f063fa3d..f8a2067cf 100644 --- a/crates/core/src/library/add_dialog/tests.rs +++ b/crates/core/src/library/add_dialog/tests.rs @@ -45,6 +45,7 @@ pub(crate) fn library() -> LibraryMachine { let (mut machine, _) = loaded(false, cache); let op = machine.scan.as_ref().unwrap().op; machine.handle(Input::ProviderScanned { + targets: Default::default(), op, provider: "steam".to_owned(), result: Ok(games diff --git a/crates/core/src/library/add_run/tests.rs b/crates/core/src/library/add_run/tests.rs index 5eae9e3b2..42afe29a1 100644 --- a/crates/core/src/library/add_run/tests.rs +++ b/crates/core/src/library/add_run/tests.rs @@ -602,6 +602,7 @@ fn only_confirming_the_dialog_can_create_an_entry() { let lookups = step( &mut machine, Input::ProviderScanned { + targets: Default::default(), op, provider: "steam".to_owned(), result: Ok(vec![ diff --git a/crates/core/src/library/cover_queue/tests.rs b/crates/core/src/library/cover_queue/tests.rs index 0f4e001f7..bfb330711 100644 --- a/crates/core/src/library/cover_queue/tests.rs +++ b/crates/core/src/library/cover_queue/tests.rs @@ -49,6 +49,7 @@ fn library(n: u64, tweak: impl FnOnce(&mut Vec)) -> LibraryMachine { let (mut machine, _) = loaded(false, cache); let op = machine.scan.as_ref().unwrap().op; machine.handle(Input::ProviderScanned { + targets: Default::default(), op, provider: "steam".to_owned(), result: Ok(records), @@ -147,6 +148,7 @@ fn rescan(machine: &mut LibraryMachine, now: i64) -> Vec { machine.handle(Input::ScanRequested); let op = machine.scan.as_ref().unwrap().op; machine.handle(Input::ProviderScanned { + targets: Default::default(), op, provider: "steam".to_owned(), result: Ok(vec![record("100", "G100", "/g")]), @@ -220,6 +222,7 @@ fn a_failure_that_persisted_from_an_earlier_run_is_retried_after_a_scan() { machine.handle(Input::ScanRequested); let op = machine.scan.as_ref().unwrap().op; let effects = machine.handle(Input::ProviderScanned { + targets: Default::default(), op, provider: "steam".to_owned(), result: Ok(vec![record("100", "G100", "/g")]), diff --git a/crates/core/src/library/custom_launch.rs b/crates/core/src/library/custom_launch.rs new file mode 100644 index 000000000..e0b2d24aa --- /dev/null +++ b/crates/core/src/library/custom_launch.rs @@ -0,0 +1,460 @@ +//! Typed plugin-owned launch recipes. Plugin-provided text is data; only host-resolved handles may +//! become executable command paths. + +use crate::drm_free::{LaunchEnvironment, LaunchEnvironmentDelta}; +use serde::{Deserialize, Serialize}; +use std::collections::BTreeSet; + +pub const MAX_RECIPE_ARGUMENTS: usize = 128; +pub const MAX_RECIPE_ARGUMENT_BYTES: usize = 4096; +pub const MAX_RECIPE_TEXT_BYTES: usize = 128; +pub const MAX_RECIPE_MOD_LAYERS: usize = 32; + +/// A declared launch-time mod layer. The host cannot inspect mod files, so the identity and +/// version are plugin-provided text covered by the reviewed plan; the layer's argument and +/// environment contributions are host-validated and applied in declaration order. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CustomLaunchModLayer { + pub id: String, + #[serde(default)] + pub name: String, + pub version: String, + /// Changes whenever the plugin replaces this layer; a changed value requires new review. + pub revision: u64, + pub arguments: Vec, + pub environment_set: LaunchEnvironment, + pub environment_unset: BTreeSet, +} + +impl CustomLaunchModLayer { + pub fn environment(&self) -> LaunchEnvironmentDelta { + LaunchEnvironmentDelta { + set: self.environment_set.clone(), + unset: self.environment_unset.clone(), + } + } + + pub fn validate(&self) -> bool { + let text_ok = |value: &str| { + value.len() <= MAX_RECIPE_TEXT_BYTES && !value.chars().any(char::is_control) + }; + !self.id.is_empty() + && text_ok(&self.id) + && text_ok(&self.name) + && text_ok(&self.version) + && self.revision > 0 + && arguments_ok(&self.arguments) + && self.environment().validate() + } +} + +fn arguments_ok(arguments: &[String]) -> bool { + arguments.len() <= MAX_RECIPE_ARGUMENTS + && arguments + .iter() + .all(|argument| argument.len() <= MAX_RECIPE_ARGUMENT_BYTES && !argument.contains('\0')) +} + +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CustomLaunchRecipe { + /// Opaque id minted by Core when the recipe is proposed. + pub recipe_id: String, + /// Changes whenever the stored recipe is replaced. + pub revision: u64, + /// Package version that authored the recipe, copied from the authenticated caller. + #[serde(default)] + pub requester_package_version: String, + pub game_id: u64, + pub installation_id: String, + /// Revision of the detected target this recipe was based on. + pub base_target_revision: u64, + /// Fingerprint of the provider's effective launch action when this recipe was proposed. + #[serde(default)] + pub base_launch_fingerprint: u64, + /// Exactly one direct alternate executable handle or URI, unless a runtime wraps the default. + pub executable_handle: String, + /// Durable host-owned file reference captured from `executable_handle` when proposed. + /// It contains an approval id and relative path, never an absolute path or session token. + #[serde(default)] + pub executable: Option, + pub uri: String, + pub arguments: Vec, + pub working_directory_handle: String, + /// Durable host-owned file reference captured from `working_directory_handle` when proposed. + #[serde(default)] + pub working_directory: Option, + pub runtime_handle: String, + /// Stable selected-content identity when a runtime binding requires a content item. + #[serde(default)] + pub content_id: String, + pub environment_set: LaunchEnvironment, + pub environment_unset: BTreeSet, + /// Declared mod layers applied after the recipe arguments, in order. They are reviewed as + /// components and contribute their arguments/environment changes to the effective plan. + #[serde(default)] + pub mod_layers: Vec, +} + +impl CustomLaunchRecipe { + pub fn environment(&self) -> LaunchEnvironmentDelta { + LaunchEnvironmentDelta { + set: self.environment_set.clone(), + unset: self.environment_unset.clone(), + } + } + + /// The exact argument vector after applying declared mod layers in order. + pub fn effective_arguments(&self) -> Vec { + let mut arguments = self.arguments.clone(); + for layer in &self.mod_layers { + arguments.extend(layer.arguments.iter().cloned()); + } + arguments + } + + /// The exact environment delta after applying declared mod layers in order. A later layer + /// replaces an earlier `set` for the same key and removes a key it `unset`s. + pub fn effective_environment(&self) -> LaunchEnvironmentDelta { + let mut environment = self.environment(); + for layer in &self.mod_layers { + let layer = layer.environment(); + for (key, value) in layer.set { + environment.unset.remove(&key); + environment.set.insert(key, value); + } + for key in layer.unset { + environment.set.remove(&key); + environment.unset.insert(key); + } + } + environment + } + + pub fn validate(&self) -> bool { + let handle_ok = |value: &str| { + value.len() <= MAX_RECIPE_TEXT_BYTES + && !value.chars().any(|ch| ch.is_control() || ch == '\0') + }; + let has_executable = !self.executable_handle.is_empty() || self.executable.is_some(); + let has_uri = !self.uri.is_empty(); + // A ROM store has no detected executable/URI target. A runtime recipe is a complete + // launch on its own, so revision 0 means "no detected target" rather than invalid. + let runtime_recipe = !self.runtime_handle.is_empty() && !has_executable && !has_uri; + let effective_arguments = self.effective_arguments(); + let effective_environment = self.effective_environment(); + let parameter_overlay = !effective_arguments.is_empty() + || !effective_environment.is_empty() + || (!self.working_directory_handle.is_empty() || self.working_directory.is_some()); + let mut layer_ids = BTreeSet::new(); + if !handle_ok(&self.recipe_id) + || self.recipe_id.is_empty() + || self.revision == 0 + || self.requester_package_version.len() > 128 + || self.requester_package_version.chars().any(char::is_control) + || self.game_id == 0 + || !handle_ok(&self.installation_id) + || self.installation_id.is_empty() + || self.base_target_revision == 0 && !runtime_recipe + || self.base_launch_fingerprint == 0 + || !handle_ok(&self.executable_handle) + || !handle_ok(&self.working_directory_handle) + || !handle_ok(&self.runtime_handle) + || !handle_ok(&self.content_id) + || !arguments_ok(&self.arguments) + || self.mod_layers.len() > MAX_RECIPE_MOD_LAYERS + || self + .mod_layers + .iter() + .any(|layer| !layer.validate() || !layer_ids.insert(layer.id.as_str())) + || !arguments_ok(&effective_arguments) + || !effective_environment.validate() + || (!has_executable && !has_uri && self.runtime_handle.is_empty() && !parameter_overlay) + || (has_executable && has_uri) + || (!self.runtime_handle.is_empty() && has_executable) + || (!self.executable_handle.is_empty() && self.executable.is_some()) + || (!self.working_directory_handle.is_empty() && self.working_directory.is_some()) + || self + .executable + .as_ref() + .is_some_and(|reference| !reference.validate()) + || self + .working_directory + .as_ref() + .is_some_and(|reference| !reference.validate()) + { + return false; + } + if has_uri { + let target = super::target::TargetSpec::Uri { + uri: self.uri.clone(), + }; + // Custom fields are retained on the recipe and passed to UriOpener::open_custom. + // The platform adapter decides whether its handler can honor them and returns + // Unsupported when it cannot. A runtime wrapper has no meaning for a URI target. + return target.validate_shape() && self.runtime_handle.is_empty(); + } + has_executable || !self.runtime_handle.is_empty() || parameter_overlay + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn uri_recipe() -> CustomLaunchRecipe { + CustomLaunchRecipe { + recipe_id: "recipe-1".into(), + revision: 1, + requester_package_version: "1.0".into(), + game_id: 620, + installation_id: "install-1".into(), + base_target_revision: 3, + base_launch_fingerprint: 9, + executable_handle: String::new(), + executable: None, + uri: "steam://rungameid/620".into(), + arguments: vec!["--custom".into()], + working_directory_handle: "approved-cwd".into(), + working_directory: None, + runtime_handle: String::new(), + content_id: String::new(), + environment_set: [("CUSTOM_VALUE".into(), "value".into())].into(), + environment_unset: ["REMOVE_VALUE".into()].into(), + mod_layers: Vec::new(), + } + } + + fn mod_layer() -> CustomLaunchModLayer { + CustomLaunchModLayer { + id: "texture-hd".into(), + name: "HD texture layer".into(), + version: "1.2".into(), + revision: 3, + arguments: vec!["--mod=texture-hd".into()], + environment_set: [("MOD_LAYER".into(), "texture-hd".into())].into(), + environment_unset: ["VANILLA".into()].into(), + } + } + + #[test] + fn recipes_without_a_content_id_remain_compatible() { + let mut value = serde_json::to_value(uri_recipe()).unwrap(); + value.as_object_mut().unwrap().remove("contentId"); + let recipe: CustomLaunchRecipe = serde_json::from_value(value).unwrap(); + assert!(recipe.content_id.is_empty()); + } + + #[test] + fn durable_file_references_round_trip_without_session_handles() { + let recipe = CustomLaunchRecipe { + recipe_id: "recipe-1".into(), + revision: 1, + requester_package_version: "1.0".into(), + game_id: 620, + installation_id: "install-1".into(), + base_target_revision: 3, + base_launch_fingerprint: 9, + executable_handle: String::new(), + executable: Some(super::super::ApprovedFileReference { + approval_id: "approval-1".into(), + relative_path: vec!["bin".into(), "game.exe".into()], + }), + uri: String::new(), + arguments: vec!["--custom".into()], + working_directory_handle: String::new(), + working_directory: Some(super::super::ApprovedFileReference { + approval_id: "approval-1".into(), + relative_path: vec!["bin".into()], + }), + runtime_handle: String::new(), + content_id: String::new(), + environment_set: Default::default(), + environment_unset: Default::default(), + mod_layers: Vec::new(), + }; + assert!(recipe.validate()); + let serialized = serde_json::to_string(&recipe).unwrap(); + assert!(!serialized.contains("C:\\")); + assert!(recipe.executable_handle.is_empty()); + assert!(recipe.working_directory_handle.is_empty()); + assert_eq!( + serde_json::from_str::(&serialized).unwrap(), + recipe + ); + } + + #[test] + fn uri_customization_is_retained_for_the_uri_handler_to_accept_or_reject() { + assert!(uri_recipe().validate()); + } + + #[test] + fn uri_recipe_cannot_also_select_an_external_runtime() { + let mut recipe = uri_recipe(); + recipe.runtime_handle = "runtime-handle".into(); + assert!(!recipe.validate()); + } + + #[test] + fn uri_recipe_cannot_also_select_an_executable() { + let mut recipe = uri_recipe(); + recipe.executable_handle = "executable-handle".into(); + assert!(!recipe.validate()); + } + + #[test] + fn a_runtime_recipe_can_launch_an_entry_without_a_detected_target() { + let mut recipe = CustomLaunchRecipe { + runtime_handle: "runtime-handle".into(), + content_id: "content-1".into(), + ..CustomLaunchRecipe::default() + }; + recipe.recipe_id = "recipe-1".into(); + recipe.revision = 1; + recipe.game_id = 620; + recipe.installation_id = "install-1".into(); + recipe.base_target_revision = 0; + recipe.base_launch_fingerprint = 9; + assert!( + recipe.validate(), + "a runtime is a complete launch for a ROM store with no detected target" + ); + + recipe.runtime_handle.clear(); + assert!( + !recipe.validate(), + "without a runtime there is nothing to launch at revision 0" + ); + } + + #[test] + fn parameter_only_recipe_uses_the_detected_target_without_a_target_field() { + let mut recipe = CustomLaunchRecipe { + arguments: vec!["--windowed".into()], + environment_set: [("GAME_PROFILE".into(), "fixture".into())].into(), + ..CustomLaunchRecipe::default() + }; + recipe.recipe_id = "recipe-1".into(); + recipe.revision = 1; + recipe.game_id = 620; + recipe.installation_id = "install-1".into(); + recipe.base_target_revision = 3; + recipe.base_launch_fingerprint = 9; + assert!(recipe.validate()); + + recipe.arguments.clear(); + recipe.environment_set.clear(); + assert!( + !recipe.validate(), + "an empty overlay is not a customization" + ); + } + + #[test] + fn mod_layers_apply_in_order_and_bind_their_own_revision() { + let mut recipe = CustomLaunchRecipe { + arguments: vec!["--game".into()], + environment_set: [("MODE".into(), "base".into()), ("DROP".into(), "1".into())].into(), + mod_layers: vec![ + mod_layer(), + CustomLaunchModLayer { + id: "second".into(), + name: String::new(), + version: "0.1".into(), + revision: 1, + arguments: vec!["--second".into()], + environment_set: [("MODE".into(), "layered".into())].into(), + environment_unset: ["DROP".into()].into(), + }, + ], + ..CustomLaunchRecipe::default() + }; + recipe.recipe_id = "recipe-1".into(); + recipe.revision = 1; + recipe.game_id = 620; + recipe.installation_id = "install-1".into(); + recipe.base_target_revision = 3; + recipe.base_launch_fingerprint = 9; + assert!(recipe.validate()); + assert_eq!( + recipe.effective_arguments(), + ["--game", "--mod=texture-hd", "--second"] + ); + let environment = recipe.effective_environment(); + assert_eq!(environment.set["MODE"], "layered"); + assert_eq!(environment.set["MOD_LAYER"], "texture-hd"); + assert!(!environment.set.contains_key("DROP")); + assert!(environment.unset.contains("VANILLA")); + assert!(environment.unset.contains("DROP")); + assert!(environment.validate()); + + let mut changed = recipe.clone(); + changed.mod_layers[0].revision += 1; + assert!(changed.validate()); + assert_eq!(changed.effective_arguments(), recipe.effective_arguments()); + } + + #[test] + fn mod_layer_validation_rejects_duplicates_and_target_conflicts() { + let mut recipe = CustomLaunchRecipe { + mod_layers: vec![mod_layer(), mod_layer()], + ..CustomLaunchRecipe::default() + }; + recipe.recipe_id = "recipe-1".into(); + recipe.revision = 1; + recipe.game_id = 620; + recipe.installation_id = "install-1".into(); + recipe.base_target_revision = 3; + recipe.base_launch_fingerprint = 9; + assert!(!recipe.validate()); + + recipe.mod_layers = vec![mod_layer()]; + recipe.uri = "steam://rungameid/620".into(); + assert!(recipe.validate()); + recipe.runtime_handle = "runtime-handle".into(); + assert!(!recipe.validate()); + } + + #[test] + fn recipes_without_mod_layers_remain_compatible() { + let mut value = serde_json::to_value(uri_recipe()).unwrap(); + value.as_object_mut().unwrap().remove("modLayers"); + let recipe: CustomLaunchRecipe = serde_json::from_value(value).unwrap(); + assert!(recipe.mod_layers.is_empty()); + } +} + +/// Result of a revision-checked recipe mutation. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum CustomLaunchMutation { + Applied { revision: u64 }, + Conflict { current: u64 }, + Missing, +} + +/// The user's active custom launch choice for one library entry. No row means the detected +/// default is selected. A stale row remains present so Play can ask for an explicit repair or +/// return to the detected default instead of silently switching routes. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct LaunchRecipeSelection { + pub entry_key: String, + pub owner_key: String, + pub plugin_id: String, + pub publisher_fingerprint: String, + pub recipe_id: String, + pub recipe_revision: u64, + pub base_target_revision: u64, + /// The exact reviewed plan. Empty until the user approves a resolved plan. + pub approved_plan_fingerprint: String, +} + +/// Compare-and-set result when changing the user's active launch recipe. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum LaunchRecipeSelectionWrite { + Applied, + Conflict, + RecipeMissing, +} diff --git a/crates/core/src/library/launch.rs b/crates/core/src/library/launch.rs index 2061d0f7d..ce4864611 100644 --- a/crates/core/src/library/launch.rs +++ b/crates/core/src/library/launch.rs @@ -27,6 +27,10 @@ pub enum LaunchError { /// The store client is not installed or registered. #[error("the store application is not available")] NoHandler, + /// A selected custom recipe, its approval or one of its resources changed or was revoked. + /// The user can choose another recipe or explicitly return to the detected default. + #[error("the selected custom launch recipe needs attention")] + RecipeNeedsAttention, #[error("the link could not be opened")] Failed, } @@ -67,6 +71,7 @@ pub fn open_action( ActionError::Fill(_) => LaunchError::Incomplete, })?; opener.open(&uri).map_err(|error| match error { + UriError::Unsupported => LaunchError::Unsupported, UriError::NoHandler => LaunchError::NoHandler, UriError::Failed => LaunchError::Failed, }) diff --git a/crates/core/src/library/launch/tests.rs b/crates/core/src/library/launch/tests.rs index b8d685abd..2b30b80e9 100644 --- a/crates/core/src/library/launch/tests.rs +++ b/crates/core/src/library/launch/tests.rs @@ -37,6 +37,30 @@ fn play_opens_the_launch_uri_and_install_the_install_uri() { ); } +#[test] +fn uri_handlers_reject_execution_fields_they_cannot_apply() { + let opener = FakeOpener::default(); + let uri = Url::parse("steam://rungameid/620").unwrap(); + let environment = crate::drm_free::LaunchEnvironmentDelta { + set: [("CUSTOM_VALUE".into(), "value".into())].into(), + unset: Default::default(), + }; + + assert_eq!( + opener.open_custom(&uri, &["--custom".into()], "", &Default::default()), + Err(UriError::Unsupported) + ); + assert_eq!( + opener.open_custom(&uri, &[], "C:\\Games", &Default::default()), + Err(UriError::Unsupported) + ); + assert_eq!( + opener.open_custom(&uri, &[], "", &environment), + Err(UriError::Unsupported) + ); + assert!(opener.opened.lock().unwrap().is_empty()); +} + #[test] fn ids_are_encoded_so_they_cannot_change_the_uri() { let opener = FakeOpener::default(); diff --git a/crates/core/src/library/launch_plan.rs b/crates/core/src/library/launch_plan.rs new file mode 100644 index 000000000..f8459ce8b --- /dev/null +++ b/crates/core/src/library/launch_plan.rs @@ -0,0 +1,332 @@ +//! Immutable host-resolved launch plans and their versioned approval fingerprints. +//! +//! Fingerprints use an explicit field encoding. They never depend on protobuf/JSON serialization +//! order and include the literal effective target, argv, working directory, environment delta, +//! requester/package identity, ordered components, resource revisions and current grant revision. + +use crate::drm_free::LaunchEnvironmentDelta; +use sha2::{Digest, Sha256}; +pub const LAUNCH_PLAN_VERSION: u32 = 1; +const FINGERPRINT_DOMAIN: &[u8] = b"gamenode.launch-plan.approval.v1\0"; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct LaunchPlan { + pub version: u32, + pub game_id: String, + pub installation_id: String, + pub profile_id: String, + /// Store/provider identity or `manual`; never a plugin supplied display label. + pub source_id: String, + pub requester_plugin_id: String, + pub requester_publisher: String, + pub requester_package_version: String, + pub target_revision: u64, + pub recipe_id: String, + pub recipe_revision: u64, + pub grant_revision: u64, + pub target: LaunchPlanTarget, + /// Execution order is meaningful and therefore preserved in the canonical form. + pub components: Vec, + /// Resource identities/revisions are sorted by resource id in the canonical form. + pub resources: Vec, + pub arguments: Vec, + pub working_directory: String, + pub environment: LaunchEnvironmentDelta, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum LaunchPlanTarget { + Detected { + fingerprint: u64, + }, + Uri { + uri: String, + handler: Option, + }, + Executable { + path: String, + file_identity: String, + }, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct LaunchPlanComponent { + pub kind: String, + pub id: String, + pub owner_plugin_id: String, + pub owner_publisher: String, + pub version: String, + pub revision: u64, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct LaunchPlanResource { + pub id: String, + pub revision: u64, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)] +pub enum LaunchPlanError { + #[error("the launch plan is invalid")] + Invalid, +} + +impl LaunchPlan { + pub fn validate(&self) -> bool { + let text = |value: &str, max: usize| { + !value.is_empty() + && value.len() <= max + && !value.chars().any(|ch| ch == '\0' || ch.is_control()) + }; + self.version == LAUNCH_PLAN_VERSION + && self.game_id.len() <= 128 + && !self.game_id.chars().any(char::is_control) + && text(&self.installation_id, 128) + && text(&self.profile_id, 256) + && text(&self.source_id, 256) + && text(&self.requester_plugin_id, 256) + && text(&self.requester_publisher, 256) + && text(&self.requester_package_version, 128) + && match &self.target { + LaunchPlanTarget::Detected { .. } => true, + LaunchPlanTarget::Uri { uri, handler } => { + text(uri, 4096) && handler.as_ref().is_none_or(|handler| text(handler, 1024)) + } + LaunchPlanTarget::Executable { + path, + file_identity, + } => text(path, 4096) && text(file_identity, 1024), + } + && self.components.len() <= 128 + && self.components.iter().all(|component| { + text(&component.kind, 128) + && text(&component.id, 512) + && text(&component.owner_plugin_id, 256) + && text(&component.owner_publisher, 256) + && component.version.len() <= 256 + && !component.version.chars().any(char::is_control) + }) + && self.resources.len() <= 128 + && self + .resources + .iter() + .all(|resource| text(&resource.id, 512) && resource.revision > 0) + && self.arguments.len() <= 256 + && self + .arguments + .iter() + .all(|argument| argument.len() <= 16 * 1024 && !argument.contains('\0')) + && self.working_directory.len() <= 4096 + && !self.working_directory.contains('\0') + && self.environment.validate() + } + + /// A lowercase SHA-256 digest with the canonical encoding version in its prefix. + pub fn fingerprint(&self) -> Result { + if !self.validate() { + return Err(LaunchPlanError::Invalid); + } + let mut hash = Sha256::new(); + hash.update(FINGERPRINT_DOMAIN); + number(&mut hash, self.version as u64); + for field in [ + self.game_id.as_str(), + self.installation_id.as_str(), + self.profile_id.as_str(), + self.source_id.as_str(), + self.requester_plugin_id.as_str(), + self.requester_publisher.as_str(), + self.requester_package_version.as_str(), + ] { + part(&mut hash, field.as_bytes()); + } + number(&mut hash, self.target_revision); + part(&mut hash, self.recipe_id.as_bytes()); + number(&mut hash, self.recipe_revision); + number(&mut hash, self.grant_revision); + match &self.target { + LaunchPlanTarget::Detected { fingerprint } => { + part(&mut hash, b"detected"); + number(&mut hash, *fingerprint); + } + LaunchPlanTarget::Uri { uri, handler } => { + part(&mut hash, b"uri"); + part(&mut hash, uri.as_bytes()); + optional(&mut hash, handler.as_deref()); + } + LaunchPlanTarget::Executable { + path, + file_identity, + } => { + part(&mut hash, b"executable"); + part(&mut hash, path.as_bytes()); + part(&mut hash, file_identity.as_bytes()); + } + } + number(&mut hash, self.components.len() as u64); + for component in &self.components { + for field in [ + component.kind.as_str(), + component.id.as_str(), + component.owner_plugin_id.as_str(), + component.owner_publisher.as_str(), + component.version.as_str(), + ] { + part(&mut hash, field.as_bytes()); + } + number(&mut hash, component.revision); + } + let mut resources = self.resources.iter().collect::>(); + resources.sort_by(|left, right| { + left.id + .cmp(&right.id) + .then_with(|| left.revision.cmp(&right.revision)) + }); + number(&mut hash, resources.len() as u64); + for resource in resources { + part(&mut hash, resource.id.as_bytes()); + number(&mut hash, resource.revision); + } + number(&mut hash, self.arguments.len() as u64); + for argument in &self.arguments { + part(&mut hash, argument.as_bytes()); + } + part(&mut hash, self.working_directory.as_bytes()); + number(&mut hash, self.environment.set.len() as u64); + for (key, value) in &self.environment.set { + part(&mut hash, key.as_bytes()); + part(&mut hash, value.as_bytes()); + } + number(&mut hash, self.environment.unset.len() as u64); + for key in &self.environment.unset { + part(&mut hash, key.as_bytes()); + } + let digest = hash.finalize(); + let hex = digest + .iter() + .map(|byte| format!("{byte:02x}")) + .collect::(); + Ok(format!("v{}:{hex}", self.version)) + } +} + +fn part(hash: &mut Sha256, bytes: &[u8]) { + number(hash, bytes.len() as u64); + hash.update(bytes); +} + +fn number(hash: &mut Sha256, value: u64) { + hash.update(value.to_be_bytes()); +} + +fn optional(hash: &mut Sha256, value: Option<&str>) { + match value { + Some(value) => { + hash.update([1]); + part(hash, value.as_bytes()); + } + None => hash.update([0]), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::collections::{BTreeMap, BTreeSet}; + + fn plan() -> LaunchPlan { + LaunchPlan { + version: LAUNCH_PLAN_VERSION, + game_id: "42".into(), + installation_id: "steam-install".into(), + profile_id: "profile-a".into(), + source_id: "steam".into(), + requester_plugin_id: "org.example.runtime".into(), + requester_publisher: "publisher-a".into(), + requester_package_version: "1.2.3".into(), + target_revision: 7, + recipe_id: "recipe-a".into(), + recipe_revision: 3, + grant_revision: 8, + target: LaunchPlanTarget::Executable { + path: "/games/example/wrapper".into(), + file_identity: "volume:inode".into(), + }, + components: vec![LaunchPlanComponent { + kind: "runtime".into(), + id: "runtime-a".into(), + owner_plugin_id: "org.example.runtime".into(), + owner_publisher: "publisher-a".into(), + version: "4.0".into(), + revision: 2, + }], + resources: vec![LaunchPlanResource { + id: "approval-a".into(), + revision: 1, + }], + arguments: vec!["--profile".into(), "Two Words".into()], + working_directory: "/games/example".into(), + environment: LaunchEnvironmentDelta { + set: BTreeMap::from([("MODE".into(), "performance".into())]), + unset: BTreeSet::from(["REMOVE_ME".into()]), + }, + } + } + + #[test] + fn fingerprint_is_stable_and_versioned() { + let fingerprint = plan().fingerprint().unwrap(); + assert!(fingerprint.starts_with("v1:")); + assert_eq!(plan().fingerprint().unwrap(), fingerprint); + } + + #[test] + fn every_approval_sensitive_field_changes_the_fingerprint() { + let original = plan().fingerprint().unwrap(); + let mut variants = Vec::new(); + let mut changed = plan(); + changed.arguments.reverse(); + variants.push(changed); + let mut changed = plan(); + changed + .environment + .set + .insert("MODE".into(), "quiet".into()); + variants.push(changed); + let mut changed = plan(); + changed.components[0].revision += 1; + variants.push(changed); + let mut changed = plan(); + changed.resources[0].revision += 1; + variants.push(changed); + let mut changed = plan(); + changed.grant_revision += 1; + variants.push(changed); + let mut changed = plan(); + changed.requester_package_version.push_str("+build2"); + variants.push(changed); + let mut changed = plan(); + changed.target = LaunchPlanTarget::Uri { + uri: "steam://rungameid/42".into(), + handler: None, + }; + variants.push(changed); + assert!( + variants + .iter() + .all(|variant| variant.fingerprint().unwrap() != original) + ); + } + + #[test] + fn resource_input_order_does_not_change_the_fingerprint() { + let mut first = plan(); + first.resources.push(LaunchPlanResource { + id: "approval-b".into(), + revision: 9, + }); + let mut second = first.clone(); + second.resources.reverse(); + assert_eq!(first.fingerprint().unwrap(), second.fingerprint().unwrap()); + } +} diff --git a/crates/core/src/library/lookup/tests.rs b/crates/core/src/library/lookup/tests.rs index 6e2cf602e..e0124229f 100644 --- a/crates/core/src/library/lookup/tests.rs +++ b/crates/core/src/library/lookup/tests.rs @@ -58,6 +58,7 @@ fn verified() -> (LibraryMachine, (u64, u32, Vec)) { }); let op = machine.scan.as_ref().expect("scan running").op; let effects = machine.handle(Input::ProviderScanned { + targets: Default::default(), op, provider: "steam".to_owned(), result: Ok(vec![ @@ -105,6 +106,7 @@ fn nothing_is_looked_up_without_a_verified_session() { machine.handle(Input::SetAccess { access, now: NOW }); let op = machine.scan.as_ref().unwrap().op; let effects = machine.handle(Input::ProviderScanned { + targets: Default::default(), op, provider: "steam".to_owned(), result: Ok(vec![record("620", "Portal 2", "/games/Portal 2")]), @@ -271,6 +273,7 @@ fn a_rescan_that_adds_a_game_asks_only_about_the_new_id() { machine.handle(Input::ScanRequested); let op = machine.scan.as_ref().unwrap().op; let effects = machine.handle(Input::ProviderScanned { + targets: Default::default(), op, provider: "steam".to_owned(), result: Ok(vec![ @@ -297,6 +300,7 @@ fn an_uninstalled_game_is_not_looked_up() { }); let op = machine.scan.as_ref().unwrap().op; let effects = machine.handle(Input::ProviderScanned { + targets: Default::default(), op, provider: "steam".to_owned(), result: Ok(vec![record("620", "Portal 2", "/g")]), @@ -322,6 +326,7 @@ fn a_manual_pick_survives_any_lookup_result() { entry_key: entry_key("steam", "620"), game_id: Some(42), chosen_at: NOW, + source: Default::default(), }, ); done(&mut machine, &ask, Ok(result), NOW + 1); @@ -344,6 +349,7 @@ fn no_game_stays_no_game_after_a_lookup_finds_one() { entry_key: entry_key("steam", "620"), game_id: None, chosen_at: NOW, + source: Default::default(), }, ); done( @@ -444,6 +450,7 @@ fn owned_only_and_shared_games_are_looked_up() { }); let op = machine.scan.as_ref().unwrap().op; let effects = machine.handle(Input::ProviderScanned { + targets: Default::default(), op, provider: "steam".to_owned(), result: Ok(vec![]), @@ -521,6 +528,7 @@ fn a_declared_field_is_the_lookup_uid_and_covers_every_entry_with_it() { let op = machine.scan.as_ref().expect("scan running").op; let effects = machine.handle(Input::ProviderScanned { + targets: Default::default(), op, provider: "steam".to_owned(), result: Ok(vec![]), @@ -528,6 +536,7 @@ fn a_declared_field_is_the_lookup_uid_and_covers_every_entry_with_it() { }); assert!(lookups(&effects).is_empty(), "no steam entry to ask about"); let effects = machine.handle(Input::ProviderScanned { + targets: Default::default(), op, provider: "fixture".to_owned(), result: Ok(vec![ @@ -592,12 +601,14 @@ fn an_entry_without_the_declared_field_is_skipped() { }); let op = machine.scan.as_ref().expect("scan running").op; machine.handle(Input::ProviderScanned { + targets: Default::default(), op, provider: "steam".to_owned(), result: Ok(vec![]), now: NOW, }); let effects = machine.handle(Input::ProviderScanned { + targets: Default::default(), op, provider: "fixture".to_owned(), result: Ok(vec![record("app3", "No namespace", "/games/fixture")]), @@ -618,12 +629,14 @@ fn a_second_entry_with_a_known_namespace_does_not_ask_again() { }); let op = machine.scan.as_ref().expect("scan running").op; machine.handle(Input::ProviderScanned { + targets: Default::default(), op, provider: "steam".to_owned(), result: Ok(vec![]), now: NOW, }); let effects = machine.handle(Input::ProviderScanned { + targets: Default::default(), op, provider: "fixture".to_owned(), result: Ok(vec![namespaced("app1", "ns1")]), @@ -635,12 +648,14 @@ fn a_second_entry_with_a_known_namespace_does_not_ask_again() { machine.handle(Input::ScanRequested); let op = machine.scan.as_ref().expect("scan running").op; machine.handle(Input::ProviderScanned { + targets: Default::default(), op, provider: "steam".to_owned(), result: Ok(vec![]), now: NOW + 2, }); let effects = machine.handle(Input::ProviderScanned { + targets: Default::default(), op, provider: "fixture".to_owned(), result: Ok(vec![namespaced("app1", "ns1"), namespaced("app2", "ns1")]), diff --git a/crates/core/src/library/machine.rs b/crates/core/src/library/machine.rs index 479f6b496..3b29563ef 100644 --- a/crates/core/src/library/machine.rs +++ b/crates/core/src/library/machine.rs @@ -36,9 +36,9 @@ use super::organization::{ }; use super::selection::{Direction, SelectMode, Selection}; use super::store::{ - AccountLibrary, AutoMatch, CatalogError, CatalogRecord, CatalogUpdate, ChosenMatch, - FavoriteRecord, GameRecord, LastAccount, LibraryCache, ProviderScanState, StoredEntry, - entry_key, + AccountLibrary, ArtworkOverride, AutoMatch, CatalogError, CatalogRecord, CatalogUpdate, + ChosenMatch, DisplayOverride, FavoriteRecord, GameRecord, LastAccount, LibraryCache, + ProviderScanState, StoredEntry, entry_key, }; use super::suggest::SuggestionView; use super::view::{LibraryView, ScanProgress, ScanProgressState}; @@ -62,7 +62,11 @@ pub enum Access { #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub enum ScanOutcome { - Scanned(Vec), + Scanned { + records: Vec, + /// The detected launch target of each record id, if any (task 7.7). + targets: std::collections::BTreeMap, + }, /// The provider's roots could not be read. The message is for the log and the detail view. Failed(String), } @@ -270,9 +274,19 @@ pub enum Input { op: u64, provider: String, result: Result, String>, + /// The detected launch target of each record id, if any (task 7.7). + #[allow(clippy::type_complexity)] + targets: std::collections::BTreeMap, /// Unix seconds. now: i64, }, + /// The user approved or repaired the detected target of one entry. The host writes the + /// target first and reports the stored value. + TargetReviewed { + entry_key: String, + expected_revision: u64, + target: super::target::DetectedTarget, + }, /// Where a scan looked, reported with its successful answer before [`Input::ProviderScanned`]. /// A scan that reports no location clears the previous one for that provider. ProviderLocated { @@ -306,36 +320,50 @@ pub enum Input { RequestCatalog, /// Replace the toolbar filters. SetFilters(LibraryFilters), + /// A plugin's display-name override of an entry was stored (or cleared with `None`) at this + /// revision. Applies only to entries the library knows. + DisplayNameStored { + key: String, + display_name: Option, + revision: u64, + }, + /// A plugin's artwork override of an entry was stored (or cleared with `None`) at this revision. + ArtworkStored { + key: String, + file: Option, + revision: u64, + }, + /// A plugin's catalog search returned these games; they can now be assigned to its entries. + CatalogSearched { + games: Vec, + }, + /// Match a plugin's own entry to a game (`plan_plugin_match` decides). + AssignPluginMatch { + key: String, + game_id: u64, + now: i64, + }, /// Save the effective scope, filters, sort, grouping and view mode as a named view. SaveView { name: String, }, - /// Rename one saved view. Its payload and position do not change. RenameView { id: i64, name: String, }, - /// Delete one saved view. When it is the highlighted one, the layout keeps the payload's - /// effective scope, filters, sort, grouping and view mode. DeleteView { id: i64, }, - /// Apply one saved view and highlight it. The payload becomes the layout; the scope marker is - /// only the highlight until the payload changes again. ApplyView { id: i64, }, - /// Hide or reveal library keys for the account. Hiding never removes matches, favorites, - /// playtime or GameNode data; it only leaves the normal view and counts. SetHidden { keys: Vec, hidden: bool, }, - /// The answer to [`Effect::PersistView`]: the database id of the inserted or updated view. ViewPersisted { op: u64, account_id: String, - /// `Err` keeps the previous list: the write did not happen. result: Result, }, /// Mark or unmark the entry's matched game as a favorite. `now` is unix seconds. @@ -379,6 +407,11 @@ pub enum Input { CloseMatch, /// The dialog's search text changed. Nothing is sent until [`Input::SearchMatch`]. SetMatchQuery(String), + /// Narrow the dialog's candidates and results to the entry's declared platform, or show the + /// complete answer again. The already-received answer is filtered locally; nothing is sent. + SetMatchPlatformFilter { + enabled: bool, + }, SearchMatch, MatchSearched { op: u64, @@ -694,6 +727,10 @@ pub struct LibraryMachine { pub(super) auto_matches: BTreeMap<(u32, String), AutoMatch>, pub(super) chosen: BTreeMap, pub(super) games: BTreeMap, + /// Presentation overrides by entry key, written by the entry's own provider plugin. + pub(super) display_overrides: BTreeMap, + /// Cover overrides by entry key, written by the entry's own provider plugin. + pub(super) artwork_overrides: BTreeMap, pub(super) scan: Option, pub(super) rescan_pending: bool, pub(super) layout: LibraryLayout, @@ -748,6 +785,8 @@ pub struct LibraryMachine { pub(super) lookups: BTreeMap, /// The match dialog, while it is open. pub(super) dialog: Option, + /// Games plugin searches offered, still open for assignment (bounded, oldest first). + pub(super) offered: super::plugin_match::Offered, pub(super) covers: CoverQueue, /// Artwork is loaded on demand; the engine checks its disk cache before downloading. pub(super) artwork_focus: Option, @@ -798,6 +837,8 @@ impl LibraryMachine { auto_matches: BTreeMap::new(), chosen: BTreeMap::new(), games: BTreeMap::new(), + display_overrides: BTreeMap::new(), + artwork_overrides: BTreeMap::new(), scan: None, rescan_pending: false, layout: layout.normalized(), @@ -826,6 +867,7 @@ impl LibraryMachine { last_collection_run: None, lookups: BTreeMap::new(), dialog: None, + offered: Default::default(), covers: CoverQueue::default(), artwork_focus: None, artwork_requests: BTreeMap::new(), @@ -850,6 +892,71 @@ impl LibraryMachine { self.providers.iter().find(|provider| provider.id() == id) } + /// Adds one provider to the scan list, or replaces the entry with the same id in place. + /// + /// This is the post-startup registration path for an accepted import: stored entries, + /// matches, settings and the running scan are untouched, and the provider keeps its existing + /// position when it was already known. Callers request a scan afterwards; a scan already + /// running coalesces that request into one more run. Returns whether the list changed. + pub fn put_provider(&mut self, provider: Provider) -> bool { + if let Some(existing) = self + .providers + .iter_mut() + .find(|existing| existing.id() == provider.id()) + { + *existing = provider; + } else { + self.providers.push(provider); + } + self.view_dirty = true; + true + } + + /// Removes one provider and its live entries after an accepted uninstall. + /// + /// Persisted rows stay in the account cache for a later reinstall; the provider's scan state + /// and pending slot in a running scan are dropped so a late answer cannot bring it back. A + /// subsequent import calls [`Self::put_provider`] and requests a scan, which repopulates the + /// rows. Returns whether the provider was loaded. + pub fn remove_provider(&mut self, id: &str) -> bool { + let before = self.providers.len(); + self.providers.retain(|provider| provider.id() != id); + if self.providers.len() == before { + return false; + } + self.entries.retain(|_, entry| entry.provider != id); + self.scans.remove(id); + self.scan_progress.remove(id); + if let Some(run) = &mut self.scan { + run.waiting.remove(id); + if run.waiting.is_empty() { + self.scan = None; + } + } + self.view_dirty = true; + true + } + + /// Removes the provider a plugin package contributes after an accepted uninstall. + /// + /// The installed plugin id is not necessarily the provider id: a package such as + /// `dev.example.dolphin-emu` can contribute `dolphin-emu`. The composed provider records the + /// package as its discovery plugin, so uninstall resolves the store through that instead of + /// assuming both ids match. Returns whether a provider was loaded. + pub fn remove_provider_for_plugin(&mut self, plugin_id: &str) -> bool { + let providers: Vec = self + .providers + .iter() + .filter(|provider| provider.discovery_plugin() == Some(plugin_id)) + .map(|provider| provider.id().to_owned()) + .collect(); + let mut removed = false; + for provider in providers { + removed |= self.remove_provider(&provider); + } + removed + } + /// Whether the library is shown (an account is set, even before it is verified). pub fn is_active(&self) -> bool { !matches!(self.phase, Phase::Inactive) @@ -918,18 +1025,6 @@ impl LibraryMachine { self.entries.get(key) } - /// The cover file one entry's row resolves to: a DRM-free custom cover first, then the - /// matched GameNode cover. `None` when the entry is unknown or has no cover. - pub fn cover_for(&self, key: &str) -> Option { - let entry = self.entries.get(key)?; - let game_cover = self - .match_status(entry) - .game_id() - .and_then(|game_id| self.games.get(&game_id)) - .and_then(|game| game.cover_file.clone()); - self.local_covers.get(key).cloned().or(game_cover) - } - /// The playtime recorded for one entry, if the selected source knows any. pub fn playtime_for(&self, key: &str) -> Option { self.playtime.get(key).copied() @@ -947,6 +1042,7 @@ impl LibraryMachine { self.entries .values() .filter(|entry| entry.is_visible() && !self.excluded.contains(&entry.key)) + .filter(|entry| self.provider(&entry.provider).is_some()) } /// Whether the shared-games preference leaves this entry out: only entries that are shared @@ -973,6 +1069,18 @@ impl LibraryMachine { self.entries.values() } + /// The plugin-written display override of an entry, if one was ever written. A cleared + /// override stays here with no name, so its revision keeps counting. + pub fn display_override(&self, key: &str) -> Option<&DisplayOverride> { + self.display_overrides.get(key) + } + + /// The plugin-written cover override of an entry, if one was ever written. A cleared override + /// stays here with no file, so its revision keeps counting. + pub fn artwork_override(&self, key: &str) -> Option<&ArtworkOverride> { + self.artwork_overrides.get(key) + } + pub fn chosen_match(&self, key: &str) -> Option<&ChosenMatch> { self.chosen.get(key) } @@ -1098,8 +1206,25 @@ impl LibraryMachine { op, provider, result, + targets, now, - } => self.on_provider_scanned(op, provider, result, now), + } => self.on_provider_scanned(op, provider, result, targets, now), + Input::TargetReviewed { + entry_key, + expected_revision, + target, + } => { + if let Some(entry) = self.entries.get_mut(&entry_key) + && entry + .target + .as_ref() + .is_some_and(|current| current.revision == expected_revision) + { + entry.target = Some(target); + self.view_dirty = true; + } + vec![] + } Input::ProviderLocated { op, provider, @@ -1129,6 +1254,40 @@ impl LibraryMachine { let filters = filters.normalized(); self.update_layout(|layout| layout.filters = filters) } + Input::DisplayNameStored { + key, + display_name, + revision, + } => { + if self.entries.contains_key(&key) { + self.display_overrides.insert( + key.clone(), + DisplayOverride { + entry_key: key, + display_name, + revision, + }, + ); + } + vec![] + } + Input::ArtworkStored { + key, + file, + revision, + } => { + if self.entries.contains_key(&key) { + self.artwork_overrides.insert( + key.clone(), + ArtworkOverride { + entry_key: key, + file, + revision, + }, + ); + } + vec![] + } Input::SaveView { name } => self.save_view(name), Input::RenameView { id, name } => self.rename_view(id, name), Input::DeleteView { id } => self.delete_view(id), @@ -1197,6 +1356,14 @@ impl LibraryMachine { self.set_match_query(text); vec![] } + Input::SetMatchPlatformFilter { enabled } => self.set_match_platform_filter(enabled), + Input::CatalogSearched { games } => { + self.catalog_searched(games); + vec![] + } + Input::AssignPluginMatch { key, game_id, now } => { + self.assign_plugin_match(&key, game_id, now) + } Input::SearchMatch => self.search_match(), Input::MatchSearched { op, result } => self.on_match_searched(op, result), Input::SuggestionsFound { op, key, result } => { @@ -1612,6 +1779,16 @@ impl LibraryMachine { .map(|game| (game.game_id, game)) .collect(); self.excluded = cache.excluded.into_iter().collect(); + self.display_overrides = cache + .display_overrides + .into_iter() + .map(|over| (over.entry_key.clone(), over)) + .collect(); + self.artwork_overrides = cache + .artwork_overrides + .into_iter() + .map(|over| (over.entry_key.clone(), over)) + .collect(); self.saved_views = cache.saved_views; self.hidden = cache.hidden.into_iter().collect(); self.account_library = cache.account_library; @@ -1904,6 +2081,7 @@ impl LibraryMachine { install_dir: String::new(), fields: record.fields.clone(), installed: false, + target: None, owned: fact == CatalogFact::Owned, shared: fact == CatalogFact::Shared, first_seen: now, @@ -2004,8 +2182,14 @@ impl LibraryMachine { op: u64, provider: String, result: Result, String>, + targets: std::collections::BTreeMap, now: i64, ) -> Vec { + // An uninstalled provider is removed from the scan list and its pending slot; a late + // child answer must not repopulate rows the user just removed. + if self.provider(&provider).is_none() { + return vec![]; + } let Some(run) = &mut self.scan else { return vec![]; }; @@ -2034,7 +2218,7 @@ impl LibraryMachine { ); let outcome = match result { - Ok(records) => ScanOutcome::Scanned(records), + Ok(records) => ScanOutcome::Scanned { records, targets }, Err(message) => ScanOutcome::Failed(message), }; self.merge_scan(&provider, &outcome, now); @@ -2067,7 +2251,7 @@ impl LibraryMachine { ScanOutcome::Failed(message) => { state.last_error = Some(message.clone()); } - ScanOutcome::Scanned(records) => { + ScanOutcome::Scanned { records, targets } => { state.last_success_at = Some(now); state.last_error = None; // A successful scan with a location or any record proves the store is installed @@ -2079,6 +2263,11 @@ impl LibraryMachine { .filter(|entry| entry.provider == provider) { entry.installed = false; + // A target this scan no longer reports stays stored, so a later scan can + // offer repair, but it cannot launch while it is unavailable. + if let Some(target) = entry.target.take() { + entry.target = Some(super::target::DetectedTarget::missing(&target, now)); + } } for record in records { let key = entry_key(provider, &record.id); @@ -2087,6 +2276,13 @@ impl LibraryMachine { let (owned, shared) = existing .map(|entry| (entry.owned, entry.shared)) .unwrap_or_default(); + let target = targets.get(&record.id).map(|spec| { + super::target::DetectedTarget::reported( + existing.and_then(|entry| entry.target.as_ref()), + spec.clone(), + now, + ) + }); self.entries.insert( key.clone(), StoredEntry { @@ -2097,6 +2293,7 @@ impl LibraryMachine { install_dir: record.install_dir.clone(), fields: record.fields.clone(), installed: true, + target, owned, shared, first_seen, diff --git a/crates/core/src/library/machine/tests.rs b/crates/core/src/library/machine/tests.rs index 7cb1d0c35..e058dd4d2 100644 --- a/crates/core/src/library/machine/tests.rs +++ b/crates/core/src/library/machine/tests.rs @@ -59,6 +59,7 @@ pub(crate) fn stored_with( install_dir: format!("/games/{name}"), fields: Default::default(), installed, + target: None, owned, shared, first_seen: 100, @@ -145,6 +146,7 @@ pub(crate) fn scanned( now: i64, ) -> Vec { machine.handle(Input::ProviderScanned { + targets: Default::default(), op, provider: provider.to_owned(), result: result.map_err(str::to_owned), @@ -272,7 +274,10 @@ fn a_scan_adds_entries_and_persists_the_outcome() { effects, [Effect::PersistScan { provider: "steam".to_owned(), - outcome: ScanOutcome::Scanned(records), + outcome: ScanOutcome::Scanned { + records, + targets: Default::default() + }, now: 50 }] ); @@ -312,6 +317,7 @@ fn a_reinstalled_game_returns_with_its_match_and_cover() { entry_key: "steam:2".to_owned(), game_id: Some(42), chosen_at: 5, + source: Default::default(), }; let game = GameRecord { game_id: 42, @@ -355,6 +361,7 @@ fn a_moved_install_folder_keeps_the_entry() { entry_key: "steam:620".to_owned(), game_id: Some(7), chosen_at: 1, + source: Default::default(), }], ..LibraryCache::default() }; @@ -488,11 +495,13 @@ fn artwork_machine() -> LibraryMachine { entry_key: "steam:1".into(), game_id: Some(7), chosen_at: 0, + source: Default::default(), }, ChosenMatch { entry_key: "steam:2".into(), game_id: Some(8), chosen_at: 0, + source: Default::default(), }, ], ..LibraryCache::default() @@ -986,6 +995,7 @@ fn clearing_the_catalog_keeps_entries_matches_and_covers() { entry_key: "steam:70".to_owned(), game_id: Some(7), chosen_at: 3, + source: Default::default(), }; let game = GameRecord { game_id: 7, @@ -1847,3 +1857,240 @@ fn fresh_for(game_id: u64) -> LibraryEntry { finished_at: None, } } + +#[test] +fn putting_a_provider_adds_it_without_losing_entries_matches_or_settings_and_requests_a_scan() { + let (mut machine, effects) = loaded(false, matched_cache()); + let (op, _) = scan_ops(&effects)[0].clone(); + scanned( + &mut machine, + op, + "steam", + Ok(vec![record("620", "Portal 2", "/g/Portal 2")]), + 50, + ); + assert_eq!(machine.providers().len(), 1); + assert!(machine.entry("steam:620").is_some()); + let matches_before = machine.auto_matches.len(); + let layout_before = machine.layout.clone(); + + // The already-known provider is replaced in place rather than appended twice. + let loaded = registry::tests::load(&[("shop.toml", SHOP_MANIFEST)], Platform::Linux); + let shop = loaded.providers.into_iter().next().unwrap(); + assert!(machine.put_provider(shop)); + assert_eq!( + machine + .providers() + .iter() + .map(|provider| provider.id()) + .collect::>(), + ["steam", "shop"] + ); + assert!(machine.entry("steam:620").is_some(), "entries are kept"); + assert_eq!( + machine.auto_matches.len(), + matches_before, + "matches are kept" + ); + assert_eq!(machine.layout, layout_before, "layout settings are kept"); + + machine.put_provider(providers(true).pop().unwrap()); + assert_eq!( + machine + .providers() + .iter() + .map(|provider| provider.id()) + .collect::>(), + ["steam", "shop"], + "replacing by id keeps the position" + ); + + // A scan request now includes the new provider. + let effects = machine.handle(Input::ScanRequested); + assert_eq!( + scan_ops(&effects) + .into_iter() + .map(|(_, provider)| provider) + .collect::>(), + ["shop", "steam"] + ); + assert!(machine.entry("steam:620").is_some(), "entries are kept"); +} + +#[test] +fn removing_a_provider_drops_its_live_rows_and_a_reinstall_restores_them() { + let (mut machine, effects) = loaded(true, LibraryCache::default()); + let ops = scan_ops(&effects); + let shop_op = ops.iter().find(|(_, id)| id == "shop").unwrap().0; + let steam_op = ops.iter().find(|(_, id)| id == "steam").unwrap().0; + scanned( + &mut machine, + shop_op, + "shop", + Ok(vec![record("1", "Shop One", "/shop/one")]), + 10, + ); + assert!(machine.entry("shop:1").is_some()); + + assert!(machine.remove_provider("shop")); + assert!(machine.provider("shop").is_none()); + assert!(machine.entry("shop:1").is_none(), "live rows are dropped"); + assert!( + !machine + .visible_entries() + .any(|entry| entry.provider == "shop") + ); + assert!(!machine.remove_provider("shop"), "removal is idempotent"); + + // A late answer for the uninstalled provider is ignored instead of recreating its rows. + let effects = scanned( + &mut machine, + shop_op, + "shop", + Ok(vec![record("9", "Late", "/shop/late")]), + 11, + ); + assert!(effects.is_empty()); + assert!(machine.entry("shop:9").is_none()); + + // The rest of the scan still completes. + scanned(&mut machine, steam_op, "steam", Ok(vec![]), 12); + + // Reinstalling puts the provider back and the next scan repopulates the rows. + let shop = registry::tests::load(&[("shop.toml", SHOP_MANIFEST)], Platform::Linux) + .providers + .into_iter() + .next() + .unwrap(); + machine.put_provider(shop); + let effects = machine.handle(Input::ScanRequested); + let (op, _) = scan_ops(&effects) + .into_iter() + .find(|(_, id)| id == "shop") + .unwrap(); + scanned( + &mut machine, + op, + "shop", + Ok(vec![record("1", "Shop One", "/shop/one")]), + 20, + ); + assert!(machine.entry("shop:1").is_some()); +} + +#[test] +fn removing_a_provider_by_plugin_id_resolves_the_composed_provider_id() { + let (mut machine, effects) = loaded(false, LibraryCache::default()); + let (op, _) = scan_ops(&effects)[0].clone(); + scanned( + &mut machine, + op, + "steam", + Ok(vec![record("620", "Portal 2", "/g/Portal 2")]), + 10, + ); + assert_eq!( + machine.providers()[0].discovery_plugin(), + Some("org.gamenode.plugin.steam-discovery"), + "the installed plugin id is not the provider id" + ); + assert!(machine.entry("steam:620").is_some()); + + assert!(machine.remove_provider_for_plugin("org.gamenode.plugin.steam-discovery")); + assert!(machine.provider("steam").is_none()); + assert!( + machine.entry("steam:620").is_none(), + "live rows are dropped" + ); + assert!( + !machine + .visible_entries() + .any(|entry| entry.provider == "steam") + ); + assert!( + !machine.remove_provider_for_plugin("org.gamenode.plugin.steam-discovery"), + "removal is idempotent" + ); + + // An unknown plugin id changes nothing. + assert!(!machine.remove_provider_for_plugin("dev.example.unknown")); +} + +#[test] +fn a_reinstalled_provider_keeps_the_users_chosen_match() { + let cache = LibraryCache { + entries: vec![stored("shop", "1", "Shop One", true)], + chosen_matches: vec![ChosenMatch { + entry_key: "shop:1".to_owned(), + game_id: Some(42), + chosen_at: 5, + source: Default::default(), + }], + ..LibraryCache::default() + }; + let (mut machine, effects) = loaded(true, cache); + let ops = scan_ops(&effects); + for (op, provider) in &ops { + let records = if provider == "shop" { + vec![record("1", "Shop One", "/shop/one")] + } else { + Vec::new() + }; + scanned(&mut machine, *op, provider, Ok(records), 10); + } + assert_eq!( + machine + .match_status(machine.entry("shop:1").unwrap()) + .game_id(), + Some(42), + "the host cache restores the user's chosen match" + ); + + let shop = registry::tests::load(&[("shop.toml", SHOP_MANIFEST)], Platform::Linux) + .providers + .into_iter() + .next() + .unwrap(); + assert!(machine.remove_provider("shop")); + assert!(machine.entry("shop:1").is_none()); + assert!(machine.put_provider(shop)); + let effects = machine.handle(Input::ScanRequested); + let (op, _) = scan_ops(&effects) + .into_iter() + .find(|(_, provider)| provider == "shop") + .unwrap(); + scanned( + &mut machine, + op, + "shop", + Ok(vec![record("1", "Shop One", "/shop/one")]), + 20, + ); + assert_eq!( + machine + .match_status(machine.entry("shop:1").unwrap()) + .game_id(), + Some(42), + "reinstalling the provider must not lose the host-owned association" + ); +} + +#[test] +fn cached_entries_of_a_provider_that_is_not_loaded_stay_hidden() { + let cache = LibraryCache { + entries: vec![stored("shop", "1", "Shop One", true)], + ..LibraryCache::default() + }; + let (machine, _) = loaded(false, cache); + assert!(machine.provider("shop").is_none()); + assert!( + machine.entry("shop:1").is_some(), + "the persisted row stays available for a reinstall" + ); + assert!( + !machine + .visible_entries() + .any(|entry| entry.provider == "shop"), + "an uninstalled store cannot keep showing cached games" + ); +} diff --git a/crates/core/src/library/match_dialog.rs b/crates/core/src/library/match_dialog.rs index a5eca4fd8..83f3acf7a 100644 --- a/crates/core/src/library/match_dialog.rs +++ b/crates/core/src/library/match_dialog.rs @@ -13,7 +13,7 @@ use serde::{Deserialize, Serialize}; use super::actions::Reason; use super::machine::{Effect, LibraryMachine}; use super::matching::{MatchSource, MatchStatus}; -use super::store::ChosenMatch; +use super::store::{ChoiceSource, ChosenMatch}; use super::suggest::{ SuggestionTone, confidence, detected_years, percent_of, search_query, title_score, tone, }; @@ -38,12 +38,61 @@ enum Search { Failed(SearchFailure), } +/// Catalog platform abbreviations accepted for a declared content platform. +const GAMECUBE_ALIASES: &[&str] = &["NGC", "GC", "GCN", "GameCube"]; +const WII_ALIASES: &[&str] = &["Wii"]; + +/// The platform narrowing derived from the entry's record. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct MatchPlatformFilter { + /// The entry's declared platform, normalized to lowercase (for example `gamecube`). + pub platform: String, + /// The platform's display name (for example `GameCube`). + pub label: String, + /// The catalog abbreviations an option may report for this platform. + pub aliases: Vec, + /// Whether options outside the platform are hidden. On by default when the platform is known. + pub enabled: bool, +} + +impl MatchPlatformFilter { + /// The filter a declared platform implies. Unknown, blank and absent declarations set no + /// filter, so the dialog keeps today's behavior. + fn derived(declared: Option<&str>) -> Option { + let platform = declared?.trim().to_ascii_lowercase(); + let (label, aliases): (&str, &[&str]) = match platform.as_str() { + "gamecube" => ("GameCube", GAMECUBE_ALIASES), + "wii" => ("Wii", WII_ALIASES), + _ => return None, + }; + Some(Self { + platform, + label: label.to_owned(), + aliases: aliases.iter().map(|alias| (*alias).to_owned()).collect(), + enabled: true, + }) + } + + /// Whether the option belongs to the declared platform. A disabled filter hides nothing. + pub fn shows(&self, option: &MatchOption) -> bool { + !self.enabled + || option.platforms.iter().any(|platform| { + self.aliases + .iter() + .any(|alias| alias.eq_ignore_ascii_case(platform)) + }) + } +} + /// An open dialog. Lives in the machine; the view is [`MatchDialogView`]. #[derive(Debug)] pub(super) struct MatchDialog { key: String, query: String, search: Search, + /// The platform narrowing derived from the entry's record, when it declares one. + platform: Option, /// The game the preview shows. `None` while there is nothing to offer. selected: Option, /// The user selected an option, so an arriving result no longer replaces it. @@ -107,7 +156,13 @@ pub struct MatchDialogView { /// The option selected for preview, with its confidence and reasons. pub selected: Option, /// Set after a search that returned nothing, so the UI can say so instead of showing a blank. + /// The platform filter never sets this: a narrowed-empty answer is explained by + /// [`Self::filtered_out`] with empty lists instead. pub no_results: bool, + /// The platform narrowing derived from the entry, when it declares one. + pub platform_filter: Option, + /// How many options the active platform filter hides. `0` when it hides nothing. + pub filtered_out: usize, pub error: Option, /// Why searching is unavailable right now, if it is. pub search_blocked: Option, @@ -130,11 +185,14 @@ impl LibraryMachine { let Some(entry) = self.entries.get(key) else { return vec![]; }; - let query = entry.name.clone().unwrap_or_else(|| entry.store_id.clone()); + let query = search_query(entry); + let platform = + MatchPlatformFilter::derived(entry.fields.get("platform").map(String::as_str)); self.dialog = Some(MatchDialog { key: key.clone(), query, search: Search::Idle, + platform, selected: None, manual_selection: false, }); @@ -158,28 +216,46 @@ impl LibraryMachine { self.dialog.as_ref().and_then(|dialog| dialog.selected) } - /// Selects the current match, else the most confident option, unless the user already - /// chose. Called on open and after every search answer. + /// Selects the current match, else the most confident option, unless the user already chose + /// an option the platform filter shows. A manual pick the filter hides yields to the default. + /// Called on open, after every search answer and when the filter toggles. fn apply_default_selection(&mut self) { - if self + let manual = self .dialog .as_ref() - .is_some_and(|dialog| dialog.manual_selection) + .is_some_and(|dialog| dialog.manual_selection); + if manual + && self + .dialog + .as_ref() + .is_some_and(|dialog| self.selection_is_visible(dialog)) { return; } + if manual && let Some(dialog) = &mut self.dialog { + dialog.manual_selection = false; + } let selected = self.default_selection_id(); if let Some(dialog) = &mut self.dialog { dialog.selected = selected; } } + /// Whether the dialog's selected option is one the platform filter shows. + fn selection_is_visible(&self, dialog: &MatchDialog) -> bool { + dialog.selected.is_some_and(|game_id| { + self.dialog_option(dialog, game_id) + .is_some_and(|option| self.platform_shows(dialog, &option)) + }) + } + fn default_selection_id(&self) -> Option { let dialog = self.dialog.as_ref()?; let entry = self.entries.get(&dialog.key)?; let current = self.match_status(entry); if let Some(game_id) = current.game_id() - && self.games.contains_key(&game_id) + && let Some(option) = self.dialog_option(dialog, game_id) + && self.platform_shows(dialog, &option) { return Some(game_id); } @@ -198,6 +274,44 @@ impl LibraryMachine { best.map(|option| option.game_id) } + /// Whether the dialog's active platform filter shows this option. + fn platform_shows(&self, dialog: &MatchDialog, option: &MatchOption) -> bool { + dialog + .platform + .as_ref() + .is_none_or(|filter| filter.shows(option)) + } + + /// Splits the options the dialog built into the ones the platform filter shows and the ones + /// it hides. A disabled or absent filter hides nothing. + fn split_platform_filter( + &self, + dialog: &MatchDialog, + options: Vec, + ) -> (Vec, Vec) { + let Some(filter) = dialog.platform.as_ref().filter(|filter| filter.enabled) else { + return (options, Vec::new()); + }; + options.into_iter().partition(|option| filter.shows(option)) + } + + /// The option for one game, as the dialog currently knows it (from a search answer or the + /// cached game record). + fn dialog_option(&self, dialog: &MatchDialog, game_id: u64) -> Option { + let summary = match &dialog.search { + Search::Done(games) => games.iter().find(|game| game.id == game_id), + _ => None, + }; + let status = self + .entries + .get(&dialog.key) + .map(|entry| self.match_status(entry)); + let candidate = status + .as_ref() + .is_some_and(|status| status.candidates().contains(&game_id)); + self.option_for(dialog, game_id, summary, candidate) + } + /// The option for one game, scored against the dialog entry's detected title and years. fn option_for( &self, @@ -280,8 +394,19 @@ impl LibraryMachine { }) } - /// The server's candidates, ordered by confidence (then title and id for determinism). + /// The server's candidates, ordered by confidence (then title and id for determinism), with + /// the ones the active platform filter hides omitted. fn candidate_options(&self, dialog: &MatchDialog, current: &MatchStatus) -> Vec { + let options = self.candidate_options_unfiltered(dialog, current); + self.split_platform_filter(dialog, options).0 + } + + /// Every candidate the server offered, before the platform filter. + fn candidate_options_unfiltered( + &self, + dialog: &MatchDialog, + current: &MatchStatus, + ) -> Vec { let mut options: Vec = current .candidates() .iter() @@ -297,8 +422,19 @@ impl LibraryMachine { options } - /// The search answer's games in the server's order, without the candidates. + /// The search answer's games in the server's order, without the candidates, and with the ones + /// the active platform filter hides omitted. fn result_options(&self, dialog: &MatchDialog, candidate_ids: &[u64]) -> Vec { + let options = self.result_options_unfiltered(dialog, candidate_ids); + self.split_platform_filter(dialog, options).0 + } + + /// Every search result, before the platform filter. + fn result_options_unfiltered( + &self, + dialog: &MatchDialog, + candidate_ids: &[u64], + ) -> Vec { let Search::Done(games) = &dialog.search else { return Vec::new(); }; @@ -310,14 +446,19 @@ impl LibraryMachine { } /// Whether the dialog currently offers this game, so a stale selection input changes nothing. + /// An option the active platform filter hides is not offered. fn dialog_offers(&self, dialog: &MatchDialog, game_id: u64) -> bool { let Some(entry) = self.entries.get(&dialog.key) else { return false; }; let status = self.match_status(entry); - status.game_id() == Some(game_id) + let offered = status.game_id() == Some(game_id) || status.candidates().contains(&game_id) - || matches!(&dialog.search, Search::Done(games) if games.iter().any(|game| game.id == game_id)) + || matches!(&dialog.search, Search::Done(games) if games.iter().any(|game| game.id == game_id)); + offered + && self + .dialog_option(dialog, game_id) + .is_some_and(|option| self.platform_shows(dialog, &option)) } pub(super) fn close_match(&mut self) { @@ -330,6 +471,29 @@ impl LibraryMachine { } } + /// Turns the entry's platform filter on or off. The answer is already local, so nothing is + /// searched again. A manual pick the new filter hides yields to the best visible option; a + /// visible pick is kept so the user's choice survives the toggle. + pub(super) fn set_match_platform_filter(&mut self, enabled: bool) -> Vec { + let Some(platform) = self + .dialog + .as_ref() + .and_then(|dialog| dialog.platform.as_ref()) + else { + return vec![]; + }; + if platform.enabled == enabled { + return vec![]; + } + if let Some(dialog) = &mut self.dialog + && let Some(platform) = &mut dialog.platform + { + platform.enabled = enabled; + } + self.apply_default_selection(); + vec![] + } + /// Searches GameNode for the dialog's query. A blank query searches nothing. pub(super) fn search_match(&mut self) -> Vec { let blocked = self.network_block(); @@ -512,13 +676,20 @@ impl LibraryMachine { let Some(account) = self.account.as_ref().map(|a| a.id.clone()) else { return vec![]; }; - if self.chosen.get(key).map(|c| c.game_id) == Some(game_id) { + // A plugin's earlier choice of the same game still becomes the user's own, so a plugin + // can no longer replace it. + if self + .chosen + .get(key) + .is_some_and(|c| c.game_id == game_id && c.source == ChoiceSource::User) + { return vec![]; } let choice = ChosenMatch { entry_key: key.to_owned(), game_id, chosen_at: now, + source: ChoiceSource::User, }; self.chosen.insert(key.to_owned(), choice.clone()); vec![Effect::PersistChoice { @@ -531,16 +702,20 @@ impl LibraryMachine { let dialog = self.dialog.as_ref()?; let entry = self.entries.get(&dialog.key)?; let current = self.match_status(entry); - let candidates = self.candidate_options(dialog, ¤t); - let results = self.result_options(dialog, current.candidates()); - let selected = dialog.selected.and_then(|game_id| { - let summary = match &dialog.search { - Search::Done(games) => games.iter().find(|game| game.id == game_id), - _ => None, - }; - let candidate = current.candidates().contains(&game_id); - self.option_for(dialog, game_id, summary, candidate) - }); + let (candidates, hidden_candidates) = + self.split_platform_filter(dialog, self.candidate_options_unfiltered(dialog, ¤t)); + let (results, hidden_results) = self.split_platform_filter( + dialog, + self.result_options_unfiltered(dialog, current.candidates()), + ); + // Whether the server's answer itself was empty, regardless of what the filter hides. + let answer_empty = candidates.is_empty() + && hidden_candidates.is_empty() + && results.is_empty() + && hidden_results.is_empty(); + let selected = dialog + .selected + .and_then(|game_id| self.dialog_option(dialog, game_id)); let (searching, error, searched) = match &dialog.search { Search::Idle => (false, None, false), Search::Running { .. } => (true, None, false), @@ -556,7 +731,9 @@ impl LibraryMachine { .unwrap_or_default(), query: dialog.query.clone(), searching, - no_results: searched && results.is_empty() && candidates.is_empty(), + no_results: searched && answer_empty, + platform_filter: dialog.platform.clone(), + filtered_out: hidden_candidates.len() + hidden_results.len(), candidates, results, selected, diff --git a/crates/core/src/library/match_dialog/tests.rs b/crates/core/src/library/match_dialog/tests.rs index 87609f263..44e3ffc60 100644 --- a/crates/core/src/library/match_dialog/tests.rs +++ b/crates/core/src/library/match_dialog/tests.rs @@ -54,6 +54,7 @@ fn library() -> LibraryMachine { let (mut machine, _) = loaded(false, cache); let op = machine.scan.as_ref().unwrap().op; machine.handle(Input::ProviderScanned { + targets: Default::default(), op, provider: "steam".to_owned(), result: Ok(vec![ @@ -145,6 +146,57 @@ fn opening_prefills_the_detected_title_and_searches_it() { assert!(!view.can_clear); } +#[test] +fn opening_a_dump_searches_its_record_title_instead_of_the_file_name() { + let mut cache = LibraryCache::default(); + cache + .entries + .push(stored("steam", "GPIE01", "Pikmin (USA) (Rev 1)", true)); + cache.games = vec![platform_record(500, "Pikmin", 2001, &["NGC"])]; + let (mut machine, _) = loaded(false, cache); + let op = machine.scan.as_ref().unwrap().op; + let mut scanned = record( + "GPIE01", + "Pikmin (USA) (Rev 1)", + "/games/Pikmin (USA) (Rev 1)", + ); + scanned + .fields + .insert("platform".to_owned(), "gamecube".to_owned()); + scanned + .fields + .insert("title".to_owned(), "Pikmin".to_owned()); + machine.handle(Input::ProviderScanned { + op, + provider: "steam".to_owned(), + result: Ok(vec![scanned]), + targets: Default::default(), + now: NOW, + }); + machine.handle(Input::SetAccess { + access: Access::Verified, + now: NOW, + }); + + let effects = open(&mut machine, "GPIE01"); + let sent = searches(&effects); + assert_eq!(sent.len(), 1); + assert_eq!( + sent[0].1, "Pikmin", + "the record title, not the tagged file name" + ); + + let view = dialog(&mut machine); + assert_eq!(view.query, "Pikmin"); + assert_eq!(view.detected_name, "Pikmin (USA) (Rev 1)"); + assert_eq!( + view.platform_filter + .as_ref() + .map(|filter| filter.platform.as_str()), + Some("gamecube") + ); +} + #[test] fn search_results_show_title_year_and_cover_and_can_be_picked() { let mut machine = library(); @@ -698,6 +750,7 @@ fn year_library() -> LibraryMachine { op, provider: "steam".to_owned(), result: Ok(vec![record("900", "Hollow Mountain 2024", "/g")]), + targets: Default::default(), now: NOW, }); machine.handle(Input::SetAccess { @@ -951,3 +1004,445 @@ fn a_selection_the_dialog_does_not_offer_is_ignored() { ); assert!(dialog(&mut machine).selected.is_none()); } + +/// A catalog game the search answer can carry, with its platform abbreviations. +fn game_with(id: u64, name: &str, platforms: &[&str]) -> GameSummary { + GameSummary { + platforms: platforms + .iter() + .map(|platform| (*platform).to_owned()) + .collect(), + ..game(id, name) + } +} + +/// A library whose single Steam entry declares `platform` in its scan record, so the match dialog +/// derives the platform filter independently of the provider. `candidates` become the store-id +/// candidates; games 500–503 cover both platforms. +fn platform_library(platform: Option<&str>, candidates: &[u64]) -> LibraryMachine { + let mut cache = LibraryCache::default(); + cache.entries.push(stored("steam", "500", "Pikmin", true)); + if !candidates.is_empty() { + cache.auto_matches.push(AutoMatch { + category: 1, + uid: "500".to_owned(), + game_ids: candidates.to_vec(), + checked_at: NOW, + }); + } + cache.games = vec![ + platform_record(500, "Pikmin", 2001, &["NGC"]), + platform_record(501, "Pikmin 4", 2023, &["Switch"]), + platform_record(502, "Pikmin 2", 2004, &["NGC"]), + platform_record(503, "Pikmin 3 Deluxe", 2020, &["Switch"]), + ]; + let (mut machine, _) = loaded(false, cache); + let op = machine.scan.as_ref().unwrap().op; + let mut scanned = record("500", "Pikmin", "/g"); + if let Some(platform) = platform { + scanned + .fields + .insert("platform".to_owned(), platform.to_owned()); + } + machine.handle(Input::ProviderScanned { + op, + provider: "steam".to_owned(), + result: Ok(vec![scanned]), + targets: Default::default(), + now: NOW, + }); + machine.handle(Input::SetAccess { + access: Access::Verified, + now: NOW, + }); + machine +} + +/// A cached game record with the platforms the catalog reported. +fn platform_record(id: u64, name: &str, year: i32, platforms: &[&str]) -> GameRecord { + GameRecord { + game_id: id, + name: name.to_owned(), + release_year: Some(year), + cover_url: None, + cover_file: None, + cover_failed_at: None, + platforms: platforms + .iter() + .map(|platform| (*platform).to_owned()) + .collect(), + } +} + +fn option_with(platforms: &[&str]) -> MatchOption { + MatchOption { + game_id: 1, + name: "Pikmin".to_owned(), + release_year: Some(2001), + cover_url: None, + cover_file: None, + current: false, + confidence: 90, + tone: SuggestionTone::Success, + platforms: platforms + .iter() + .map(|platform| (*platform).to_owned()) + .collect(), + reasons: Vec::new(), + } +} + +fn result_ids(view: &MatchDialogView) -> Vec { + view.results.iter().map(|option| option.game_id).collect() +} + +fn candidate_ids(view: &MatchDialogView) -> Vec { + view.candidates + .iter() + .map(|option| option.game_id) + .collect() +} + +#[test] +fn the_declared_platform_maps_to_catalog_aliases() { + let gamecube = MatchPlatformFilter::derived(Some(" GameCube ")).expect("known platform"); + assert_eq!(gamecube.platform, "gamecube"); + assert_eq!(gamecube.label, "GameCube"); + assert_eq!(gamecube.aliases, ["NGC", "GC", "GCN", "GameCube"]); + assert!(gamecube.enabled, "on by default when the platform is known"); + for alias in ["NGC", "gc", "GCN", "gamecube"] { + assert!(gamecube.shows(&option_with(&[alias])), "{alias}"); + } + assert!(!gamecube.shows(&option_with(&["Switch"]))); + assert!( + !gamecube.shows(&option_with(&[])), + "an option without platforms cannot be shown to belong to the entry's platform" + ); + + let wii = MatchPlatformFilter::derived(Some("WII")).expect("known platform"); + assert_eq!(wii.label, "Wii"); + assert!(wii.shows(&option_with(&["wii"]))); + assert!(!wii.shows(&option_with(&["NGC"]))); + + for unknown in [None, Some(""), Some(" "), Some("dreamcast")] { + assert_eq!(MatchPlatformFilter::derived(unknown), None, "{unknown:?}"); + } + + let mut disabled = gamecube.clone(); + disabled.enabled = false; + assert!( + disabled.shows(&option_with(&["Switch"])), + "showing all hides nothing" + ); +} + +#[test] +fn a_gamecube_entry_shows_the_ngc_candidates_and_results_by_default() { + let mut machine = platform_library(Some("gamecube"), &[500, 501]); + let effects = open(&mut machine, "500"); + + // The search request is unchanged: text only, whatever platform the entry declares. + let sent = searches(&effects); + assert_eq!(sent.len(), 1); + assert_eq!(sent[0].1, "Pikmin"); + + let view = dialog(&mut machine); + let filter = view + .platform_filter + .as_ref() + .expect("the entry declares a platform"); + assert_eq!(filter.platform, "gamecube"); + assert_eq!(filter.label, "GameCube"); + assert!(filter.enabled); + assert_eq!( + candidate_ids(&view), + [500], + "the Switch candidate is hidden" + ); + assert_eq!( + view.selected.as_ref().map(|option| option.game_id), + Some(500), + "the default selection comes from the filtered candidates" + ); + assert_eq!(view.filtered_out, 1); + assert!(!view.no_results); + + let (op, _) = sent[0]; + machine.handle(Input::MatchSearched { + op, + result: Ok(vec![ + game_with(502, "Pikmin 2", &["NGC"]), + game_with(503, "Pikmin 3 Deluxe", &["Switch"]), + ]), + }); + let view = dialog(&mut machine); + assert_eq!(result_ids(&view), [502]); + assert_eq!( + view.filtered_out, 2, + "one candidate and one result are hidden" + ); + assert!(!view.no_results); + + // Show all restores the complete answer and the full list, with no new search. + let effects = machine.handle(Input::SetMatchPlatformFilter { enabled: false }); + assert!( + effects.is_empty(), + "the filter works on the received answer" + ); + let view = dialog(&mut machine); + assert!(!view.platform_filter.as_ref().unwrap().enabled); + assert_eq!(candidate_ids(&view), [500, 501]); + assert_eq!(result_ids(&view), [502, 503]); + assert_eq!(view.filtered_out, 0); + assert_eq!( + view.selected.as_ref().map(|option| option.game_id), + Some(500), + "the best option of the full answer is preselected" + ); + + // Turning it back on narrows the same lists again. + machine.handle(Input::SetMatchPlatformFilter { enabled: true }); + let view = dialog(&mut machine); + assert_eq!(candidate_ids(&view), [500]); + assert_eq!(result_ids(&view), [502]); + assert_eq!(view.filtered_out, 2); +} + +#[test] +fn a_wii_entry_matches_the_wii_alias_and_keeps_its_manual_choice() { + let mut machine = platform_library(Some("Wii"), &[]); + let (op, _) = searches(&open(&mut machine, "500")).remove(0); + machine.handle(Input::MatchSearched { + op, + result: Ok(vec![ + game_with(500, "Metroid Prime", &["Wii"]), + game_with(501, "Metroid Prime Remastered", &["Switch"]), + game_with(502, "Metroid Prime 2: Echoes", &["wii"]), + ]), + }); + let view = dialog(&mut machine); + assert_eq!(view.platform_filter.as_ref().unwrap().platform, "wii"); + assert_eq!(view.platform_filter.as_ref().unwrap().label, "Wii"); + assert_eq!(result_ids(&view), [500, 502]); + assert_eq!(view.filtered_out, 1); + + // A visible manual choice survives turning the filter off. + machine.handle(Input::SelectMatch { game_id: 502 }); + let effects = machine.handle(Input::SetMatchPlatformFilter { enabled: false }); + assert!(effects.is_empty()); + let view = dialog(&mut machine); + assert_eq!(result_ids(&view), [500, 501, 502]); + assert_eq!( + view.selected.as_ref().map(|option| option.game_id), + Some(502) + ); +} + +#[test] +fn an_entry_without_a_known_platform_is_not_filtered() { + for platform in [None, Some("dreamcast")] { + let mut machine = platform_library(platform, &[500, 501]); + let (op, _) = searches(&open(&mut machine, "500")).remove(0); + machine.handle(Input::MatchSearched { + op, + result: Ok(vec![ + game_with(502, "Pikmin 2", &["NGC"]), + game_with(503, "Pikmin 3 Deluxe", &[]), + ]), + }); + let view = dialog(&mut machine); + assert!( + view.platform_filter.is_none(), + "{platform:?} declares no known platform" + ); + assert_eq!(view.filtered_out, 0); + assert_eq!(candidate_ids(&view), [500, 501]); + assert_eq!(result_ids(&view), [502, 503]); + assert_eq!( + machine.handle(Input::SetMatchPlatformFilter { enabled: false }), + Vec::::new(), + "a dialog without a filter ignores the toggle" + ); + } +} + +#[test] +fn an_answer_the_filter_hides_entirely_is_not_a_failed_search() { + let mut machine = platform_library(Some("gamecube"), &[]); + let (op, _) = searches(&open(&mut machine, "500")).remove(0); + machine.handle(Input::MatchSearched { + op, + result: Ok(vec![ + game_with(503, "Pikmin 3 Deluxe", &["Switch"]), + game_with(501, "Pikmin 4", &["Switch"]), + ]), + }); + let view = dialog(&mut machine); + assert!( + !view.no_results, + "the server answered; the filter is what hides the answer" + ); + assert_eq!(view.filtered_out, 2); + assert!(view.results.is_empty() && view.candidates.is_empty()); + assert!(view.selected.is_none()); + + // Show all makes the same answer visible. + machine.handle(Input::SetMatchPlatformFilter { enabled: false }); + let view = dialog(&mut machine); + assert_eq!(result_ids(&view), [503, 501]); + assert_eq!(view.filtered_out, 0); + assert!(view.selected.is_some()); + + // A genuinely empty answer is still reported as no results. + let mut empty = platform_library(Some("gamecube"), &[]); + let (op, _) = searches(&open(&mut empty, "500")).remove(0); + empty.handle(Input::MatchSearched { + op, + result: Ok(vec![]), + }); + let view = dialog(&mut empty); + assert!(view.no_results); + assert_eq!(view.filtered_out, 0); +} + +#[test] +fn toggling_the_filter_recomputes_a_hidden_selection() { + let mut machine = platform_library(Some("gamecube"), &[500, 501]); + let (op, _) = searches(&open(&mut machine, "500")).remove(0); + machine.handle(Input::MatchSearched { + op, + result: Ok(vec![ + game_with(502, "Pikmin 2", &["NGC"]), + game_with(503, "Pikmin 3 Deluxe", &["Switch"]), + ]), + }); + + // Show all, then pick the Switch game the GameCube filter would hide. + machine.handle(Input::SetMatchPlatformFilter { enabled: false }); + machine.handle(Input::SelectMatch { game_id: 503 }); + assert_eq!( + dialog(&mut machine) + .selected + .as_ref() + .map(|option| option.game_id), + Some(503) + ); + + // Turning the filter on hides the pick, so the best visible option takes over. + machine.handle(Input::SetMatchPlatformFilter { enabled: true }); + let view = dialog(&mut machine); + assert_eq!( + view.selected.as_ref().map(|option| option.game_id), + Some(500) + ); + assert!(view.results.iter().all(|option| option.game_id != 503)); + assert_eq!(view.filtered_out, 2); + + // Turning it off restores the full answer; the recomputed default is the best of it. + machine.handle(Input::SetMatchPlatformFilter { enabled: false }); + let view = dialog(&mut machine); + assert_eq!(result_ids(&view), [502, 503]); + assert_eq!( + view.selected.as_ref().map(|option| option.game_id), + Some(500) + ); + + // A hidden option cannot be selected while the filter is on. + machine.handle(Input::SetMatchPlatformFilter { enabled: true }); + machine.handle(Input::SelectMatch { game_id: 503 }); + assert_eq!( + dialog(&mut machine) + .selected + .as_ref() + .map(|option| option.game_id), + Some(500) + ); +} + +#[test] +fn the_current_match_is_kept_when_it_is_visible_and_yielded_when_it_is_hidden() { + // The current match is a GameCube game: it stays selected and previewed. + let mut cache = LibraryCache::default(); + cache.entries.push(stored("steam", "500", "Pikmin", true)); + cache.auto_matches.push(AutoMatch { + category: 1, + uid: "500".to_owned(), + game_ids: vec![500], + checked_at: NOW, + }); + cache.games = vec![ + platform_record(500, "Pikmin", 2001, &["NGC"]), + platform_record(501, "Pikmin 4", 2023, &["Switch"]), + ]; + let (mut machine, _) = loaded(false, cache); + let op = machine.scan.as_ref().unwrap().op; + let mut scanned = record("500", "Pikmin", "/g"); + scanned + .fields + .insert("platform".to_owned(), "gamecube".to_owned()); + machine.handle(Input::ProviderScanned { + op, + provider: "steam".to_owned(), + result: Ok(vec![scanned]), + targets: Default::default(), + now: NOW, + }); + machine.handle(Input::SetAccess { + access: Access::Verified, + now: NOW, + }); + open(&mut machine, "500"); + let view = dialog(&mut machine); + assert_eq!( + view.selected.as_ref().map(|option| option.game_id), + Some(500) + ); + assert!(view.selected.unwrap().current); + + // The same entry matched to a Switch game, with the search answer offering a GameCube game: + // the hidden current match yields to the visible option, and the entry itself is unchanged. + let mut cache = LibraryCache::default(); + cache.entries.push(stored("steam", "500", "Pikmin", true)); + cache.auto_matches.push(AutoMatch { + category: 1, + uid: "500".to_owned(), + game_ids: vec![501], + checked_at: NOW, + }); + cache.games = vec![ + platform_record(501, "Pikmin 4", 2023, &["Switch"]), + platform_record(502, "Pikmin 2", 2004, &["NGC"]), + ]; + let (mut machine, _) = loaded(false, cache); + let op = machine.scan.as_ref().unwrap().op; + let mut scanned = record("500", "Pikmin", "/g"); + scanned + .fields + .insert("platform".to_owned(), "gamecube".to_owned()); + machine.handle(Input::ProviderScanned { + op, + provider: "steam".to_owned(), + result: Ok(vec![scanned]), + targets: Default::default(), + now: NOW, + }); + machine.handle(Input::SetAccess { + access: Access::Verified, + now: NOW, + }); + let (op, _) = searches(&open(&mut machine, "500")).remove(0); + machine.handle(Input::MatchSearched { + op, + result: Ok(vec![ + game_with(502, "Pikmin 2", &["NGC"]), + game_with(503, "Pikmin 3 Deluxe", &["Switch"]), + ]), + }); + let view = dialog(&mut machine); + assert_eq!( + view.selected.as_ref().map(|option| option.game_id), + Some(502) + ); + assert_eq!(view.filtered_out, 1); + assert_eq!(status(&machine, "500").game_id(), Some(501)); +} diff --git a/crates/core/src/library/matching.rs b/crates/core/src/library/matching.rs index 4f243bc6d..44723001f 100644 --- a/crates/core/src/library/matching.rs +++ b/crates/core/src/library/matching.rs @@ -95,6 +95,7 @@ mod tests { entry_key: "steam:620".to_owned(), game_id, chosen_at: 0, + source: Default::default(), } } diff --git a/crates/core/src/library/mod.rs b/crates/core/src/library/mod.rs index 63f816ba8..dad868078 100644 --- a/crates/core/src/library/mod.rs +++ b/crates/core/src/library/mod.rs @@ -10,8 +10,10 @@ mod batch; mod catalog; pub mod cover; mod cover_queue; +pub mod custom_launch; pub mod favorites; pub mod launch; +pub mod launch_plan; pub mod layout; mod lookup; pub mod machine; @@ -19,10 +21,13 @@ pub mod match_dialog; pub mod matching; pub mod membership; pub mod organization; +pub mod plugin_match; pub mod query; +pub mod runtime; pub mod selection; pub mod store; pub mod suggest; +pub mod target; pub mod view; pub use actions::{Actions, Availability, Reason, Why}; pub use add_dialog::{ @@ -34,9 +39,17 @@ pub use add_run::{ }; pub use batch::{CollectionRunView, StatusRunView, UndoAddView, UndoState}; pub use catalog::{CatalogResult, CatalogStatus, CatalogView}; +pub use custom_launch::{ + CustomLaunchModLayer, CustomLaunchMutation, CustomLaunchRecipe, LaunchRecipeSelection, + LaunchRecipeSelectionWrite, +}; pub use launch::{ LaunchError, LaunchKind, LaunchState, LaunchStateView, LaunchStatus, open_action, }; +pub use launch_plan::{ + LAUNCH_PLAN_VERSION, LaunchPlan, LaunchPlanComponent, LaunchPlanError, LaunchPlanResource, + LaunchPlanTarget, +}; pub use layout::{ AddedFilter, AvailabilityFilter, CoverSize, DAY_SECONDS, FIRST_RELEASE_DECADE, GameNodeStatusFilter, GroupBy, LastPlayedFilter, LibraryFilters, LibraryLayout, LibraryScope, @@ -45,7 +58,8 @@ pub use layout::{ }; pub use machine::{Access, Effect, Input, LibraryMachine, ScanOutcome}; pub use match_dialog::{ - CandidateOption, MatchDialogView, MatchOption, MatchReason, SearchFailure, SearchResultItem, + CandidateOption, MatchDialogView, MatchOption, MatchPlatformFilter, MatchReason, SearchFailure, + SearchResultItem, }; pub use matching::{MatchSource, MatchStatus}; pub use membership::{EntryStatus, GameStatus, Membership, StandingView}; @@ -53,19 +67,26 @@ pub use organization::{ HiddenNotice, SavedView, SavedViewNotice, SavedViewPayload, ViewError, ViewWriteError, ViewWriteOperation, ViewWriteState, ViewWriteView, }; +pub use plugin_match::{MAX_OFFERED_GAMES, PluginMatch}; pub use query::{ AddedCounts, AvailabilityCounts, CollectionCount, FilterCounts, GameNodeStatusCounts, LastPlayedCounts, MatchStateCounts, PlayedCounts, PlaytimeCounts, ProviderCount, ReleaseCount, Row, RowGameNode, RowGroup, SavedViewCount, ScopeCounts, StoreCount, TitleSource, TitleSourceKind, }; +pub use runtime::{ + ApprovedFileReference, RuntimeArgumentTemplate, RuntimeAvailabilityEntry, + RuntimeContentBinding, RuntimeExtension, RuntimeMutation, RuntimeProvenance, RuntimeResource, +}; pub use selection::{Direction, SelectMode, Selection}; pub use store::{ - AccountLibrary, AutoMatch, CatalogError, CatalogRecord, CatalogUpdate, ChosenMatch, - FavoriteRecord, GameRecord, LastAccount, LibraryCache, LibraryStore, ProviderScanState, - StoreAccount, StoredEntry, entry_key, + AccountLibrary, ArtworkOverride, ArtworkWrite, AutoMatch, CatalogError, CatalogRecord, + CatalogUpdate, ChoiceSource, ChosenMatch, DisplayOverride, DisplayWrite, FavoriteRecord, + GameRecord, LastAccount, LibraryCache, LibraryStore, ProviderScanState, StoreAccount, + StoredEntry, TargetApproval, entry_key, }; pub use suggest::{SuggestionTone, SuggestionView}; +pub use target::{DetectedTarget, DetectedTargetView, TargetSpec}; pub use view::{ DetailView, EmptyState, LibraryView, PaletteEntry, ScanProgress, ScanProgressState, }; diff --git a/crates/core/src/library/plugin_match.rs b/crates/core/src/library/plugin_match.rs new file mode 100644 index 000000000..87b5b60a0 --- /dev/null +++ b/crates/core/src/library/plugin_match.rs @@ -0,0 +1,104 @@ +//! Matching on behalf of a provider's plugin: searching GameNode's catalog and assigning one of +//! the plugin's own entries to a game. +//! +//! This is the match dialog's policy without the dialog, so a plugin never disturbs a dialog the +//! user has open. A game can be assigned only if the host already knows it (it is in the library's +//! game records) or a plugin search just offered it. A choice the user made is never replaced by a +//! plugin; a plugin may replace a choice it made earlier. Nothing here talks to the network: the +//! engine runs the search and reports the answer. + +use std::collections::VecDeque; + +use crate::game_api::GameSummary; + +use super::machine::{Effect, LibraryMachine}; +use super::store::{ChoiceSource, ChosenMatch}; + +/// Games offered by plugin searches that can still be assigned. Older offers drop out first. +pub const MAX_OFFERED_GAMES: usize = 256; + +/// What assigning an entry to a game would do right now. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PluginMatch { + /// The assignment would be stored. + Assign, + /// The entry already has an explicit choice of this game; nothing changes. + Already, + /// The user chose another game, or none, for this entry. + UserChoice, + /// The host does not know this game: it was never found or offered here. + UnknownGame, + /// The library has no such entry. + UnknownEntry, + /// No account library is open, so there is nowhere to keep a choice. + NoAccount, +} + +impl LibraryMachine { + /// What [`Input::AssignPluginMatch`](super::Input::AssignPluginMatch) would do for `key`. + pub fn plan_plugin_match(&self, key: &str, game_id: u64) -> PluginMatch { + if self.account.is_none() { + return PluginMatch::NoAccount; + } + if !self.entries.contains_key(key) { + return PluginMatch::UnknownEntry; + } + if !self.games.contains_key(&game_id) && !self.offered.iter().any(|g| g.id == game_id) { + return PluginMatch::UnknownGame; + } + match self.chosen.get(key) { + Some(choice) if choice.game_id == Some(game_id) => PluginMatch::Already, + Some(choice) if choice.source == ChoiceSource::User => PluginMatch::UserChoice, + _ => PluginMatch::Assign, + } + } + + /// Remembers the games a plugin search returned so one of them can be assigned. + pub(super) fn catalog_searched(&mut self, games: Vec) { + for game in games { + self.offered.retain(|offered| offered.id != game.id); + if self.offered.len() == MAX_OFFERED_GAMES { + self.offered.pop_front(); + } + self.offered.push_back(game); + } + } + + /// Stores a plugin's choice of `game_id` for `key` when [`plan_plugin_match`] allows it. + /// + /// [`plan_plugin_match`]: Self::plan_plugin_match + pub(super) fn assign_plugin_match(&mut self, key: &str, game_id: u64, now: i64) -> Vec { + if self.plan_plugin_match(key, game_id) != PluginMatch::Assign { + return vec![]; + } + let Some(account) = self.account.as_ref().map(|a| a.id.clone()) else { + return vec![]; + }; + let mut effects = Vec::new(); + if let Some(offer) = self.offered.iter().find(|g| g.id == game_id).cloned() { + let games = self.merge_games(std::iter::once(&offer)); + effects.push(Effect::PersistMatches { + games, + matches: vec![], + }); + } + let choice = ChosenMatch { + entry_key: key.to_owned(), + game_id: Some(game_id), + chosen_at: now, + source: ChoiceSource::Plugin, + }; + self.chosen.insert(key.to_owned(), choice.clone()); + effects.push(Effect::PersistChoice { + account_id: account, + choice, + }); + effects.extend(self.plan_covers(None)); + effects + } +} + +pub(super) type Offered = VecDeque; + +#[cfg(test)] +mod tests; diff --git a/crates/core/src/library/plugin_match/tests.rs b/crates/core/src/library/plugin_match/tests.rs new file mode 100644 index 000000000..45bd7c987 --- /dev/null +++ b/crates/core/src/library/plugin_match/tests.rs @@ -0,0 +1,260 @@ +use super::*; +use crate::library::machine::tests::{loaded, record, stored}; +use crate::library::store::{AutoMatch, GameRecord, LibraryCache}; +use crate::library::{Access, Input, SelectMode, entry_key}; + +const NOW: i64 = 5_000; + +fn game(id: u64, name: &str) -> GameSummary { + GameSummary { + id, + name: name.to_owned(), + release_year: Some(2011), + platforms: vec![], + cover_url: None, + } +} + +fn known(id: u64, name: &str) -> GameRecord { + GameRecord { + game_id: id, + name: name.to_owned(), + release_year: Some(2011), + platforms: vec![], + cover_url: None, + cover_file: None, + cover_failed_at: None, + } +} + +/// A verified library: Portal 2 (620, automatically matched to game 7), Dota 2 (570, unknown to +/// GameNode). Game 7 is known; game 40 is not. +fn library() -> LibraryMachine { + let mut cache = LibraryCache::default(); + for (id, name) in [("620", "Portal 2"), ("570", "Dota 2")] { + cache.entries.push(stored("steam", id, name, true)); + } + for (uid, ids) in [("620", vec![7]), ("570", vec![])] { + cache.auto_matches.push(AutoMatch { + category: 1, + uid: uid.to_owned(), + game_ids: ids, + checked_at: NOW, + }); + } + cache.games = vec![known(7, "Portal 2")]; + let (mut machine, _) = loaded(false, cache); + let op = machine.scan.as_ref().unwrap().op; + machine.handle(Input::ProviderScanned { + targets: Default::default(), + op, + provider: "steam".to_owned(), + result: Ok(vec![ + record("620", "Portal 2", "/g"), + record("570", "Dota 2", "/g"), + ]), + now: NOW, + }); + machine.handle(Input::SetAccess { + access: Access::Verified, + now: NOW, + }); + machine +} + +fn assign(machine: &mut LibraryMachine, id: &str, game_id: u64) -> Vec { + machine.handle(Input::AssignPluginMatch { + key: entry_key("steam", id), + game_id, + now: NOW + 1, + }) +} + +fn persisted_choices(effects: &[Effect]) -> Vec { + effects + .iter() + .filter_map(|effect| match effect { + Effect::PersistChoice { choice, .. } => Some(choice.clone()), + _ => None, + }) + .collect() +} + +fn matched(machine: &LibraryMachine, id: &str) -> Option { + machine + .match_status(machine.entry(&entry_key("steam", id)).unwrap()) + .game_id() +} + +#[test] +fn the_plan_names_why_an_assignment_is_not_possible() { + let mut machine = library(); + let key = entry_key("steam", "570"); + assert_eq!(machine.plan_plugin_match(&key, 7), PluginMatch::Assign); + assert_eq!( + machine.plan_plugin_match("steam:nope", 7), + PluginMatch::UnknownEntry + ); + assert_eq!( + machine.plan_plugin_match(&key, 40), + PluginMatch::UnknownGame + ); + machine.account = None; + assert_eq!(machine.plan_plugin_match(&key, 7), PluginMatch::NoAccount); +} + +#[test] +fn a_game_a_search_offered_can_be_assigned_and_is_stored_with_the_choice() { + let mut machine = library(); + assert!(assign(&mut machine, "570", 40).is_empty()); + assert_eq!(matched(&machine, "570"), None); + + machine.handle(Input::CatalogSearched { + games: vec![game(40, "Defense of the Ancients")], + }); + let effects = assign(&mut machine, "570", 40); + + let [choice] = persisted_choices(&effects).try_into().unwrap(); + assert_eq!(choice.entry_key, entry_key("steam", "570")); + assert_eq!(choice.game_id, Some(40)); + assert_eq!(choice.chosen_at, NOW + 1); + assert_eq!(choice.source, ChoiceSource::Plugin); + assert!(effects.iter().any(|effect| matches!( + effect, + Effect::PersistMatches { games, .. } if games.iter().any(|g| g.game_id == 40) + ))); + assert_eq!(matched(&machine, "570"), Some(40)); + assert_eq!(machine.game(40).unwrap().name, "Defense of the Ancients"); +} + +#[test] +fn a_known_game_needs_no_search() { + let mut machine = library(); + let effects = assign(&mut machine, "570", 7); + assert_eq!(persisted_choices(&effects).len(), 1); + assert_eq!(matched(&machine, "570"), Some(7)); +} + +#[test] +fn assigning_the_game_an_explicit_choice_already_names_changes_nothing() { + let mut machine = library(); + assert!(!assign(&mut machine, "570", 7).is_empty()); + assert_eq!( + machine.plan_plugin_match(&entry_key("steam", "570"), 7), + PluginMatch::Already + ); + assert!(assign(&mut machine, "570", 7).is_empty()); +} + +#[test] +fn an_automatic_match_is_pinned_by_an_assignment_of_the_same_game() { + let mut machine = library(); + assert_eq!(matched(&machine, "620"), Some(7)); + let effects = assign(&mut machine, "620", 7); + assert_eq!(persisted_choices(&effects)[0].source, ChoiceSource::Plugin); +} + +#[test] +fn a_plugin_replaces_its_own_choice_but_never_the_users() { + let mut machine = library(); + machine.handle(Input::CatalogSearched { + games: vec![game(40, "Other")], + }); + assign(&mut machine, "570", 7); + assert!(!assign(&mut machine, "570", 40).is_empty()); + assert_eq!(matched(&machine, "570"), Some(40)); + + // The user picks a different game in the dialog... + machine.chosen.insert( + entry_key("steam", "570"), + ChosenMatch { + entry_key: entry_key("steam", "570"), + game_id: Some(7), + chosen_at: NOW + 2, + source: ChoiceSource::User, + }, + ); + assert_eq!( + machine.plan_plugin_match(&entry_key("steam", "570"), 40), + PluginMatch::UserChoice + ); + assert!(assign(&mut machine, "570", 40).is_empty()); + assert_eq!(matched(&machine, "570"), Some(7)); + + // ...and "no game" is a choice too. + machine + .chosen + .get_mut(&entry_key("steam", "570")) + .unwrap() + .game_id = None; + assert_eq!( + machine.plan_plugin_match(&entry_key("steam", "570"), 7), + PluginMatch::UserChoice + ); +} + +#[test] +fn the_user_picking_the_plugins_game_makes_it_theirs() { + let mut machine = library(); + let key = entry_key("steam", "570"); + machine.handle(Input::CatalogSearched { + games: vec![game(40, "Defense of the Ancients")], + }); + assign(&mut machine, "570", 40); + assert_eq!( + machine.chosen_match(&key).unwrap().source, + ChoiceSource::Plugin + ); + + machine.handle(Input::Select { + key: key.clone(), + mode: SelectMode::Replace, + }); + let effects = machine.handle(Input::OpenMatch); + let op = effects + .iter() + .find_map(|effect| match effect { + Effect::SearchGames { op, .. } => Some(*op), + _ => None, + }) + .expect("opening searches the detected title"); + machine.handle(Input::MatchSearched { + op, + result: Ok(vec![game(40, "Defense of the Ancients")]), + }); + let effects = machine.handle(Input::PickMatch { + game_id: 40, + now: NOW + 3, + }); + + assert_eq!(persisted_choices(&effects)[0].source, ChoiceSource::User); + assert_eq!( + machine.chosen_match(&key).unwrap().source, + ChoiceSource::User + ); + assert_eq!(machine.plan_plugin_match(&key, 40), PluginMatch::Already); + machine.handle(Input::CatalogSearched { + games: vec![game(41, "Other")], + }); + assert_eq!(machine.plan_plugin_match(&key, 41), PluginMatch::UserChoice); +} + +#[test] +fn offers_are_bounded_and_the_oldest_drop_first() { + let mut machine = library(); + let games: Vec<_> = (0..MAX_OFFERED_GAMES as u64 + 5) + .map(|id| game(1000 + id, "Game")) + .collect(); + machine.handle(Input::CatalogSearched { games }); + assert_eq!(machine.offered.len(), MAX_OFFERED_GAMES); + let key = entry_key("steam", "570"); + assert_eq!( + machine.plan_plugin_match(&key, 1000), + PluginMatch::UnknownGame + ); + assert_eq!( + machine.plan_plugin_match(&key, 1004), + PluginMatch::UnknownGame + ); + assert_eq!(machine.plan_plugin_match(&key, 1005), PluginMatch::Assign); +} diff --git a/crates/core/src/library/query.rs b/crates/core/src/library/query.rs index 8868e9aed..3bf1b2d88 100644 --- a/crates/core/src/library/query.rs +++ b/crates/core/src/library/query.rs @@ -30,7 +30,7 @@ use super::machine::LibraryMachine; use super::matching::{self, MatchStatus}; use super::membership::EntryStatus; use super::organization::SavedView; -use super::store::StoredEntry; +use super::store::{GameRecord, StoredEntry}; /// One visible game as the view shows it. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] @@ -335,6 +335,27 @@ impl LibraryMachine { matching::resolve(self.chosen.get(&entry.key), auto) } + /// The cover an entry shows: its provider plugin's override if one is set, else the matched + /// game's own. + fn cover_for(&self, key: &str, game: Option<&GameRecord>) -> Option { + self.artwork_overrides + .get(key) + .and_then(|over| over.file.clone()) + .or_else(|| self.local_covers.get(key).cloned()) + .or_else(|| game.and_then(|game| game.cover_file.clone())) + } + + /// The cover file of the entry `key` as the library shows it, if the entry is known and has + /// one. + pub fn entry_cover_file(&self, key: &str) -> Option { + let entry = self.entries.get(key)?; + let game = self + .match_status(entry) + .game_id() + .and_then(|id| self.games.get(&id)); + self.cover_for(key, game) + } + fn row(&self, entry: &StoredEntry) -> Row { let status = self.match_status(entry); let game = status.game_id().and_then(|id| self.games.get(&id)); @@ -363,8 +384,12 @@ impl LibraryMachine { // The execution start the live session clock counts from; `None` when not running. session_started_at: self.running.get(&entry.key).copied(), key: entry.key.clone(), - title: matched_name - .clone() + // A plugin's display override wins, then the matched game's name, then the detected one. + title: self + .display_overrides + .get(&entry.key) + .and_then(|over| over.display_name.clone()) + .or_else(|| matched_name.clone()) .unwrap_or_else(|| detected_name.clone()), detected_name, matched_name, @@ -376,11 +401,7 @@ impl LibraryMachine { owned: entry.owned, shared: entry.shared && !entry.owned, status, - cover_file: self - .local_covers - .get(&entry.key) - .cloned() - .or_else(|| game_cover_file.clone()), + cover_file: self.cover_for(&entry.key, game), game_cover_file, release_year: game.and_then(|game| game.release_year), added_at: entry.first_seen, diff --git a/crates/core/src/library/query/tests.rs b/crates/core/src/library/query/tests.rs index a11e86d32..d13eb3689 100644 --- a/crates/core/src/library/query/tests.rs +++ b/crates/core/src/library/query/tests.rs @@ -8,6 +8,7 @@ use crate::library::machine::tests::{ use crate::library::matching::MatchSource; use crate::library::store::{AccountLibrary, AutoMatch, ChosenMatch, GameRecord, LibraryCache}; use crate::library::{Effect, SavedViewPayload}; +use std::collections::BTreeMap; fn row(provider: &str, id: &str, title: &str, status: MatchStatus) -> Row { Row { @@ -515,6 +516,7 @@ fn provider_counts_carry_the_location_reported_by_the_latest_scan() { op: steam_op, provider: "steam".to_owned(), result: Ok(Vec::new()), + targets: Default::default(), now: 10, }); let steam = machine @@ -547,6 +549,7 @@ fn the_machine_shows_only_installed_games_with_matched_titles_and_covers() { entry_key: "steam:70".to_owned(), game_id: None, chosen_at: 1, + source: Default::default(), }], games: vec![GameRecord { game_id: 7, @@ -2152,6 +2155,230 @@ fn provider_counts_follow_every_facet_except_the_sidebar_and_stay_raw_for_facts( assert_eq!(steam.count, 1); } +fn override_cache(display_overrides: Vec) -> LibraryCache { + LibraryCache { + entries: vec![ + stored("steam", "620", "portal 2", true), + stored("steam", "70", "Half-Life", true), + ], + auto_matches: vec![AutoMatch { + category: 1, + uid: "620".to_owned(), + game_ids: vec![7], + checked_at: 1, + }], + games: vec![GameRecord { + game_id: 7, + name: "Portal 2".to_owned(), + release_year: None, + cover_url: None, + cover_file: None, + cover_failed_at: None, + platforms: vec![], + }], + display_overrides, + ..LibraryCache::default() + } +} + +fn titles(machine: &mut LibraryMachine) -> BTreeMap { + machine + .all_rows() + .into_iter() + .map(|row| (row.key, row.title)) + .collect() +} + +fn scan_both(machine: &mut LibraryMachine) { + finish_scan( + machine, + vec![ + record("620", "portal 2", "/p"), + record("70", "Half-Life", "/h"), + ], + 9, + ); +} + +fn stored_override(machine: &mut LibraryMachine, key: &str, name: Option<&str>, revision: u64) { + machine.handle(Input::DisplayNameStored { + key: key.to_owned(), + display_name: name.map(str::to_owned), + revision, + }); +} + +#[test] +fn a_plugin_display_name_wins_over_the_matched_and_detected_titles_until_cleared() { + let (mut machine, _) = loaded(false, override_cache(vec![])); + scan_both(&mut machine); + assert_eq!( + titles(&mut machine)["steam:620"], + "Portal 2", + "matched name" + ); + assert_eq!( + titles(&mut machine)["steam:70"], + "Half-Life", + "detected name" + ); + + stored_override(&mut machine, "steam:620", Some("Portal Two"), 1); + stored_override(&mut machine, "steam:70", Some("HL"), 1); + let rows = machine.all_rows(); + let portal = rows.iter().find(|row| row.key == "steam:620").unwrap(); + // The facts stay separate from the override. + assert_eq!(portal.title, "Portal Two"); + assert_eq!(portal.matched_name.as_deref(), Some("Portal 2")); + assert_eq!(portal.detected_name, "portal 2"); + assert_eq!(titles(&mut machine)["steam:70"], "HL"); + + // Clearing restores each entry's previous title and the revision keeps counting. + stored_override(&mut machine, "steam:620", None, 2); + stored_override(&mut machine, "steam:70", None, 2); + assert_eq!(titles(&mut machine)["steam:620"], "Portal 2"); + assert_eq!(titles(&mut machine)["steam:70"], "Half-Life"); + let cleared = machine.display_override("steam:620").unwrap(); + assert_eq!( + (cleared.display_name.as_deref(), cleared.revision), + (None, 2) + ); +} + +#[test] +fn a_display_name_for_an_unknown_entry_is_ignored() { + let (mut machine, _) = loaded(false, override_cache(vec![])); + scan_both(&mut machine); + stored_override(&mut machine, "steam:nope", Some("Ghost"), 1); + assert!(machine.display_override("steam:nope").is_none()); + assert_eq!(titles(&mut machine).len(), 2); +} + +#[test] +fn stored_display_names_load_with_their_revision() { + let (mut machine, _) = loaded( + false, + override_cache(vec![ + crate::library::DisplayOverride { + entry_key: "steam:620".to_owned(), + display_name: Some("Portal Two".to_owned()), + revision: 4, + }, + // Cleared earlier: no name, but its revision is kept. + crate::library::DisplayOverride { + entry_key: "steam:70".to_owned(), + display_name: None, + revision: 2, + }, + ]), + ); + scan_both(&mut machine); + assert_eq!(titles(&mut machine)["steam:620"], "Portal Two"); + assert_eq!(titles(&mut machine)["steam:70"], "Half-Life"); + assert_eq!(machine.display_override("steam:620").unwrap().revision, 4); + assert_eq!(machine.display_override("steam:70").unwrap().revision, 2); +} + +fn covers_cache(artwork_overrides: Vec) -> LibraryCache { + let mut cache = override_cache(vec![]); + cache.games[0].cover_file = Some("7.jpg".to_owned()); + cache.artwork_overrides = artwork_overrides; + cache +} + +fn covers(machine: &mut LibraryMachine) -> BTreeMap> { + machine + .all_rows() + .into_iter() + .map(|row| (row.key, row.cover_file)) + .collect() +} + +fn stored_cover(machine: &mut LibraryMachine, key: &str, file: Option<&str>, revision: u64) { + machine.handle(Input::ArtworkStored { + key: key.to_owned(), + file: file.map(str::to_owned), + revision, + }); +} + +#[test] +fn a_plugin_cover_wins_over_the_matched_games_cover_until_cleared() { + let (mut machine, _) = loaded(false, covers_cache(vec![])); + scan_both(&mut machine); + assert_eq!(covers(&mut machine)["steam:620"].as_deref(), Some("7.jpg")); + assert_eq!(covers(&mut machine)["steam:70"], None, "no matched game"); + + // The override replaces the game's cover for this entry, and also gives an unmatched entry + // a cover; the game record is untouched. + stored_cover(&mut machine, "steam:620", Some("plugin-a-b.jpg"), 1); + stored_cover(&mut machine, "steam:70", Some("plugin-c-d.png"), 1); + assert_eq!( + covers(&mut machine)["steam:620"].as_deref(), + Some("plugin-a-b.jpg") + ); + assert_eq!( + covers(&mut machine)["steam:70"].as_deref(), + Some("plugin-c-d.png") + ); + assert_eq!( + machine.game(7).unwrap().cover_file.as_deref(), + Some("7.jpg") + ); + assert_eq!( + machine.entry_cover_file("steam:620").as_deref(), + Some("plugin-a-b.jpg") + ); + + // Clearing restores each entry's own cover and the revision keeps counting. + stored_cover(&mut machine, "steam:620", None, 2); + stored_cover(&mut machine, "steam:70", None, 2); + assert_eq!(covers(&mut machine)["steam:620"].as_deref(), Some("7.jpg")); + assert_eq!(covers(&mut machine)["steam:70"], None); + assert_eq!( + machine.entry_cover_file("steam:620").as_deref(), + Some("7.jpg") + ); + assert_eq!(machine.artwork_override("steam:620").unwrap().revision, 2); +} + +#[test] +fn a_cover_for_an_unknown_entry_is_ignored() { + let (mut machine, _) = loaded(false, covers_cache(vec![])); + scan_both(&mut machine); + stored_cover(&mut machine, "steam:nope", Some("plugin-x-y.jpg"), 1); + assert!(machine.artwork_override("steam:nope").is_none()); + assert_eq!(machine.entry_cover_file("steam:nope"), None); +} + +#[test] +fn stored_covers_load_with_their_revision() { + let (mut machine, _) = loaded( + false, + covers_cache(vec![ + crate::library::ArtworkOverride { + entry_key: "steam:620".to_owned(), + file: Some("plugin-a-b.jpg".to_owned()), + revision: 4, + }, + // Cleared earlier: no file, but its revision is kept. + crate::library::ArtworkOverride { + entry_key: "steam:70".to_owned(), + file: None, + revision: 2, + }, + ]), + ); + scan_both(&mut machine); + assert_eq!( + covers(&mut machine)["steam:620"].as_deref(), + Some("plugin-a-b.jpg") + ); + assert_eq!(covers(&mut machine)["steam:70"], None); + assert_eq!(machine.artwork_override("steam:620").unwrap().revision, 4); + assert_eq!(machine.artwork_override("steam:70").unwrap().revision, 2); +} + #[test] fn a_local_custom_cover_wins_over_the_gamenode_cover_and_survives_a_match() { let game = |id: u64, cover: &str| GameRecord { @@ -2164,12 +2391,12 @@ fn a_local_custom_cover_wins_over_the_gamenode_cover_and_survives_a_match() { platforms: vec![], }; let cache = LibraryCache { - entries: vec![stored("manual", "1", "Game", true)], + entries: vec![stored("steam", "1", "Game", true)], games: vec![game(7, "7.jpg"), game(8, "8.jpg")], ..LibraryCache::default() }; let (mut machine, _) = loaded(false, cache); - let key = "manual:1".to_owned(); + let key = "steam:1".to_owned(); machine.set_local_inference(key.clone(), Some(7), None); machine.replace_local_covers(std::collections::BTreeMap::from([( key.clone(), diff --git a/crates/core/src/library/runtime.rs b/crates/core/src/library/runtime.rs new file mode 100644 index 000000000..ac6be9321 --- /dev/null +++ b/crates/core/src/library/runtime.rs @@ -0,0 +1,272 @@ +//! Approved runtime resources and content-to-runtime bindings. +//! +//! Runtime paths and content locations are never stored here. Resource handles are opaque host +//! identifiers, and game/install identity remains independent of the runtime that can launch it. + +use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; + +pub const MAX_RUNTIME_ID_BYTES: usize = 128; +pub const MAX_RUNTIME_FIELD_BYTES: usize = 4096; +pub const MAX_RUNTIME_ITEMS: usize = 128; +/// Bounded declarative metadata namespaces per runtime. +pub const MAX_RUNTIME_EXTENSIONS: usize = 32; +/// Total serialized size of a runtime's declarative metadata. +pub const MAX_RUNTIME_EXTENSION_BYTES: usize = 64 * 1024; + +/// A durable, host-only reference to a location inside an approved file root. Unlike the opaque +/// handle returned to a plugin, this reference is not session-sealed and can be stored. It never +/// includes an absolute path; the host rechecks the approval and resolves the relative path when +/// it issues a fresh session handle or launches a runtime. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ApprovedFileReference { + pub approval_id: String, + pub relative_path: Vec, +} + +impl ApprovedFileReference { + pub fn validate(&self) -> bool { + !self.approval_id.is_empty() + && self.approval_id.len() <= MAX_RUNTIME_ID_BYTES + && !self + .approval_id + .chars() + .any(|ch| ch == '\0' || ch.is_control()) + && self.relative_path.len() <= MAX_RUNTIME_ITEMS + && self.relative_path.iter().all(|part| { + !part.is_empty() + && part.len() <= MAX_RUNTIME_FIELD_BYTES + && part != "." + && part != ".." + && !part.chars().any(|ch| matches!(ch, '/' | '\\' | '\0')) + && !part.chars().any(char::is_control) + }) + } +} + +/// Host-recorded provenance of the authenticated plugin that registered a runtime. +/// +/// The host writes these values from the verified package and session, never from a plugin +/// payload. Older stored records deserialize with empty provenance. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct RuntimeProvenance { + pub plugin_id: String, + pub declared_developer: String, + pub origin: String, + pub publisher_fingerprint: String, + pub package_version: String, + #[serde(default)] + pub package_digest: Vec, +} + +impl RuntimeProvenance { + pub fn is_empty(&self) -> bool { + self.plugin_id.is_empty() + && self.declared_developer.is_empty() + && self.origin.is_empty() + && self.publisher_fingerprint.is_empty() + && self.package_version.is_empty() + && self.package_digest.is_empty() + } + + fn validate(&self) -> bool { + let valid = |value: &str, max: usize| { + value.len() <= max && !value.chars().any(|ch| ch == '\0' || ch.is_control()) + }; + valid(&self.plugin_id, MAX_RUNTIME_ID_BYTES) + && valid(&self.declared_developer, MAX_RUNTIME_FIELD_BYTES) + && valid(&self.origin, MAX_RUNTIME_FIELD_BYTES) + && valid(&self.publisher_fingerprint, MAX_RUNTIME_ID_BYTES) + && valid(&self.package_version, MAX_RUNTIME_FIELD_BYTES) + && self.package_digest.len() <= 64 + } +} + +/// One namespaced declarative metadata payload. It is an annotation only: the host never treats +/// it as identity, authorization, a path or an executable command. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct RuntimeExtension { + pub schema_id: String, + pub schema_version: u32, + #[serde(default)] + pub schema_digest: Vec, + pub data: serde_json::Value, +} + +impl RuntimeExtension { + fn validate(&self) -> bool { + !self.schema_id.is_empty() + && self.schema_id.len() <= MAX_RUNTIME_FIELD_BYTES + && !self + .schema_id + .chars() + .any(|ch| ch == '\0' || ch.is_control()) + && self.data.is_object() + } +} + +/// A plugin-owned, host-approved installed runtime. This describes software already present on +/// the host; registering it never installs or downloads anything. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct RuntimeResource { + pub id: String, + pub name: String, + pub version: String, + /// Stable host-only reference to an approved executable; never a session token or path. + pub executable: ApprovedFileReference, + /// Target platform identifier, such as `linux` or `windows`. + pub platform: String, + /// Content formats this runtime can execute, such as `snes-rom`. + pub supported_formats: Vec, + /// Ordered argument template. Each token is a literal or a content path; never shell text. + pub launch_arguments: Vec, + #[serde(default)] + pub revision: u64, + /// Unix seconds assigned by the host when the resource is stored. + pub observed_at: i64, + /// Host-recorded registering-plugin provenance; empty for records saved before it existed. + #[serde(default)] + pub provenance: RuntimeProvenance, + /// Validated declarative metadata namespaces. Annotations only; never authority. + #[serde(default)] + pub extensions: BTreeMap, +} + +fn validate_extensions(extensions: &BTreeMap) -> bool { + extensions.len() <= MAX_RUNTIME_EXTENSIONS + && extensions.iter().all(|(namespace, extension)| { + valid_extension_namespace(namespace) && extension.validate() + }) + && extensions + .values() + .filter_map(|extension| serde_json::to_vec(&extension.data).ok()) + .map(|data| data.len()) + .sum::() + <= MAX_RUNTIME_EXTENSION_BYTES +} + +fn valid_extension_namespace(namespace: &str) -> bool { + !namespace.is_empty() + && namespace.len() <= MAX_RUNTIME_ID_BYTES + && namespace + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'-' | b'_')) +} + +impl RuntimeResource { + pub fn validate(&self) -> bool { + let valid_text = |value: &str, max: usize| { + !value.is_empty() + && value.len() <= max + && !value.chars().any(|ch| ch == '\0' || ch.is_control()) + }; + valid_text(&self.id, MAX_RUNTIME_ID_BYTES) + && valid_text(&self.name, MAX_RUNTIME_FIELD_BYTES) + && self.version.len() <= MAX_RUNTIME_FIELD_BYTES + && !self.version.chars().any(|ch| ch == '\0' || ch.is_control()) + && self.executable.validate() + && valid_text(&self.platform, MAX_RUNTIME_ID_BYTES) + && !self.supported_formats.is_empty() + && self.supported_formats.len() <= MAX_RUNTIME_ITEMS + && self + .supported_formats + .iter() + .all(|format| valid_text(format, MAX_RUNTIME_ID_BYTES)) + && self.launch_arguments.len() <= MAX_RUNTIME_ITEMS + && self + .launch_arguments + .iter() + .all(RuntimeArgumentTemplate::validate) + && self.revision > 0 + && self.observed_at >= 0 + && self.provenance.validate() + && validate_extensions(&self.extensions) + } +} + +/// One token in a runtime's argument vector. The host inserts a content path as one argv item; +/// literal arguments remain separate items and are never expanded by a shell. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", tag = "kind", content = "value")] +pub enum RuntimeArgumentTemplate { + Literal(String), + ContentPath, +} + +impl RuntimeArgumentTemplate { + fn validate(&self) -> bool { + match self { + Self::Literal(value) => value.len() <= MAX_RUNTIME_FIELD_BYTES && !value.contains('\0'), + Self::ContentPath => true, + } + } +} + +/// A stable logical game's content as runnable by one plugin-owned runtime. +/// +/// `content_id` remains stable when content is moved or renamed; `content` identifies its current +/// approved location and is not a path or file payload. The composite key allows one content to +/// have several selectable runtime bindings and one runtime to serve many games. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct RuntimeContentBinding { + pub game_id: u64, + pub installation_id: String, + /// Stable host-issued identity, independent of content's current name or location. + pub content_id: String, + /// Current approved host-only location, never a session token or absolute path. + pub content: ApprovedFileReference, + pub content_kind: String, + pub runtime_id: String, + pub supported_platforms: Vec, + pub revision: u64, +} + +impl RuntimeContentBinding { + pub fn validate(&self) -> bool { + let valid = |value: &str, max: usize| { + !value.is_empty() + && value.len() <= max + && !value.chars().any(|ch| ch == '\0' || ch.is_control()) + }; + self.game_id > 0 + && valid(&self.installation_id, MAX_RUNTIME_ID_BYTES) + && valid(&self.content_id, MAX_RUNTIME_ID_BYTES) + && self.content.validate() + && valid(&self.content_kind, MAX_RUNTIME_ID_BYTES) + && valid(&self.runtime_id, MAX_RUNTIME_ID_BYTES) + && self.supported_platforms.len() <= MAX_RUNTIME_ITEMS + && self + .supported_platforms + .iter() + .all(|platform| valid(platform, MAX_RUNTIME_ID_BYTES)) + && self.revision > 0 + } +} + +/// Safe content/runtime availability projection for one installation. It never carries a path, +/// handle or payload; shared rows identify the registering plugin, not a private field. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct RuntimeAvailabilityEntry { + pub installation_id: String, + pub content_id: String, + pub content_kind: String, + pub runtime_id: String, + pub runtime_name: String, + pub platform: String, + pub publisher_id: String, + pub revision: u64, +} + +/// Outcome of a revision-checked runtime or binding mutation. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum RuntimeMutation { + Applied { revision: u64 }, + Conflict { current: u64 }, + Missing, +} diff --git a/crates/core/src/library/selection/tests.rs b/crates/core/src/library/selection/tests.rs index 1bc1e92ed..83aaa720d 100644 --- a/crates/core/src/library/selection/tests.rs +++ b/crates/core/src/library/selection/tests.rs @@ -235,6 +235,21 @@ fn grouped_grid_navigation_starts_each_group_on_a_new_line_and_clamps_columns() #[test] fn grouped_navigation_skips_collapsed_groups_through_the_machine() { let mut machine = library_of(4); + let manifest = |id: &str| { + format!( + "id = \"{id}\"\nname = \"{}\"\nplatforms = [\"windows\", \"linux\"]\nsource = \"{id}\"\nscan = {{ native = \"manual\" }}\n", + id.to_uppercase() + ) + }; + let (gog, shop) = (manifest("gog"), manifest("shop")); + let loaded = crate::provider::registry::tests::load( + &[("gog.toml", &gog), ("shop.toml", &shop)], + crate::provider::Platform::Linux, + ); + assert!(loaded.diagnostics.is_empty(), "{:?}", loaded.diagnostics); + for provider in loaded.providers { + machine.put_provider(provider); + } for (provider, title) in [("gog", "GOG Game"), ("shop", "Shop Game")] { machine.entries.insert( format!("{provider}:1"), @@ -245,6 +260,7 @@ fn grouped_navigation_skips_collapsed_groups_through_the_machine() { name: Some(title.to_owned()), install_dir: format!("/{provider}"), fields: Default::default(), + target: None, installed: true, owned: false, shared: false, diff --git a/crates/core/src/library/store.rs b/crates/core/src/library/store.rs index 4fde1d9fc..0cd42a9bb 100644 --- a/crates/core/src/library/store.rs +++ b/crates/core/src/library/store.rs @@ -32,6 +32,10 @@ pub struct StoredEntry { pub install_dir: String, pub fields: BTreeMap, pub installed: bool, + /// The launch target the provider detected for this entry, if any (task 7.7). It is stored + /// apart from `fields` so a Struct/opaque field can never become an executable target. + #[serde(default)] + pub target: Option, /// Found by the connected store account's owned catalog. #[serde(default)] pub owned: bool, @@ -204,6 +208,37 @@ pub struct ChosenMatch { pub entry_key: String, pub game_id: Option, pub chosen_at: i64, + /// Who made the choice. Stored choices from before plugins existed read as the user's. + #[serde(default)] + pub source: ChoiceSource, +} + +/// Who made a [`ChosenMatch`]. A plugin may replace its own choices but never the user's. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum ChoiceSource { + /// Picked in the match dialog (including "no GameNode game"). + #[default] + User, + /// Assigned by a plugin through the plugin API for its own entry. + Plugin, +} + +impl ChoiceSource { + pub fn as_str(self) -> &'static str { + match self { + Self::User => "user", + Self::Plugin => "plugin", + } + } + + pub fn parse(text: &str) -> Option { + match text { + "user" => Some(Self::User), + "plugin" => Some(Self::Plugin), + _ => None, + } + } } /// GameNode game metadata kept for display. @@ -239,6 +274,55 @@ pub struct FavoriteRecord { pub updated_at: i64, } +/// A presentation override a provider's plugin wrote for one of its own entries. It is kept apart +/// from the detected facts: clearing it (`display_name = None`) restores the detected name. The +/// revision counts writes per entry, starts at 1 and only ever grows, so a reset keeps its row. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct DisplayOverride { + pub entry_key: String, + pub display_name: Option, + pub revision: u64, +} + +/// How a guarded display-name write ended. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum DisplayWrite { + /// The value changed; this is the entry's new revision. + Applied { revision: u64 }, + /// The entry already had this value; its revision is unchanged. + Unchanged { revision: u64 }, + /// The expected revision was obsolete; nothing was written. + Conflict { current: u64 }, +} + +/// The cover a provider's plugin set for one of its own entries. `file` names an image in the +/// covers folder that only this entry owns; the game's own cover is never touched. Clearing it +/// (`file = None`) restores the game's cover. The revision counts writes per entry, starts at 1 +/// and only ever grows, so a reset keeps its row. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ArtworkOverride { + pub entry_key: String, + pub file: Option, + pub revision: u64, +} + +/// How a guarded artwork write ended. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum ArtworkWrite { + /// The value changed; this is the entry's new revision, and `replaced` the file it no longer + /// uses (which the caller deletes). + Applied { + revision: u64, + replaced: Option, + }, + /// The entry already had this value; its revision is unchanged. + Unchanged { revision: u64 }, + /// The expected revision was obsolete; nothing was written. + Conflict { current: u64 }, +} + /// The account's last complete GameNode library read: one entry per game it knows, the account's /// collections and when the read finished. Games that exist only in the account library are still /// not library rows; the cache feeds status columns, the status facet, collection scopes and the @@ -267,6 +351,12 @@ pub struct LibraryCache { pub favorites: Vec, pub games: Vec, pub excluded: Vec, + /// Presentation overrides written by providers' plugins. + #[serde(default)] + pub display_overrides: Vec, + /// Covers written by providers' plugins. + #[serde(default)] + pub artwork_overrides: Vec, /// The account's saved views, in sidebar order. Populated by the organization work. #[serde(default)] pub saved_views: Vec, @@ -286,6 +376,17 @@ pub struct LastAccount { pub name: String, } +/// What happened to an approval or repair of a detected target. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum TargetApproval { + /// The target was stored at this revision with the new decision. + Applied { revision: u64 }, + /// The target changed since the caller read it; nothing was written. + Conflict { current: u64 }, + /// The entry has no detected target any more. + Missing, +} + /// Library persistence. All calls may block; run them on the storage worker. /// /// `now` is unix seconds, passed in so this crate never reads the clock. @@ -294,12 +395,250 @@ pub trait LibraryStore: Send + Sync { /// Records a completed scan of `provider` in one transaction: its entries in `records` are /// inserted or refreshed and installed, entries it no longer finds are marked uninstalled, and - /// the provider's state shows the success. Other providers are untouched. - fn save_scan(&self, provider: &str, records: &[Record], now: i64) -> Result<(), StorageError>; + /// the provider's state shows the success. `targets` carries the detected launch target of + /// each record id, if any; a target no longer reported stays stored but unavailable. Other + /// providers are untouched. + fn save_scan( + &self, + provider: &str, + records: &[Record], + targets: &std::collections::BTreeMap, + now: i64, + ) -> Result<(), StorageError>; /// Records that a scan of `provider` failed. Its entries are left as they were. fn save_scan_failure(&self, provider: &str, error: &str) -> Result<(), StorageError>; + /// Stores the user's approval (or repair) of `entry_key`'s detected target if its revision is + /// still `expected_revision`. A changed target is a conflict and writes nothing. + fn save_target_review( + &self, + entry_key: &str, + expected_revision: u64, + replacement: &super::target::DetectedTarget, + ) -> Result { + let _ = (entry_key, expected_revision, replacement); + Ok(TargetApproval::Missing) + } + + /// One plugin-owned recipe, scoped by a host-derived owner key. + fn custom_launch_recipe( + &self, + owner_key: &str, + recipe_id: &str, + ) -> Result, StorageError> { + let _ = (owner_key, recipe_id); + Err(StorageError::Failed( + "custom launch recipes are unavailable in this store".into(), + )) + } + + /// Persists a new host-issued recipe or reports the already-stored revision. + fn save_custom_launch_recipe( + &self, + owner_key: &str, + recipe: &super::custom_launch::CustomLaunchRecipe, + ) -> Result { + let _ = (owner_key, recipe); + Err(StorageError::Failed( + "custom launch recipes are unavailable in this store".into(), + )) + } + + fn remove_custom_launch_recipe( + &self, + owner_key: &str, + recipe_id: &str, + expected_revision: u64, + ) -> Result { + let _ = (owner_key, recipe_id, expected_revision); + Err(StorageError::Failed( + "custom launch recipes are unavailable in this store".into(), + )) + } + + /// Lists recipes owned by one authenticated plugin for an installation. + fn custom_launch_recipes( + &self, + owner_key: &str, + game_id: u64, + ) -> Result, StorageError> { + let _ = (owner_key, game_id); + Ok(Vec::new()) + } + + /// The user's active custom launch choice. No row means the detected target is active. + fn launch_recipe_selection( + &self, + entry_key: &str, + ) -> Result, StorageError> { + let _ = entry_key; + Ok(None) + } + + /// Persists a user-selected recipe only while its game target and recipe revisions match. + fn save_launch_recipe_selection( + &self, + selection: &super::custom_launch::LaunchRecipeSelection, + expected_target_revision: u64, + ) -> Result { + let _ = (selection, expected_target_revision); + Ok(super::custom_launch::LaunchRecipeSelectionWrite::RecipeMissing) + } + + /// Explicitly returns the entry to its detected default, using target revision CAS. + fn clear_launch_recipe_selection( + &self, + entry_key: &str, + expected_target_revision: u64, + ) -> Result { + let _ = (entry_key, expected_target_revision); + Ok(super::custom_launch::LaunchRecipeSelectionWrite::RecipeMissing) + } + + /// Records remembered user approval for the currently selected, exact plan. + fn approve_launch_recipe_plan( + &self, + entry_key: &str, + recipe_id: &str, + recipe_revision: u64, + expected_target_revision: u64, + fingerprint: &str, + ) -> Result { + let _ = ( + entry_key, + recipe_id, + recipe_revision, + expected_target_revision, + fingerprint, + ); + Ok(super::custom_launch::LaunchRecipeSelectionWrite::RecipeMissing) + } + + /// Lists this plugin owner's approved runtime resources. + fn runtime_resources( + &self, + owner_key: &str, + ) -> Result, StorageError> { + let _ = owner_key; + Err(StorageError::Failed( + "runtime resources are unavailable in this store".into(), + )) + } + + /// Lists every owner's runtimes for an authorized common-category read. + fn shared_runtime_resources( + &self, + ) -> Result, StorageError> { + Err(StorageError::Failed( + "runtime resources are unavailable in this store".into(), + )) + } + + /// Combined catalog revision across every owner, for a shared read subscription. + fn shared_runtime_catalog_revision(&self) -> Result { + Err(StorageError::Failed( + "runtime resources are unavailable in this store".into(), + )) + } + + /// Safe availability rows for the named installations. `owner_key` limits the projection to + /// the caller's private bindings; `None` includes every owner for an authorized category read. + fn runtime_availability( + &self, + owner_key: Option<&str>, + installation_ids: &[String], + ) -> Result, StorageError> { + let _ = (owner_key, installation_ids); + Err(StorageError::Failed( + "runtime availability is unavailable in this store".into(), + )) + } + + /// Looks up one runtime without exposing another plugin owner's private record. + fn runtime_resource( + &self, + owner_key: &str, + runtime_id: &str, + ) -> Result, StorageError> { + let _ = (owner_key, runtime_id); + Err(StorageError::Failed( + "runtime resources are unavailable in this store".into(), + )) + } + + /// Creates a new runtime at revision 1 or updates it only at current revision + 1. + fn save_runtime_resource( + &self, + owner_key: &str, + runtime: &super::runtime::RuntimeResource, + ) -> Result { + let _ = (owner_key, runtime); + Err(StorageError::Failed( + "runtime resources are unavailable in this store".into(), + )) + } + + /// Removes only the runtime record. Historical content bindings deliberately remain so they + /// can be shown as unavailable and migrated; games, saves and play history are independent. + fn remove_runtime_resource( + &self, + owner_key: &str, + runtime_id: &str, + expected_revision: u64, + ) -> Result { + let _ = (owner_key, runtime_id, expected_revision); + Err(StorageError::Failed( + "runtime resources are unavailable in this store".into(), + )) + } + + /// Lists runtime bindings for a stable GameNode game and installation identity. + fn runtime_content_bindings( + &self, + owner_key: &str, + game_id: u64, + installation_id: &str, + ) -> Result, StorageError> { + let _ = (owner_key, game_id, installation_id); + Err(StorageError::Failed( + "runtime bindings are unavailable in this store".into(), + )) + } + + /// Durable watch cursor for this owner's runtime and content catalog. + fn runtime_catalog_revision(&self, owner_key: &str) -> Result { + let _ = owner_key; + Err(StorageError::Failed( + "runtime resources are unavailable in this store".into(), + )) + } + + /// Upserts one binding by owner/game/installation/content/runtime identity, revision-checked. + /// If the stable content locator changes, update all sibling runtime bindings for that content + /// atomically and advance their revisions too. + fn save_runtime_content_binding( + &self, + owner_key: &str, + binding: &super::runtime::RuntimeContentBinding, + ) -> Result { + let _ = (owner_key, binding); + Err(StorageError::Failed( + "runtime bindings are unavailable in this store".into(), + )) + } + + fn remove_runtime_content_binding( + &self, + owner_key: &str, + binding: &super::runtime::RuntimeContentBinding, + ) -> Result { + let _ = (owner_key, binding); + Err(StorageError::Failed( + "runtime bindings are unavailable in this store".into(), + )) + } + /// Applies an owned or shared catalog result for `provider`, replacing only the fact sets the /// update covers and leaving installed facts, matches and covers untouched. fn save_catalog(&self, provider: &str, update: &CatalogUpdate) -> Result<(), StorageError>; @@ -389,6 +728,32 @@ pub trait LibraryStore: Send + Sync { Ok(()) } + /// The opaque installation ids of the entries in `entry_keys`, as `(entry key, id)` pairs. + /// A key without an id is given a new random one in the same transaction, so every returned + /// id is durable and never changes for its key. Keys are not checked against the entries. + fn installation_ids( + &self, + entry_keys: &[String], + ) -> Result, StorageError>; + + /// Sets (`Some`) or clears (`None`) the display-name override of `entry_key` if its current + /// revision is `expected_revision` (0 when it was never written), in one transaction. + fn save_display_name( + &self, + entry_key: &str, + expected_revision: u64, + display_name: Option<&str>, + ) -> Result; + + /// Sets (`Some`) or clears (`None`) the artwork override of `entry_key` if its current + /// revision is `expected_revision` (0 when it was never written), in one transaction. + fn save_artwork( + &self, + entry_key: &str, + expected_revision: u64, + file: Option<&str>, + ) -> Result; + fn load_last_account(&self) -> Result, StorageError>; fn save_last_account(&self, account: &LastAccount) -> Result<(), StorageError>; /// Removes the last-account record. The cache and chosen matches stay for a later sign-in. diff --git a/crates/core/src/library/suggest.rs b/crates/core/src/library/suggest.rs index 6bfd1faaa..10fd937da 100644 --- a/crates/core/src/library/suggest.rs +++ b/crates/core/src/library/suggest.rs @@ -204,13 +204,45 @@ fn game_summary(record: &GameRecord) -> GameSummary { } pub(super) fn search_query(entry: &StoredEntry) -> String { - entry - .name - .as_deref() + let title = entry + .fields + .get("title") + .map(String::as_str) + .or(entry.name.as_deref()) .map(str::trim) - .filter(|name| !name.is_empty()) - .unwrap_or(&entry.store_id) - .to_owned() + .filter(|text| !text.is_empty()) + .unwrap_or(entry.store_id.as_str()); + without_release_tags(title).unwrap_or_else(|| title.to_owned()) +} + +/// Drops trailing `(...)`/`[...]` groups, which dump names use for region, revision, language +/// and disc metadata (`Pikmin (USA) (Rev 1)`). The original text is kept when nothing would +/// remain, so a title that is only a group is never emptied. +fn without_release_tags(text: &str) -> Option { + let mut end = text.len(); + loop { + let trimmed = text[..end].trim_end(); + let Some(close) = trimmed.chars().last() else { + break; + }; + let open = match close { + ')' => '(', + ']' => '[', + _ => break, + }; + let Some(position) = trimmed.rfind(open) else { + break; + }; + if position == 0 || !trimmed[..position].ends_with(char::is_whitespace) { + break; + } + let candidate = trimmed[..position].trim_end(); + if candidate.is_empty() { + break; + } + end = candidate.len(); + } + (end != text.len()).then(|| text[..end].trim_end().to_owned()) } pub(super) fn detected_years(entry: &StoredEntry) -> Vec { diff --git a/crates/core/src/library/suggest/tests.rs b/crates/core/src/library/suggest/tests.rs index dcb2d5cd0..e93132997 100644 --- a/crates/core/src/library/suggest/tests.rs +++ b/crates/core/src/library/suggest/tests.rs @@ -33,6 +33,31 @@ fn normalization_strips_separators_and_punctuation_and_collapses_spaces() { assert_eq!(normalize_title("***"), ""); } +#[test] +fn the_search_query_prefers_a_record_title_and_drops_release_tags() { + let mut entry = stored("dolphin-emu", "GPIE01", "Pikmin (USA) (Rev 1)", true); + assert_eq!(search_query(&entry), "Pikmin"); + + entry.fields.insert("title".to_owned(), "Pikmin".to_owned()); + assert_eq!(search_query(&entry), "Pikmin"); + + let plain = stored("steam", "570", "Dota 2", true); + assert_eq!(search_query(&plain), "Dota 2"); + + let tagged = stored("steam", "1", "Sonic Adventure [b]", true); + assert_eq!(search_query(&tagged), "Sonic Adventure"); + + // A name that is only a release tag is kept rather than emptied. + let mut only_tag = stored("steam", "2", "(USA)", true); + assert_eq!(search_query(&only_tag), "(USA)"); + + // A record title wins over a file name that carries tags. + only_tag + .fields + .insert("title".to_owned(), "Pikmin".to_owned()); + assert_eq!(search_query(&only_tag), "Pikmin"); +} + #[test] fn exact_underscore_separated_and_partial_titles_score_as_designed() { assert!(close(title_score("Hollow Knight", "Hollow Knight"), 1.0)); @@ -455,6 +480,7 @@ fn a_no_game_entry_gets_no_suggestions() { entry_key: "steam:123".to_owned(), game_id: None, chosen_at: 1, + source: crate::library::ChoiceSource::User, }], ..LibraryCache::default() }; diff --git a/crates/core/src/library/target.rs b/crates/core/src/library/target.rs new file mode 100644 index 000000000..51382fd94 --- /dev/null +++ b/crates/core/src/library/target.rs @@ -0,0 +1,472 @@ +//! Detected launch targets of library entries (task 7.7, design section 11). +//! +//! A provider may report a typed URI or a local executable for one of its own games. Reporting a +//! target only registers a candidate: it never starts anything. An executable target needs the +//! user's approval, and a changed target loses that approval, so an unreviewed scan can never run +//! code. The approval is bound to [`DetectedTarget::revision`]; a revalidation before every spawn +//! catches a replaced file or a folder that moved, and the entry then offers repair. +//! +//! Paths stay relative to the reported install folder, and the platform adapter canonicalizes +//! them and checks the file identity. Nothing here performs I/O. + +use serde::{Deserialize, Serialize}; + +use crate::ports::is_safe_relative_path; + +/// Longest accepted URI, in bytes. +pub const MAX_URI_BYTES: usize = 2048; +/// Longest accepted relative executable path, in bytes. +pub const MAX_PATH_BYTES: usize = 1024; +/// Most arguments one target may carry. +pub const MAX_ARGUMENTS: usize = 64; +/// Longest accepted argument, in bytes. +pub const MAX_ARGUMENT_BYTES: usize = 4096; +/// Schemes a detected URI may never use: they open local content or script instead of a game. +const DENIED_SCHEMES: &[&str] = &[ + "about", + "blob", + "data", + "file", + "javascript", + "ms-msdt", + "search-ms", + "shell", + "vbscript", +]; + +/// What a provider reported for one game. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", rename_all_fields = "camelCase")] +pub enum TargetSpec { + /// A URI the provider's own client handles. + Uri { uri: String }, + /// An executable inside the game's install folder. + Executable { + /// The install folder the provider reported. + root: String, + /// Executable path relative to `root`. + path: String, + /// Literal arguments, in launch order. + #[serde(default)] + arguments: Vec, + /// Working directory relative to `root`; empty means `root` itself. + #[serde(default)] + working_directory: String, + }, +} + +impl TargetSpec { + /// Bounds and shape a provider's target. The host calls this before storing a candidate; a + /// rejected target leaves the game's other facts intact. + pub fn validate_shape(&self) -> bool { + match self { + Self::Uri { uri } => valid_uri(uri), + Self::Executable { + root, + path, + arguments, + working_directory, + } => { + valid_root(root) + && path.len() <= MAX_PATH_BYTES + && is_safe_relative_path(path) + && (working_directory.is_empty() + || (working_directory.len() <= MAX_PATH_BYTES + && is_safe_relative_path(working_directory))) + && arguments.len() <= MAX_ARGUMENTS + && arguments.iter().all(|argument| { + argument.len() <= MAX_ARGUMENT_BYTES + && !argument.chars().any(char::is_control) + }) + } + } + } + + /// The URI, when this is a URI target. + pub fn uri(&self) -> Option<&str> { + match self { + Self::Uri { uri } => Some(uri), + Self::Executable { .. } => None, + } + } + + /// A stable list of the fields that make this target what it is. A changed list is a new + /// target revision and loses the user's approval. + pub fn fingerprint_parts(&self) -> Vec { + match self { + Self::Uri { uri } => vec!["uri".into(), uri.clone()], + Self::Executable { + root, + path, + arguments, + working_directory, + } => { + let mut parts = vec![ + "executable".into(), + root.clone(), + path.clone(), + working_directory.clone(), + ]; + parts.extend(arguments.iter().cloned()); + parts + } + } + } +} + +/// A stored target and the user's decision about it. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct DetectedTarget { + pub spec: TargetSpec, + /// Last target the provider reported. A user repair may change `spec` while scans keep + /// reporting this original value; a later provider change still creates a new revision. + #[serde(default)] + pub reported_spec: Option, + /// `spec` was explicitly chosen by the user as a repair for the same provider candidate. + #[serde(default)] + pub user_override: bool, + /// Grows when the provider reports a different target; approval is bound to it. + pub revision: u64, + /// Whether the user approved this revision. + pub approved: bool, + /// Whether the target was still reported and its executable still validated. + pub available: bool, + /// File identity the platform recorded at approval; `None` for URI targets. + #[serde(default)] + pub identity: Option, + /// Unix seconds of the scan that reported it. + pub reported_at: i64, +} + +impl DetectedTarget { + /// The target after a scan reported `spec`. The same target keeps its revision and approval; + /// a different one starts a new revision without approval, so changed paths ask again. + pub fn reported(existing: Option<&Self>, spec: TargetSpec, now: i64) -> Self { + if let Some(existing) = existing + && existing.user_override + && existing.reported_spec.as_ref() == Some(&spec) + { + return Self { + available: true, + reported_at: now, + ..existing.clone() + }; + } + match existing { + Some(existing) if existing.spec == spec => Self { + available: true, + reported_at: now, + reported_spec: Some(spec), + ..existing.clone() + }, + _ => Self { + revision: existing.map_or(1, |existing| existing.revision.saturating_add(1)), + spec: spec.clone(), + reported_spec: Some(spec), + user_override: false, + approved: false, + available: true, + identity: None, + reported_at: now, + }, + } + } + + /// The same target, marked unavailable: a completed scan no longer reported it. + pub fn missing(existing: &Self, now: i64) -> Self { + Self { + available: false, + reported_at: now, + ..existing.clone() + } + } + + /// User-selected replacement executable for a previously reported target. + pub fn repaired(&self, spec: TargetSpec, identity: String, now: i64) -> Self { + let changed = self.spec != spec; + Self { + revision: if changed { + self.revision.saturating_add(1) + } else { + self.revision + }, + spec, + user_override: changed || self.user_override, + approved: true, + available: true, + identity: Some(identity), + reported_at: now, + ..self.clone() + } + } + + /// A stable number for what a launch would start now. A remembered confirmation and a + /// pre-issued intent are bound to it. + /// + /// This is a fingerprint, not a security boundary: approval and revision are checked + /// separately before anything starts. It is computed without a crypto dependency so this + /// crate stays free of I/O and platform crates. + pub fn fingerprint(&self) -> u64 { + let mut hash: u64 = 0xcbf2_9ce4_8422_2325; + let mut part = |bytes: &[u8]| { + for byte in (bytes.len() as u64).to_be_bytes().iter().chain(bytes) { + hash ^= u64::from(*byte); + hash = hash.wrapping_mul(0x0000_0100_0000_01b3); + } + }; + part(b"detected"); + part(&self.revision.to_be_bytes()); + part(if self.approved { + b"approved" + } else { + b"unapproved" + }); + part(if self.available { + b"available" + } else { + b"unavailable" + }); + part(self.identity.as_deref().unwrap_or_default().as_bytes()); + for value in self.spec.fingerprint_parts() { + part(value.as_bytes()); + } + hash + } + + /// Whether Play may run this target now. + pub fn ready(&self) -> bool { + self.approved && self.available + } +} + +/// Non-secret target state exposed in the selected library entry's detail view. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct DetectedTargetView { + pub spec: TargetSpec, + pub revision: u64, + pub approved: bool, + pub available: bool, +} + +impl From<&DetectedTarget> for DetectedTargetView { + fn from(target: &DetectedTarget) -> Self { + Self { + spec: target.spec.clone(), + revision: target.revision, + approved: target.approved, + available: target.available, + } + } +} + +fn valid_root(root: &str) -> bool { + !root.trim().is_empty() + && root.len() <= MAX_PATH_BYTES + && !root.chars().any(char::is_control) + && (root.starts_with('/') + || root.starts_with('\\') + || crate::provider::path::is_windows_style(root)) +} + +fn valid_uri(uri: &str) -> bool { + if uri.is_empty() + || uri.len() > MAX_URI_BYTES + || uri.trim() != uri + || uri.chars().any(char::is_control) + || uri.chars().any(char::is_whitespace) + { + return false; + } + let Some((scheme, rest)) = uri.split_once(':') else { + return false; + }; + if rest.is_empty() { + return false; + } + let mut chars = scheme.chars(); + if !chars.next().is_some_and(|c| c.is_ascii_alphabetic()) + || !chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.')) + { + return false; + } + !DENIED_SCHEMES + .iter() + .any(|denied| scheme.eq_ignore_ascii_case(denied)) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn executable() -> TargetSpec { + TargetSpec::Executable { + root: r"C:\Games\Celeste".into(), + path: "Celeste.exe".into(), + arguments: vec!["--fast".into()], + working_directory: String::new(), + } + } + + #[test] + fn a_new_target_starts_unapproved_and_a_same_one_keeps_its_approval() { + let first = DetectedTarget::reported(None, executable(), 10); + assert_eq!((first.revision, first.approved), (1, false)); + let approved = DetectedTarget { + approved: true, + identity: Some("vol:file".into()), + ..first.clone() + }; + let again = DetectedTarget::reported(Some(&approved), executable(), 20); + assert_eq!((again.revision, again.approved), (1, true)); + assert_eq!(again.identity.as_deref(), Some("vol:file")); + assert_eq!(again.reported_at, 20); + } + + #[test] + fn a_changed_target_gets_a_new_revision_and_loses_approval() { + let approved = DetectedTarget { + approved: true, + identity: Some("vol:file".into()), + ..DetectedTarget::reported(None, executable(), 10) + }; + let changed = TargetSpec::Executable { + root: r"C:\Games\Celeste".into(), + path: "Celeste.exe".into(), + arguments: vec!["--safe".into()], + working_directory: String::new(), + }; + let next = DetectedTarget::reported(Some(&approved), changed, 20); + assert_eq!((next.revision, next.approved), (2, false)); + assert_eq!(next.identity, None); + } + + #[test] + fn an_unreported_target_stays_stored_but_unavailable() { + let target = DetectedTarget { + approved: true, + ..DetectedTarget::reported(None, executable(), 10) + }; + let missing = DetectedTarget::missing(&target, 30); + assert!(!missing.available); + assert!(missing.approved); + assert_eq!(missing.revision, target.revision); + assert!(!missing.ready()); + } + + #[test] + fn a_user_repair_survives_the_same_scan_but_a_provider_change_revokes_it() { + let reported = DetectedTarget::reported(None, executable(), 10); + let replacement = TargetSpec::Executable { + root: r"C:\Games\Celeste".into(), + path: "bin/Celeste.exe".into(), + arguments: vec!["--fast".into()], + working_directory: String::new(), + }; + let repaired = reported.repaired(replacement, "vol:new-file".into(), 20); + assert!(repaired.ready()); + assert!(repaired.user_override); + let repeated = DetectedTarget::reported(Some(&repaired), executable(), 30); + assert_eq!(repeated.spec, repaired.spec); + assert_eq!(repeated.revision, repaired.revision); + assert!(repeated.ready()); + + let changed = TargetSpec::Executable { + root: r"C:\Games\Celeste".into(), + path: "Celeste64.exe".into(), + arguments: vec![], + working_directory: String::new(), + }; + let next = DetectedTarget::reported(Some(&repeated), changed, 40); + assert_eq!(next.revision, repeated.revision + 1); + assert!(!next.approved); + assert!(!next.user_override); + assert_eq!(next.identity, None); + } + + #[test] + fn target_view_does_not_expose_the_approved_file_identity() { + let target = DetectedTarget { + approved: true, + identity: Some("volume:secret-file-id".into()), + ..DetectedTarget::reported(None, executable(), 10) + }; + let view = DetectedTargetView::from(&target); + let json = serde_json::to_string(&view).unwrap(); + assert!(!json.contains("secret-file-id")); + assert!(json.contains("revision")); + } + + #[test] + fn only_relative_paths_inside_the_reported_root_are_accepted() { + for path in ["Celeste.exe", "bin/game.exe", r"bin\game.exe"] { + let spec = TargetSpec::Executable { + root: r"C:\Games\Celeste".into(), + path: path.into(), + arguments: vec![], + working_directory: String::new(), + }; + assert!(spec.validate_shape(), "{path}"); + } + for path in [ + "", + "..\\escape.exe", + "/abs/game.exe", + r"C:\abs.exe", + "bin/../../x.exe", + ] { + let spec = TargetSpec::Executable { + root: r"C:\Games\Celeste".into(), + path: path.into(), + arguments: vec![], + working_directory: String::new(), + }; + assert!(!spec.validate_shape(), "{path}"); + } + let relative_root = TargetSpec::Executable { + root: "Games/Celeste".into(), + path: "Celeste.exe".into(), + arguments: vec![], + working_directory: String::new(), + }; + assert!(!relative_root.validate_shape()); + } + + #[test] + fn uris_keep_their_scheme_and_never_open_local_content() { + for uri in [ + "steam://rungameid/620", + "https://example.com/play?id=1", + "uplay://launch/1/0", + ] { + assert!( + TargetSpec::Uri { uri: uri.into() }.validate_shape(), + "{uri}" + ); + } + for uri in [ + "", + "steam:", + " file:///C:/game.exe", + "javascript:alert(1)", + "data:text/html,x", + "no scheme", + "steam://run game", + ] { + assert!( + !TargetSpec::Uri { uri: uri.into() }.validate_shape(), + "{uri}" + ); + } + } + + #[test] + fn arguments_are_bounded_and_never_shell_fragments() { + let mut spec = executable(); + if let TargetSpec::Executable { arguments, .. } = &mut spec { + arguments.push("bad\narg".into()); + } + assert!(!spec.validate_shape()); + } +} diff --git a/crates/core/src/library/view.rs b/crates/core/src/library/view.rs index 9c4e2d627..a6fa5e23c 100644 --- a/crates/core/src/library/view.rs +++ b/crates/core/src/library/view.rs @@ -47,6 +47,9 @@ pub struct DetailView { /// The compact achievement summary, present when a cache row exists. #[serde(default)] pub achievements: Option, + /// Host-validated candidate reported for this installed entry, if any. + #[serde(default)] + pub detected_target: Option, /// Scored suggestions for an unmatched or ambiguous entry, best first, at most two. #[serde(default)] pub suggestions: Vec, @@ -353,6 +356,9 @@ impl LibraryMachine { membership: game_id.map_or(Membership::NotChecked, |id| self.cached_membership(id)), achievement_backend: false, achievements: None, + detected_target: entry + .and_then(|entry| entry.target.as_ref()) + .map(super::target::DetectedTargetView::from), suggestions: self.detail_suggestions(row), } } diff --git a/crates/core/src/ports/matching.rs b/crates/core/src/ports/matching.rs index 8e254ef66..03c8616de 100644 --- a/crates/core/src/ports/matching.rs +++ b/crates/core/src/ports/matching.rs @@ -219,6 +219,7 @@ mod tests { entry_key: "manual:install-1".into(), game_id, chosen_at: 10, + source: Default::default(), } } diff --git a/crates/core/src/ports/mod.rs b/crates/core/src/ports/mod.rs index f68734f72..51ffd7267 100644 --- a/crates/core/src/ports/mod.rs +++ b/crates/core/src/ports/mod.rs @@ -149,6 +149,9 @@ pub enum UriError { NoHandler, #[error("the link could not be opened")] Failed, + /// The operating-system URI handler cannot apply the requested execution customization. + #[error("URI handlers cannot apply this launch customization")] + Unsupported, } /// Hands one provider-declared URI (`steam://rungameid/620`) to the OS handler for its scheme. @@ -158,6 +161,22 @@ pub enum UriError { /// may block until the OS has accepted the URI; run them on a blocking worker. pub trait UriOpener: Send + Sync { fn open(&self, uri: &Url) -> Result<(), UriError>; + + /// Opens a custom URI only when the handler can honor every supplied execution field. + /// Existing handlers support only the URI itself; they must not silently ignore argv, cwd or + /// environment changes. + fn open_custom( + &self, + uri: &Url, + arguments: &[String], + working_directory: &str, + environment: &crate::drm_free::LaunchEnvironmentDelta, + ) -> Result<(), UriError> { + if !arguments.is_empty() || !working_directory.is_empty() || !environment.is_empty() { + return Err(UriError::Unsupported); + } + self.open(uri) + } } /// Read-only file access for provider scanners. diff --git a/crates/core/src/ports/view.rs b/crates/core/src/ports/view.rs index a7b708ed4..31747379c 100644 --- a/crates/core/src/ports/view.rs +++ b/crates/core/src/ports/view.rs @@ -349,6 +349,8 @@ pub struct PortPreferencesView { #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct PortsView { + #[serde(default)] + pub plugin_request: Option>, pub catalog: PortCatalogStatus, pub entries: Vec, /// Provenance by registration key. @@ -360,6 +362,23 @@ pub struct PortsView { pub preferences: PortPreferencesView, } +/// One host-owned guided-setup request. Paths stay in Core's trusted UI. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PortPluginRequest { + pub id: String, + pub catalog_id: String, + pub plugin_id: String, + pub publisher_fingerprint: String, + pub sources: Vec, +} +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PortPluginSource { + pub path: String, + pub directory: bool, +} + impl PortsView { /// The empty view the snapshot carries before the host delivers a payload. pub fn empty() -> Self { diff --git a/crates/core/src/provider/registry.rs b/crates/core/src/provider/registry.rs index 7387ab3a1..55c77f1b9 100644 --- a/crates/core/src/provider/registry.rs +++ b/crates/core/src/provider/registry.rs @@ -368,10 +368,16 @@ fn validate( if !active { return Ok(&inactive_backend); } - plugins + let mut registered = plugins .iter() - .find(|p| p.plugin_id == id && p.provider_id == manifest.id) - .ok_or_else(|| "provider plugin is not registered for this provider".into()) + .filter(|p| p.plugin_id == id && p.provider_id == manifest.id); + let backend = registered + .next() + .ok_or_else(|| "provider plugin is not registered for this provider".to_owned())?; + if registered.next().is_some() { + return Err("provider plugin registration is ambiguous".into()); + } + Ok(backend) }; let scanner: ScanFn = match &manifest.scan.plugin { Some(id) => { diff --git a/crates/core/src/provider/registry/tests.rs b/crates/core/src/provider/registry/tests.rs index 101bed58f..8d961f0c2 100644 --- a/crates/core/src/provider/registry/tests.rs +++ b/crates/core/src/provider/registry/tests.rs @@ -108,6 +108,38 @@ launch = { uri = "example://run/{id}" } ); } +#[test] +fn rejects_colliding_backend_registrations_instead_of_using_registration_order() { + let text = r#" +id = "example" +name = "Example store" +platforms = ["windows", "linux"] +source = "example" +scan = { plugin = "org.example.provider" } +"#; + let approved = PluginBackend { + plugin_id: "org.example.provider".into(), + provider_id: "example".into(), + discovery: true, + catalog: false, + counter: false, + actions: false, + achievements: false, + }; + let conflicting = PluginBackend { + discovery: false, + ..approved.clone() + }; + let loaded = load_with_plugins( + &[("example.toml", text)], + Platform::Windows, + &[approved, conflicting], + ); + assert!(loaded.providers.is_empty()); + assert_eq!(loaded.diagnostics.len(), 1); + assert!(loaded.diagnostics[0].problem.contains("ambiguous")); +} + #[test] fn loads_the_bundled_steam_manifest() { let loaded = load(&[("steam.toml", STEAM_MANIFEST)], Platform::Windows); diff --git a/crates/core/src/tools/mod.rs b/crates/core/src/tools/mod.rs index 8e6342ef8..4bd556152 100644 --- a/crates/core/src/tools/mod.rs +++ b/crates/core/src/tools/mod.rs @@ -298,6 +298,36 @@ pub trait ToolInstallerHost: Send + Sync { install_dir: &str, ) -> Result<(), ToolError>; + /// Checks authority after preparation and at transactional deployment checkpoints. + /// Adapters without this capability must refuse plugin-triggered effects. + #[allow(clippy::too_many_arguments)] // Existing installer inputs plus the authority fence. + fn install_or_update_checked( + &self, + _store: &dyn ToolStore, + _catalog: &dyn ToolCatalogApi, + _descriptor: &ToolDescriptor, + _release: &ToolRelease, + _request: &InstallRequest, + _install_dir: &str, + _check: &dyn Fn() -> Result<(), ToolError>, + ) -> Result { + Err(ToolError::Failed( + "guarded tool installation unavailable".into(), + )) + } + + /// Removal completes its existing recovery operation once its mutation phase starts. + fn uninstall_checked( + &self, + _store: &dyn ToolStore, + _entry_key: &str, + _tool_id: &str, + _install_dir: &str, + _check: &dyn Fn() -> Result<(), ToolError>, + ) -> Result<(), ToolError> { + Err(ToolError::Failed("guarded tool removal unavailable".into())) + } + fn recover_incomplete( &self, store: &dyn ToolStore, @@ -377,6 +407,8 @@ pub struct GameToolView { #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ToolModalView { + #[serde(default)] + pub plugin_request: Option, pub entry_key: String, pub title: String, pub install_dir: String, @@ -391,6 +423,15 @@ pub struct ToolModalView { pub operation: Option, } +/// Attribution and the only operation a pending plugin request may perform. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ToolPluginRequest { + pub plugin_id: String, + pub publisher_fingerprint: String, + pub remove: bool, +} + /// Machine-readable error code for localized error display in the game tools modal. #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] @@ -862,6 +903,31 @@ impl ToolInstallerHost for MockToolInstallerHost { Ok(()) } + fn install_or_update_checked( + &self, + store: &dyn ToolStore, + catalog: &dyn ToolCatalogApi, + descriptor: &ToolDescriptor, + release: &ToolRelease, + request: &InstallRequest, + install_dir: &str, + check: &dyn Fn() -> Result<(), ToolError>, + ) -> Result { + check()?; + self.install_or_update(store, catalog, descriptor, release, request, install_dir) + } + fn uninstall_checked( + &self, + store: &dyn ToolStore, + entry_key: &str, + tool_id: &str, + install_dir: &str, + check: &dyn Fn() -> Result<(), ToolError>, + ) -> Result<(), ToolError> { + check()?; + self.uninstall(store, entry_key, tool_id, install_dir) + } + fn recover_incomplete( &self, store: &dyn ToolStore, diff --git a/crates/core/src/tracker/mod.rs b/crates/core/src/tracker/mod.rs index e31a52c37..e8c30514e 100644 --- a/crates/core/src/tracker/mod.rs +++ b/crates/core/src/tracker/mod.rs @@ -1,4 +1,5 @@ //! Pure game process tracking. The engine supplies times and session ids and executes effects. +pub mod runtime_sessions; pub mod scripted; use crate::playtime::Session; @@ -79,6 +80,7 @@ struct Running { /// Matching rules are supplied by the host, allowing both platforms to be tested anywhere. pub struct Tracker { policies: BTreeMap, + process_attributions: BTreeMap, floor: i64, windows: bool, account: Option, @@ -91,12 +93,16 @@ impl Tracker { windows, account: None, policies: BTreeMap::new(), + process_attributions: BTreeMap::new(), floor: i64::MIN, entries: BTreeMap::new(), active: BTreeMap::new(), } } pub fn set_policies(&mut self, policies: BTreeMap) { + if self.policies != policies { + self.process_attributions.clear(); + } self.policies = policies; } pub fn set_floor(&mut self, at: i64) { @@ -130,6 +136,7 @@ impl Tracker { self.floor = at; } self.stop(at, &mut effects, &mut next_id); + self.process_attributions.clear(); } self.account = account; let entries: BTreeMap<_, _> = @@ -154,16 +161,33 @@ impl Tracker { for key in removed { self.close(&key, at, &mut effects, &mut next_id); } + self.process_attributions.retain(|_, key| { + entries + .get(key) + .zip(self.entries.get(key)) + .is_some_and(|(new, old)| { + new.install_dir == old.install_dir + && new.source == old.source + && new.game_id == old.game_id + && new.counter == old.counter + }) + }); self.entries = entries; } Input::Listed { at, processes } if self.account.is_some() => { + let process_index: BTreeMap<_, _> = processes + .iter() + .map(|process| ((process.pid, process.created_at), process)) + .collect(); let mut grouped: BTreeMap> = BTreeMap::new(); - for process in processes { - if let Some(entry) = match_policy( + for process in processes.iter().cloned() { + if let Some(entry) = match_process_policy( &self.entries, &self.policies, - &process.exe_path, + &process, + &process_index, + &self.process_attributions, self.windows, ) { grouped @@ -172,6 +196,12 @@ impl Tracker { .insert((process.pid, process.created_at), process); } } + self.process_attributions = grouped + .iter() + .flat_map(|(key, processes)| { + processes.keys().map(|identity| (*identity, key.clone())) + }) + .collect(); let old_keys: Vec<_> = self.active.keys().cloned().collect(); for key in old_keys { let current = grouped.get(&key); @@ -434,5 +464,41 @@ fn match_policy<'a>( .map(|(_, _, e)| e) } +/// A launched wrapper can hand execution to a child outside the game's installation folder. +/// Keep that child with the entry matched by its parent chain, using PID plus creation time so a +/// reused PID cannot inherit an old game's attribution. +fn match_process_policy<'a>( + entries: &'a BTreeMap, + policies: &BTreeMap, + process: &ProcessInfo, + process_index: &BTreeMap<(u32, std::time::SystemTime), &ProcessInfo>, + previous_attributions: &BTreeMap, + windows: bool, +) -> Option<&'a Entry> { + let mut current = Some(process); + let mut visited = BTreeSet::new(); + while let Some(process) = current { + if !visited.insert((process.pid, process.created_at)) { + return None; + } + if let Some(entry) = match_policy(entries, policies, &process.exe_path, windows) { + return Some(entry); + } + let parent = process.parent.as_ref()?; + let identity = (parent.pid, parent.created_at); + if let Some(parent_process) = process_index.get(&identity) { + current = Some(*parent_process); + } else if let Some(entry) = previous_attributions + .get(&identity) + .and_then(|key| entries.get(key)) + { + return Some(entry); + } else { + current = None; + } + } + None +} + #[cfg(test)] mod tests; diff --git a/crates/core/src/tracker/runtime_sessions.rs b/crates/core/src/tracker/runtime_sessions.rs new file mode 100644 index 000000000..5f56895ca --- /dev/null +++ b/crates/core/src/tracker/runtime_sessions.rs @@ -0,0 +1,644 @@ +//! Core arbitration for plugin-reported runtime gameplay observations. +//! +//! Runtime adapters report content identity and lifecycle; they never provide process identity +//! or a measured duration. This state machine emits the same durable session effects consumed by +//! the process tracker, bounded by the last fresh observation. + +use crate::playtime::Session; +use std::{ + collections::{BTreeMap, VecDeque}, + time::Instant, +}; + +/// Reports older than this are not allowed to extend a measured interval. +pub const FRESHNESS_SECONDS: i64 = 30; +const FUTURE_SKEW_SECONDS: i64 = 5; +const MAX_ID_BYTES: usize = 256; +const MAX_INSTANCES: usize = 256; +const MAX_DEDUPLICATION_IDS: usize = 8192; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Outcome { + Accepted { host_session_id: Option }, + Duplicate, + Invalid(&'static str), + Stale, + Conflict(&'static str), + Unavailable(&'static str), +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Transition { + Identified, + Started, + Paused, + Resumed, + ContentChanged, + Ended, + IdentificationLost, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Report { + pub correlation_id: String, + pub game_id: u64, + pub installation_id: String, + pub content_id: String, + pub runtime_id: String, + pub runtime_instance_id: String, + pub reporter_session_id: String, + pub sequence: u64, + pub observed_at: i64, + pub transition: Transition, + pub source_observation_id: String, + /// Set only by the host after validating an explicitly approved context transition. + pub context_authorized: bool, + /// Host monotonic receipt time. Plugin wall clocks never control expiry. + pub received_at: Instant, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Effect { + Open(Session), + Checkpoint { + id: String, + at: i64, + }, + Close { + id: String, + ended_at: i64, + game_id: Option, + }, +} + +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] +struct InstanceKey { + plugin_id: String, + reporter_session_id: String, + runtime_instance_id: String, +} + +#[derive(Clone, Debug)] +struct Active { + game_id: u64, + installation_id: String, + content_id: String, + runtime_id: String, + sequence: u64, + observed_at: i64, + received_at: Instant, + session: Option, + terminal: bool, +} + +/// Pure state machine. The host supplies authenticated plugin identity, account/source context, +/// current time and session ids; all persistence remains with the engine. +#[derive(Default)] +pub struct RuntimeSessions { + instances: BTreeMap, + observations: BTreeMap, + observation_order: VecDeque, +} + +impl RuntimeSessions { + pub fn report( + &mut self, + plugin_id: &str, + account_id: &str, + source: &str, + report: Report, + now: i64, + mut next_id: impl FnMut() -> String, + ) -> (Outcome, Vec) { + if !valid_id(plugin_id) + || !valid_id(account_id) + || !valid_id(source) + || !valid_id(&report.correlation_id) + || report.game_id == 0 + || !valid_id(&report.installation_id) + || !valid_id(&report.content_id) + || !valid_id(&report.runtime_id) + || !valid_id(&report.runtime_instance_id) + || !valid_id(&report.reporter_session_id) + || !valid_id(&report.source_observation_id) + || report.sequence == 0 + { + return (Outcome::Invalid("missing or malformed identity"), vec![]); + } + if report.observed_at < now.saturating_sub(FRESHNESS_SECONDS) + || report.observed_at > now.saturating_add(FUTURE_SKEW_SECONDS) + { + return (Outcome::Stale, vec![]); + } + let transition = report.transition; + let game_id = report.game_id; + + if let Some(previous) = self.observations.get(&report.source_observation_id) { + return if previous.game_id == report.game_id + && previous.installation_id == report.installation_id + && previous.content_id == report.content_id + && previous.runtime_id == report.runtime_id + && previous.observed_at == report.observed_at + && previous.transition == report.transition + { + (Outcome::Duplicate, vec![]) + } else { + (Outcome::Conflict("observation id was reused"), vec![]) + }; + } + let key = InstanceKey { + plugin_id: plugin_id.to_owned(), + reporter_session_id: report.reporter_session_id.clone(), + runtime_instance_id: report.runtime_instance_id.clone(), + }; + if !self.instances.contains_key(&key) && self.instances.len() >= MAX_INSTANCES { + return ( + Outcome::Unavailable("runtime instance capacity reached"), + vec![], + ); + } + let context_changed = self.instances.get(&key).is_some_and(|active| { + report.game_id != active.game_id + || report.installation_id != active.installation_id + || report.runtime_id != active.runtime_id + }); + if self.instances.get(&key).is_some_and(|active| { + active.terminal + || report.sequence <= active.sequence + || report.observed_at < active.observed_at + || (context_changed + && (!report.context_authorized + || report.transition != Transition::ContentChanged + || report.runtime_id != active.runtime_id)) + }) { + return ( + Outcome::Conflict("sequence or runtime identity changed"), + vec![], + ); + } + + let mut effects = Vec::new(); + let mut opened = None; + let at = report.observed_at.min(now); + let existing = self.instances.remove(&key); + let mut current = existing.unwrap_or_else(|| Active { + game_id, + installation_id: report.installation_id.clone(), + content_id: report.content_id.clone(), + runtime_id: report.runtime_id.clone(), + sequence: 0, + observed_at: at, + received_at: report.received_at, + session: None, + terminal: false, + }); + let identity_changed = current.game_id != report.game_id + || current.installation_id != report.installation_id + || current.runtime_id != report.runtime_id; + let content_changed = current.content_id != report.content_id || identity_changed; + let was_active = current.session.is_some(); + if content_changed { + // A gap between the last accepted observation for A and the approved observation + // for B is unknown; never attribute it to either game. + let close_at = if identity_changed { + current.observed_at + } else { + at + }; + close(&mut current, close_at, &mut effects); + current.game_id = game_id; + current.installation_id.clone_from(&report.installation_id); + current.runtime_id.clone_from(&report.runtime_id); + current.content_id.clone_from(&report.content_id); + } + + match transition { + Transition::Identified => {} + Transition::Started | Transition::Resumed => { + if current.session.is_none() { + let session = Session { + id: next_id(), + account_id: account_id.to_owned(), + entry_key: report.installation_id.clone(), + game_id: Some(game_id), + source: source.to_owned(), + platform_id: 6, + started_at: at, + checkpoint_at: at, + ended_at: None, + }; + opened = Some(session.id.clone()); + effects.push(Effect::Open(session.clone())); + current.session = Some(session); + } + } + Transition::Paused | Transition::Ended | Transition::IdentificationLost => { + close(&mut current, at, &mut effects) + } + Transition::ContentChanged => { + if was_active && !content_changed { + return ( + Outcome::Conflict("content change omitted a new content identity"), + vec![], + ); + } + if was_active { + let session = Session { + id: next_id(), + account_id: account_id.to_owned(), + entry_key: report.installation_id.clone(), + game_id: Some(game_id), + source: source.to_owned(), + platform_id: 6, + started_at: at, + checkpoint_at: at, + ended_at: None, + }; + opened = Some(session.id.clone()); + effects.push(Effect::Open(session.clone())); + current.session = Some(session); + } + } + } + + current.sequence = report.sequence; + current.observed_at = at; + current.received_at = report.received_at; + current.terminal = transition == Transition::Ended; + let observation_id = report.source_observation_id.clone(); + self.observations.insert(observation_id.clone(), report); + self.observation_order.push_back(observation_id); + while self.observation_order.len() > MAX_DEDUPLICATION_IDS { + if let Some(expired) = self.observation_order.pop_front() { + self.observations.remove(&expired); + } + } + self.instances.insert(key, current); + ( + Outcome::Accepted { + host_session_id: opened, + }, + effects, + ) + } + + /// Closes at the last supported observation, never at the later time of discovery. + pub fn expire(&mut self, now: Instant) -> Vec { + let expired: Vec<_> = self + .instances + .iter() + .filter(|(_, active)| { + now.duration_since(active.received_at).as_secs() > FRESHNESS_SECONDS as u64 + }) + .map(|(key, _)| key.clone()) + .collect(); + let mut effects = Vec::new(); + for key in expired { + if let Some(active) = self.instances.get_mut(&key) { + close(active, active.observed_at, &mut effects); + } + } + effects + } + + /// Disconnect/revocation fences all intervals for a reporter at its last accepted evidence. + pub fn fence_plugin(&mut self, plugin_id: &str) -> Vec { + let keys: Vec<_> = self + .instances + .keys() + .filter(|key| key.plugin_id == plugin_id) + .cloned() + .collect(); + let mut effects = Vec::new(); + for key in keys { + if let Some(mut active) = self.instances.remove(&key) { + let last_observed_at = active.observed_at; + close(&mut active, last_observed_at, &mut effects); + } + } + effects + } + + pub fn fence_entry(&mut self, entry_key: &str) -> Vec { + let mut effects = Vec::new(); + for active in self.instances.values_mut() { + if active + .session + .as_ref() + .is_some_and(|session| session.entry_key == entry_key) + { + close(active, active.observed_at, &mut effects); + } + } + effects + } + + pub fn reset(&mut self) -> Vec { + let mut effects = Vec::new(); + for active in self.instances.values_mut() { + close(active, active.observed_at, &mut effects); + } + self.instances.clear(); + self.observations.clear(); + self.observation_order.clear(); + effects + } +} + +fn close(active: &mut Active, at: i64, effects: &mut Vec) { + if let Some(session) = active.session.take() { + let ended_at = at.max(session.started_at); + effects.push(Effect::Close { + id: session.id, + ended_at, + game_id: Some(active.game_id), + }); + } +} + +fn valid_id(value: &str) -> bool { + !value.is_empty() + && value.len() <= MAX_ID_BYTES + && !value + .chars() + .any(|character| character.is_control() || character == '\0') +} + +#[cfg(test)] +mod tests { + use super::*; + + fn report(sequence: u64, transition: Transition, at: i64, content_id: &str) -> Report { + Report { + correlation_id: format!("corr-{sequence}"), + game_id: 42, + installation_id: "install-a".into(), + content_id: content_id.into(), + runtime_id: "emulator-a".into(), + runtime_instance_id: "instance-a".into(), + reporter_session_id: "reporter-a".into(), + sequence, + observed_at: at, + transition, + source_observation_id: format!("observation-{sequence}"), + context_authorized: false, + received_at: Instant::now(), + } + } + + fn apply( + tracker: &mut RuntimeSessions, + value: Report, + next: &'static str, + now: i64, + ) -> (Outcome, Vec) { + tracker.report("plugin-a", "account-a", "runtime", value, now, || { + next.into() + }) + } + + #[test] + fn content_switch_closes_old_and_opens_new_at_observed_boundary() { + let mut tracker = RuntimeSessions::default(); + assert!(matches!( + apply( + &mut tracker, + report(1, Transition::Started, 100, "rom-a"), + "session-a", + 100 + ) + .0, + Outcome::Accepted { .. } + )); + let (_, effects) = apply( + &mut tracker, + report(2, Transition::ContentChanged, 120, "rom-b"), + "session-b", + 120, + ); + assert!(matches!(&effects[0], Effect::Close { ended_at: 120, .. })); + assert!( + matches!(&effects[1], Effect::Open(session) if session.started_at == 120 && session.entry_key == "install-a") + ); + } + + #[test] + fn same_instance_changes_game_only_after_host_authorizes_new_context() { + let mut tracker = RuntimeSessions::default(); + apply( + &mut tracker, + report(1, Transition::Started, 100, "rom-a"), + "session-a", + 100, + ); + + let mut denied = report(2, Transition::ContentChanged, 130, "rom-b"); + denied.game_id = 84; + denied.installation_id = "install-b".into(); + assert!(matches!( + apply(&mut tracker, denied, "unused", 130).0, + Outcome::Conflict(_) + )); + + let mut approved = report(2, Transition::ContentChanged, 130, "rom-b"); + approved.game_id = 84; + approved.installation_id = "install-b".into(); + approved.context_authorized = true; + let (_, effects) = apply(&mut tracker, approved, "session-b", 130); + assert!(matches!( + effects.as_slice(), + [ + Effect::Close { ended_at: 100, game_id: Some(42), .. }, + Effect::Open(Session { game_id: Some(84), entry_key, started_at: 130, .. }) + ] if entry_key == "install-b" + )); + } + + #[test] + fn concurrent_instances_are_independent_and_duplicate_evidence_is_rejected() { + let mut tracker = RuntimeSessions::default(); + let first = report(1, Transition::Started, 100, "rom-a"); + let (accepted, _) = apply(&mut tracker, first.clone(), "session-a", 100); + assert!(matches!(accepted, Outcome::Accepted { .. })); + + let mut duplicate = first; + duplicate.reporter_session_id = "reporter-b".into(); + assert_eq!( + apply(&mut tracker, duplicate, "unused", 100).0, + Outcome::Duplicate + ); + + let mut parallel = report(1, Transition::Started, 101, "rom-a"); + parallel.runtime_instance_id = "instance-b".into(); + parallel.reporter_session_id = "reporter-b".into(); + parallel.source_observation_id = "observation-parallel".into(); + assert!(matches!( + apply(&mut tracker, parallel, "session-b", 101).0, + Outcome::Accepted { .. } + )); + } + + #[test] + fn identification_alone_does_not_count_and_stale_or_expired_evidence_closes_at_last_time() { + let mut tracker = RuntimeSessions::default(); + let (_, effects) = apply( + &mut tracker, + report(1, Transition::Identified, 100, "rom-a"), + "unused", + 100, + ); + assert!(effects.is_empty()); + assert_eq!( + apply( + &mut tracker, + report(2, Transition::Started, 50, "rom-a"), + "unused", + 100 + ) + .0, + Outcome::Stale + ); + let (_, opened) = apply( + &mut tracker, + report(2, Transition::Started, 101, "rom-a"), + "session-a", + 101, + ); + assert!(matches!(opened.first(), Some(Effect::Open(_)))); + assert!(matches!( + tracker + .expire(Instant::now() + std::time::Duration::from_secs(31)) + .as_slice(), + [Effect::Close { ended_at: 101, .. }] + )); + } + + #[test] + fn confirmed_pause_closes_interval_and_resume_starts_a_new_one() { + let mut tracker = RuntimeSessions::default(); + apply( + &mut tracker, + report(1, Transition::Started, 100, "rom-a"), + "first", + 100, + ); + let (_, paused) = apply( + &mut tracker, + report(2, Transition::Paused, 120, "rom-a"), + "unused", + 120, + ); + assert!(matches!( + paused.as_slice(), + [Effect::Close { ended_at: 120, .. }] + )); + let (_, resumed) = apply( + &mut tracker, + report(3, Transition::Resumed, 180, "rom-a"), + "second", + 180, + ); + assert!(matches!(resumed.as_slice(), [Effect::Open(session)] if session.started_at == 180)); + } + + #[test] + fn identification_loss_closes_confirmed_playtime_and_identification_does_not_reopen_it() { + let mut tracker = RuntimeSessions::default(); + apply( + &mut tracker, + report(1, Transition::Started, 100, "rom-a"), + "session-a", + 100, + ); + + let (_, lost) = apply( + &mut tracker, + report(2, Transition::IdentificationLost, 120, "rom-a"), + "unused", + 120, + ); + assert!(matches!( + lost.as_slice(), + [Effect::Close { + ended_at: 120, + game_id: Some(42), + .. + }] + )); + + let (_, unidentified) = apply( + &mut tracker, + report(3, Transition::Identified, 180, "rom-a"), + "unused", + 180, + ); + assert!(unidentified.is_empty()); + } + + #[test] + fn new_arbiter_after_restart_never_backfills_and_disconnect_fences_last_observation() { + let mut old = RuntimeSessions::default(); + apply( + &mut old, + report(1, Transition::Started, 100, "rom-a"), + "session-a", + 100, + ); + assert!(matches!( + old.fence_plugin("plugin-a").as_slice(), + [Effect::Close { ended_at: 100, .. }] + )); + + let mut fresh = RuntimeSessions::default(); + let (_, effects) = apply( + &mut fresh, + report(1, Transition::Started, 500, "rom-a"), + "session-fresh", + 500, + ); + assert!(matches!(effects.as_slice(), [Effect::Open(session)] if session.started_at == 500)); + } + + #[test] + fn identification_without_gameplay_confirmation_and_reused_process_identity_do_not_merge() { + let mut tracker = RuntimeSessions::default(); + let mut identified = report(1, Transition::Identified, 1_000, "rom-a"); + identified.runtime_instance_id = "instance-before-boot".into(); + let (outcome, effects) = apply(&mut tracker, identified, "unused", 1_000); + assert!(matches!( + outcome, + Outcome::Accepted { + host_session_id: None + } + )); + assert!( + effects.is_empty(), + "launch/content identification alone is not playtime" + ); + + let mut failed_boot = report(2, Transition::Ended, 1_010, "rom-a"); + failed_boot.runtime_instance_id = "instance-before-boot".into(); + let (outcome, effects) = apply(&mut tracker, failed_boot, "unused", 1_010); + assert!(matches!( + outcome, + Outcome::Accepted { + host_session_id: None + } + )); + assert!( + effects.is_empty(), + "failed boot without gameplay confirmation adds no session" + ); + + let mut reused_pid = report(1, Transition::Started, 1_020, "rom-a"); + reused_pid.runtime_instance_id = "instance-after-pid-reuse".into(); + reused_pid.source_observation_id = "observation-after-reuse".into(); + let (outcome, effects) = apply(&mut tracker, reused_pid, "session-after-reuse", 1_020); + assert!(matches!(outcome, Outcome::Accepted { .. })); + let Effect::Open(first) = &effects[0] else { + panic!("confirmed gameplay opens a fresh session"); + }; + assert_eq!(first.started_at, 1_020); + assert_eq!(first.id, "session-after-reuse"); + } +} diff --git a/crates/core/src/tracker/tests.rs b/crates/core/src/tracker/tests.rs index f73f0c4f8..575a13059 100644 --- a/crates/core/src/tracker/tests.rs +++ b/crates/core/src/tracker/tests.rs @@ -174,6 +174,35 @@ fn counter_games_emit_running_and_one_read_without_sessions() { .is_empty() ); } + +#[test] +fn a_child_outside_the_installation_keeps_wrapper_game_attribution() { + let mut tracker = setup(false); + let wrapper = process(1, 100, "/games/one/wrapper"); + let mut child = process(2, 105, "/opt/runtime/game"); + child.parent = Some(crate::ports::ProcessIdentity { + pid: wrapper.pid, + created_at: wrapper.created_at, + }); + let opened = listed(&mut tracker, 110, vec![wrapper, child.clone()]); + assert!( + opened + .iter() + .any(|effect| matches!(effect, Effect::OpenSession(row) if row.entry_key == "steam:1")) + ); + + assert!(listed(&mut tracker, 120, vec![child]).is_empty()); + assert_eq!(tracker.running(), BTreeSet::from(["steam:1".into()])); + + let mut reused_pid_child = process(3, 130, "/opt/unrelated/game"); + reused_pid_child.parent = Some(crate::ports::ProcessIdentity { + pid: 1, + created_at: UNIX_EPOCH + Duration::from_secs(200), + }); + listed(&mut tracker, 140, vec![reused_pid_child]); + assert!(tracker.running().is_empty()); +} + #[test] fn a_game_already_running_at_the_first_read_keeps_its_process_start() { let mut tracker = setup(false); diff --git a/crates/core/tests/serialization.rs b/crates/core/tests/serialization.rs index 640940622..025ac56ba 100644 --- a/crates/core/tests/serialization.rs +++ b/crates/core/tests/serialization.rs @@ -4,9 +4,9 @@ use gamenode_core::Provider; use gamenode_core::auth::{AuthMachine, Input}; use gamenode_core::credential::StorageMethod; use gamenode_core::library::{ - CoverSize, DetailView, EntryStatus, Input as LibraryInput, LibraryFilters, MatchSource, - MatchStatus, Membership, Row, SelectMode, SidebarSelection, Sort, SortDirection, SortKey, - ViewMode, + CoverSize, DetailView, EntryStatus, Input as LibraryInput, LibraryFilters, MatchPlatformFilter, + MatchSource, MatchStatus, Membership, Row, SelectMode, SidebarSelection, Sort, SortDirection, + SortKey, ViewMode, }; use gamenode_core::library::{FilterCounts, RowGroup, ScopeCounts, TitleSource, TitleSourceKind}; use gamenode_core::library::{GroupBy, LibraryScope, RowGameNode}; @@ -108,6 +108,7 @@ fn test_detail_view_serialization_and_artwork_omission() { let detail = DetailView { running: false, row, + detected_target: None, install_dir: "C:\\Games\\Cyberpunk 2077".into(), release_year: Some(2020), has_artwork: true, @@ -226,6 +227,7 @@ fn test_library_input_serialization() { }), LibraryInput::OpenMatch, LibraryInput::CloseMatch, + LibraryInput::SetMatchPlatformFilter { enabled: false }, LibraryInput::ScanRequested, LibraryInput::RequestCatalog, LibraryInput::SetFilters(LibraryFilters::default()), @@ -430,6 +432,11 @@ fn test_library_input_serialization() { serde_json::to_value(LibraryInput::ClearSelection).unwrap(), serde_json::json!("clearSelection") ); + // Exactly what the match dialog's platform switch sends. + assert_eq!( + serde_json::to_value(LibraryInput::SetMatchPlatformFilter { enabled: false }).unwrap(), + serde_json::json!({ "setMatchPlatformFilter": { "enabled": false } }) + ); } #[test] @@ -648,6 +655,23 @@ fn query_view_types_serialize_with_the_keys_the_ui_reads() { "entryId": "entry-1" }) ); + + // The match dialog's platform narrowing is camelCase for the UI's chip and counts. + assert_eq!( + serde_json::to_value(MatchPlatformFilter { + platform: "gamecube".into(), + label: "GameCube".into(), + aliases: vec!["NGC".into(), "GC".into()], + enabled: true, + }) + .unwrap(), + serde_json::json!({ + "platform": "gamecube", + "label": "GameCube", + "aliases": ["NGC", "GC"], + "enabled": true + }) + ); } #[test] diff --git a/crates/platform/Cargo.toml b/crates/platform/Cargo.toml index 930b21c31..697698978 100644 --- a/crates/platform/Cargo.toml +++ b/crates/platform/Cargo.toml @@ -13,12 +13,13 @@ workspace = true [dependencies] reqwest = { version = "0.13.5", default-features = false, features = ["blocking", "rustls"] } +ring = "0.17.14" gamenode-core.workspace = true dirs = "7.0.0" image = { version = "0.25.10", default-features = false, features = ["png", "jpeg", "webp"] } getrandom.workspace = true open.workspace = true -rusqlite = { version = "0.41.1", features = ["bundled"] } +rusqlite = { version = "0.41.1", features = ["backup", "bundled"] } serde.workspace = true serde_json.workspace = true thiserror.workspace = true @@ -28,11 +29,13 @@ url.workspace = true serde_yaml = "0.9.34" sha1 = "0.10.7" sha2 = "0.10.9" +semver = "1.0.27" +base64 = "0.22.1" sevenz-rust2 = "0.20" zip = { version = "2.4", default-features = false, features = ["deflate"] } [target.'cfg(unix)'.dependencies] -rustix = { version = "1.1.6", features = ["fs", "process"] } +rustix = { version = "1.1.6", features = ["fs", "process", "system", "event"] } [target.'cfg(target_os = "linux")'.dependencies] keyring-core = "1.0.1" @@ -54,6 +57,7 @@ windows-sys = { version = "0.61.2", features = [ "Win32_System_Threading", "Win32_System_Diagnostics_ToolHelp", "Win32_System_ProcessStatus", + "Win32_System_SystemInformation", "Win32_System_JobObjects", "Win32_Graphics_Gdi", "Win32_UI_Controls_Dialogs", diff --git a/crates/platform/examples/upgrade_check.rs b/crates/platform/examples/upgrade_check.rs new file mode 100644 index 000000000..53770ae73 --- /dev/null +++ b/crates/platform/examples/upgrade_check.rs @@ -0,0 +1,117 @@ +//! Native upgrade diagnostic for the settings database. +//! +//! Usage: `cargo run --example upgrade_check -- ` +//! +//! Runs this build's migration runner over a database copy and prints only structural evidence: +//! schema version, recorded migration history, `PRAGMA integrity_check`, per-table row counts and +//! SHA-256 file hashes. It never prints row values, so it is safe to run on a copied profile. + +use std::path::{Path, PathBuf}; + +use sha2::{Digest, Sha256}; + +fn file_sha256(path: &Path) -> Option { + let bytes = std::fs::read(path).ok()?; + Some(format!("{:x}", Sha256::digest(bytes))) +} + +fn print_history(conn: &rusqlite::Connection) { + let mut statement = conn + .prepare("SELECT version, name FROM schema_migrations ORDER BY version") + .expect("schema_migrations is readable"); + let rows = statement + .query_map([], |row| { + Ok((row.get::<_, u32>(0)?, row.get::<_, String>(1)?)) + }) + .expect("history is readable"); + for row in rows { + let (version, name) = row.expect("history row decodes"); + println!(" {version}\t{name}"); + } +} + +fn print_tables(conn: &rusqlite::Connection) { + let mut statement = conn + .prepare( + "SELECT name FROM sqlite_master + WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name", + ) + .expect("sqlite_master is readable"); + let tables = statement + .query_map([], |row| row.get::<_, String>(0)) + .expect("table names decode") + .map(Result::unwrap) + .collect::>(); + for table in tables { + let count: i64 = conn + .query_row( + &format!("SELECT COUNT(*) FROM \"{}\"", table.replace('"', "\"\"")), + [], + |row| row.get(0), + ) + .expect("table is readable"); + println!(" {table}\t{count}"); + } +} + +fn main() -> std::process::ExitCode { + let Some(path) = std::env::args_os().nth(1).map(PathBuf::from) else { + eprintln!("usage: upgrade_check "); + return std::process::ExitCode::from(2); + }; + + println!("database: {}", path.display()); + if let Some(hash) = file_sha256(&path) { + println!("sha256 before: {hash}"); + } + + let conn = match gamenode_platform::db::open(&path) { + Ok(conn) => conn, + Err(error) => { + eprintln!("refused: {error}"); + if let Some(hash) = file_sha256(&path) { + println!("sha256 after: {hash}"); + } + return std::process::ExitCode::FAILURE; + } + }; + + let integrity: String = conn + .query_row("PRAGMA integrity_check", [], |row| row.get(0)) + .expect("integrity_check runs"); + let version: u32 = conn + .query_row( + "SELECT COALESCE(MAX(version), 0) FROM schema_migrations", + [], + |row| row.get(0), + ) + .expect("history is readable"); + println!("schema version: {version}"); + println!("integrity_check: {integrity}"); + println!("history:"); + print_history(&conn); + println!("tables:"); + print_tables(&conn); + drop(conn); + if let Some(hash) = file_sha256(&path) { + println!("sha256 after: {hash}"); + } + if let Ok(entries) = std::fs::read_dir(path.parent().unwrap_or(Path::new("."))) { + let prefix = format!( + "{}.pre-migration-", + path.file_name() + .map(|name| name.to_string_lossy().into_owned()) + .unwrap_or_default() + ); + for entry in entries.flatten() { + if entry + .file_name() + .to_string_lossy() + .starts_with(prefix.as_str()) + { + println!("snapshot: {}", entry.path().display()); + } + } + } + std::process::ExitCode::SUCCESS +} diff --git a/crates/platform/migrations/0017_library_installations.sql b/crates/platform/migrations/0017_library_installations.sql new file mode 100644 index 000000000..899180d57 --- /dev/null +++ b/crates/platform/migrations/0017_library_installations.sql @@ -0,0 +1,8 @@ +-- The opaque installation identity plugins see for a library entry. One row per entry key +-- (`:`); the id is random, assigned once and never changed, so it survives +-- rescans, renames and match changes and reveals neither the store id nor a path. Rows are never +-- deleted, like the entries themselves. Nothing here is a credential. +CREATE TABLE library_installations ( + entry_key TEXT PRIMARY KEY NOT NULL, + installation_id TEXT NOT NULL UNIQUE +) STRICT; diff --git a/crates/platform/migrations/0018_library_display_overrides.sql b/crates/platform/migrations/0018_library_display_overrides.sql new file mode 100644 index 000000000..cc63bbe22 --- /dev/null +++ b/crates/platform/migrations/0018_library_display_overrides.sql @@ -0,0 +1,9 @@ +-- Presentation overrides a provider's plugin wrote for one of its own library entries. The +-- detected name stays in library_entries; clearing an override sets display_name to NULL and keeps +-- the row, so `revision` (writes per entry, starting at 1) only ever grows. Nothing here is a +-- credential. +CREATE TABLE library_display_overrides ( + entry_key TEXT PRIMARY KEY NOT NULL, + display_name TEXT, + revision INTEGER NOT NULL CHECK (revision >= 1) +) STRICT; diff --git a/crates/platform/migrations/0019_chosen_match_source.sql b/crates/platform/migrations/0019_chosen_match_source.sql new file mode 100644 index 000000000..f514ef1ab --- /dev/null +++ b/crates/platform/migrations/0019_chosen_match_source.sql @@ -0,0 +1,5 @@ +-- Who made a stored match choice: the user in the match dialog, or a plugin for one of its own +-- entries. A plugin may replace its own choices but never the user's. Choices stored before this +-- migration were made by the user, which is the default. +ALTER TABLE chosen_matches + ADD COLUMN source TEXT NOT NULL DEFAULT 'user' CHECK (source IN ('user', 'plugin')); diff --git a/crates/platform/migrations/0020_library_artwork_overrides.sql b/crates/platform/migrations/0020_library_artwork_overrides.sql new file mode 100644 index 000000000..fe5ea7533 --- /dev/null +++ b/crates/platform/migrations/0020_library_artwork_overrides.sql @@ -0,0 +1,9 @@ +-- The cover a provider's plugin set for one of its own library entries. `file` names an image in +-- the covers folder that this entry alone owns; the game's own cover stays untouched. Clearing an +-- override sets file to NULL and keeps the row, so `revision` (writes per entry, starting at 1) +-- only ever grows. Nothing here is a credential. +CREATE TABLE library_artwork_overrides ( + entry_key TEXT PRIMARY KEY NOT NULL, + file TEXT, + revision INTEGER NOT NULL CHECK (revision >= 1) +) STRICT; diff --git a/crates/platform/migrations/0021_library_entry_targets.sql b/crates/platform/migrations/0021_library_entry_targets.sql new file mode 100644 index 000000000..9a31d8dee --- /dev/null +++ b/crates/platform/migrations/0021_library_entry_targets.sql @@ -0,0 +1,6 @@ +-- The launch target a provider detected for one of its own library entries (task 7.7). The +-- serialized value carries the target's revision, the user's approval and the file identity the +-- platform recorded at approval. A target the next scan no longer reports keeps its row with +-- `available` false, so the entry can offer repair instead of silently forgetting it. Storing a +-- target never starts a process. +ALTER TABLE library_entries ADD COLUMN target_json TEXT; diff --git a/crates/platform/migrations/0022_plugin_custom_launch_recipes.sql b/crates/platform/migrations/0022_plugin_custom_launch_recipes.sql new file mode 100644 index 000000000..1570f6bc2 --- /dev/null +++ b/crates/platform/migrations/0022_plugin_custom_launch_recipes.sql @@ -0,0 +1,13 @@ +-- Host-owned, plugin-scoped custom launch recipes. The JSON contains only typed fields and opaque +-- host handles; executable paths and secret values are resolved at launch time, never persisted. +CREATE TABLE plugin_custom_launch_recipes ( + owner_key TEXT NOT NULL, + recipe_id TEXT NOT NULL, + installation_id TEXT NOT NULL, + revision INTEGER NOT NULL, + recipe_json TEXT NOT NULL, + PRIMARY KEY (owner_key, recipe_id) +) STRICT; + +CREATE INDEX plugin_custom_launch_recipes_installation + ON plugin_custom_launch_recipes (owner_key, installation_id); diff --git a/crates/platform/migrations/0023_plugin_runtime_resources.sql b/crates/platform/migrations/0023_plugin_runtime_resources.sql new file mode 100644 index 000000000..f7c0d4999 --- /dev/null +++ b/crates/platform/migrations/0023_plugin_runtime_resources.sql @@ -0,0 +1,33 @@ +-- Plugin-owned runtime/interpreter descriptors and content bindings. Runtime records describe +-- already approved installed software; they do not install files. Bindings intentionally have no +-- foreign key to runtime records or games so runtime removal cannot delete content, save/history, +-- or the binding needed to explain and migrate that content later. +CREATE TABLE plugin_runtime_resources ( + owner_key TEXT NOT NULL, + runtime_id TEXT NOT NULL, + revision INTEGER NOT NULL CHECK (revision > 0), + runtime_json TEXT NOT NULL, + PRIMARY KEY (owner_key, runtime_id) +) STRICT; + +CREATE TABLE plugin_runtime_content_bindings ( + owner_key TEXT NOT NULL, + game_id INTEGER NOT NULL CHECK (game_id > 0), + installation_id TEXT NOT NULL, + content_id TEXT NOT NULL, + runtime_id TEXT NOT NULL, + revision INTEGER NOT NULL CHECK (revision > 0), + binding_json TEXT NOT NULL, + PRIMARY KEY (owner_key, game_id, installation_id, content_id, runtime_id) +) STRICT; + +CREATE INDEX plugin_runtime_content_bindings_game + ON plugin_runtime_content_bindings (owner_key, game_id, installation_id); + +CREATE INDEX plugin_runtime_content_bindings_runtime + ON plugin_runtime_content_bindings (owner_key, runtime_id); + +CREATE TABLE plugin_runtime_catalog_state ( + owner_key TEXT PRIMARY KEY NOT NULL, + catalog_revision INTEGER NOT NULL CHECK (catalog_revision >= 0) +) STRICT; diff --git a/crates/platform/migrations/0024_library_launch_recipe_selection.sql b/crates/platform/migrations/0024_library_launch_recipe_selection.sql new file mode 100644 index 000000000..bd2b1b60a --- /dev/null +++ b/crates/platform/migrations/0024_library_launch_recipe_selection.sql @@ -0,0 +1,13 @@ +-- The user's selected recipe is separate from the plugin-owned recipe and stays scoped to the +-- library entry. A stale row is retained so deleting or revoking a recipe never silently falls +-- back to the detected launch target. +CREATE TABLE library_launch_recipe_selection ( + entry_key TEXT PRIMARY KEY NOT NULL REFERENCES library_entries(key) ON DELETE CASCADE, + owner_key TEXT NOT NULL, + plugin_id TEXT NOT NULL, + publisher_fingerprint TEXT NOT NULL, + recipe_id TEXT NOT NULL, + recipe_revision INTEGER NOT NULL CHECK (recipe_revision >= 1), + base_target_revision INTEGER NOT NULL CHECK (base_target_revision >= 0), + approved_plan_fingerprint TEXT NOT NULL DEFAULT '' +) STRICT; diff --git a/crates/platform/migrations/0025_plugin_bundles.sql b/crates/platform/migrations/0025_plugin_bundles.sql new file mode 100644 index 000000000..447a3f743 --- /dev/null +++ b/crates/platform/migrations/0025_plugin_bundles.sql @@ -0,0 +1,21 @@ +-- Bundle grouping only: component packages, grants and activation stay in their existing stores. +-- Deleting this mapping never removes a package, and a standalone import leaves no row here. A +-- component plugin id belongs to at most one bundle at a time, so the inventory and uninstall can +-- resolve a plugin to exactly one bundle; a second bundle must adopt or report a conflict first. +CREATE TABLE plugin_bundles ( + bundle_id TEXT PRIMARY KEY NOT NULL, + name TEXT NOT NULL, + version TEXT NOT NULL, + publisher_fingerprint TEXT NOT NULL, + manifest_sha256 TEXT NOT NULL, + installed_at INTEGER NOT NULL CHECK (installed_at >= 0) +) STRICT; + +CREATE TABLE plugin_bundle_components ( + bundle_id TEXT NOT NULL REFERENCES plugin_bundles(bundle_id) ON DELETE CASCADE, + plugin_id TEXT NOT NULL UNIQUE, + kind TEXT NOT NULL CHECK (kind IN ('provider', 'extension')), + component_sha256 TEXT NOT NULL, + package_version TEXT NOT NULL, + PRIMARY KEY (bundle_id, plugin_id) +) STRICT; diff --git a/crates/platform/migrations/0026_plugin_bundle_history.sql b/crates/platform/migrations/0026_plugin_bundle_history.sql new file mode 100644 index 000000000..eaba1818c --- /dev/null +++ b/crates/platform/migrations/0026_plugin_bundle_history.sql @@ -0,0 +1,25 @@ +-- Previous bundle mappings, kept only so a bundle update can be rolled back to the component set +-- and package versions that were active before it. The current mapping stays in plugin_bundles; +-- history never owns packages, grants or activation, and no other table references it. +CREATE TABLE plugin_bundle_history ( + bundle_id TEXT NOT NULL, + version TEXT NOT NULL, + name TEXT NOT NULL, + publisher_fingerprint TEXT NOT NULL, + manifest_sha256 TEXT NOT NULL, + installed_at INTEGER NOT NULL CHECK (installed_at >= 0), + archived_at INTEGER NOT NULL CHECK (archived_at >= 0), + PRIMARY KEY (bundle_id, version) +) STRICT; + +CREATE TABLE plugin_bundle_history_components ( + bundle_id TEXT NOT NULL, + version TEXT NOT NULL, + plugin_id TEXT NOT NULL, + kind TEXT NOT NULL CHECK (kind IN ('provider', 'extension')), + component_sha256 TEXT NOT NULL, + package_version TEXT NOT NULL, + PRIMARY KEY (bundle_id, version, plugin_id), + FOREIGN KEY (bundle_id, version) + REFERENCES plugin_bundle_history(bundle_id, version) ON DELETE CASCADE +) STRICT; diff --git a/crates/platform/src/backups.rs b/crates/platform/src/backups.rs index ba6faa4fa..d552345bb 100644 --- a/crates/platform/src/backups.rs +++ b/crates/platform/src/backups.rs @@ -11,6 +11,78 @@ use std::{ time::{Duration, Instant}, }; +#[derive(Clone)] +struct Execution { + namespace: Vec, + target: BackupTarget, + job_id: Option, + profile: SaveProfile, + destination: String, + operation: BackupOperation, +} + +struct LegacyAuthority; +impl BackupAuthority for LegacyAuthority { + fn check(&self) -> Result<(), LocalError> { + Ok(()) + } + fn validate_targets(&self, _: &[String], _: &[String]) -> Result<(), LocalError> { + Ok(()) + } +} + +impl Execution { + fn legacy(request: &BackupRequest) -> Result { + let profile = request.profile.clone(); + Ok(Self { + namespace: vec!["manual".into()], + target: BackupTarget { + installation_id: request.installation.id.clone(), + root: request.installation.root.clone(), + gameplay: request.installation.gameplay.clone(), + track_folder: false, + }, + job_id: request.job_id.clone(), + profile, + destination: request.destination.clone(), + operation: request.operation.clone(), + }) + } + fn scoped(request: &ScopedBackupRequest) -> Self { + Self { + namespace: vec!["plugins".into(), request.owner.clone()], + target: request.target.clone(), + job_id: request.job_id.clone(), + profile: request.profile.clone(), + destination: request.destination.clone(), + operation: request.operation.clone(), + } + } + fn suffix(&self) -> Result { + let mut path = PathBuf::new(); + for id in self.namespace.iter().map(String::as_str).chain([ + self.target.installation_id.as_str(), + self.profile.id.as_str(), + ]) { + if id.is_empty() + || !id + .bytes() + .all(|c| c.is_ascii_alphanumeric() || c == b'-' || c == b'_') + { + return Err(LocalError::InvalidTarget); + } + path.push(id); + } + Ok(path) + } + fn namespace(&self) -> Result { + if !Path::new(&self.destination).is_absolute() { + return Err(LocalError::InvalidTarget); + } + Ok(Path::new(&self.destination).join(self.suffix()?)) + } +} + pub struct Ludusavi { pub helper: PathBuf, pub private: PathBuf, @@ -31,29 +103,16 @@ impl Ludusavi { }) } pub fn namespace(request: &BackupRequest) -> Result { - if !Path::new(&request.destination).is_absolute() { - return Err(LocalError::InvalidTarget); - } - for id in [&request.installation.id, &request.profile.id] { - if id.is_empty() - || !id - .bytes() - .all(|c| c.is_ascii_alphanumeric() || c == b'-' || c == b'_') - { - return Err(LocalError::InvalidTarget); - } - } - Ok(Path::new(&request.destination) - .join("manual") - .join(&request.installation.id) - .join(&request.profile.id)) + Execution::legacy(request)?.namespace() } fn run( &self, args: &[String], cancelled: &AtomicBool, - stopped: Option<&Registration>, + stopped: Option<&BackupTarget>, + authority: &dyn BackupAuthority, ) -> Result { + authority.check()?; if !self.helper.is_absolute() || !self.helper.is_file() { return Err(LocalError::Failed( "bundled backup helper is unavailable".into(), @@ -99,6 +158,11 @@ impl Ludusavi { let start = Instant::now(); let mut next_check = Instant::now(); let outcome = loop { + if let Err(error) = authority.check() { + let _ = child.kill(); + let _ = child.wait(); + break Err(error); + } if cancelled.load(Ordering::Relaxed) || overflow.load(Ordering::Relaxed) || start.elapsed() > Duration::from_secs(300) @@ -153,13 +217,10 @@ impl Ludusavi { } Ok(value) } - fn config(&self, request: &BackupRequest) -> Result { - let path = self - .private - .join(&request.installation.id) - .join(&request.profile.id); + fn config(&self, request: &Execution) -> Result { + let path = self.private.join(request.suffix()?); std::fs::create_dir_all(&path).map_err(failed)?; - let definition = execution_definition(&request.profile, &request.installation)?; + let definition = execution_definition_at(&request.profile, &request.target.root)?; let mut manifest = serde_yaml::Mapping::new(); manifest.insert( serde_yaml::Value::String(request.profile.title.clone()), @@ -179,17 +240,25 @@ impl Ludusavi { Ok(path) } } -fn ensure_stopped(installation: &Registration) -> Result<(), LocalError> { +fn ensure_stopped(installation: &BackupTarget) -> Result<(), LocalError> { use gamenode_core::ports::Processes; let processes = crate::processes::HostProcesses::new() .list() .map_err(|_| failed("cannot confirm game is stopped"))?; let normalized = |p: &str| gamenode_core::provider::path::normalize(p).to_lowercase(); if processes.iter().any(|p| { - installation - .gameplay - .iter() - .any(|exe| normalized(exe) == normalized(&p.exe_path)) + let exe = normalized(&p.exe_path); + installation.gameplay.iter().any(|path| { + resolve_install_path(&installation.root, path) + .is_some_and(|path| normalized(&path) == exe) + }) || (installation.track_folder + && !installation.root.is_empty() + && exe.starts_with( + &(normalized(&installation.root) + .trim_end_matches('/') + .to_owned() + + "/"), + )) }) { return Err(failed("game is running")); } @@ -214,6 +283,12 @@ pub fn glob_literal(path: &str) -> String { pub fn execution_definition( profile: &SaveProfile, installation: &Registration, +) -> Result { + execution_definition_at(profile, &installation.root) +} +fn execution_definition_at( + profile: &SaveProfile, + root: &str, ) -> Result { let mut definition: serde_yaml::Value = serde_yaml::from_str(&profile.definition).map_err(failed)?; @@ -230,19 +305,19 @@ pub fn execution_definition( let mut bound = serde_yaml::Mapping::new(); for (path, rule) in files.iter() { let path = path.as_str().ok_or(LocalError::InvalidTarget)?; - let game = Path::new(&installation.root) + let game = Path::new(root) .file_name() .ok_or(LocalError::InvalidTarget)? .to_string_lossy(); - let path = path.replace("/", &glob_literal(&installation.root)); + let path = path.replace("/", &glob_literal(root)); if path.contains("") { return Err(failed( "save rule requires an explicit installation context", )); } let path = path - .replace("", &glob_literal(&installation.root)) - .replace("", &glob_literal(&installation.root)) + .replace("", &glob_literal(root)) + .replace("", &glob_literal(root)) .replace("", &glob_literal(&game)); bound.insert(serde_yaml::Value::String(path), rule.clone()); } @@ -250,6 +325,24 @@ pub fn execution_definition( } Ok(definition) } +fn validate_report_targets( + value: &Value, + title: &str, + authority: &dyn BackupAuthority, +) -> Result<(), LocalError> { + let game = value + .get("games") + .and_then(|g| g.get(title)) + .ok_or(LocalError::InvalidTarget)?; + let targets = |kind: &str| { + game.get(kind) + .and_then(Value::as_object) + .map(|m| m.keys().cloned().collect::>()) + .unwrap_or_default() + }; + authority.validate_targets(&targets("files"), &targets("registry")) +} + fn has_failure(value: &Value) -> bool { match value { Value::Object(map) => map.iter().any(|(key, value)| { @@ -326,33 +419,98 @@ impl BackupEngine for Ludusavi { .writer .lock() .map_err(|_| failed("backup writer lock failed"))?; - self.execute_serialized(request, cancelled) + self.execute_serialized(&Execution::legacy(request)?, cancelled, &LegacyAuthority) + } + + fn scoped_available(&self) -> bool { + cfg!(windows) + } + + fn execute_scoped( + &self, + request: &ScopedBackupRequest, + cancelled: &AtomicBool, + authority: &dyn BackupAuthority, + ) -> Result { + if !self.scoped_available() { + return Err(LocalError::Unsupported); + } + let deadline = Instant::now() + Duration::from_secs(300); + let _guard = loop { + authority.check()?; + if cancelled.load(Ordering::Relaxed) { + return Err(LocalError::Cancelled); + } + match self.writer.try_lock() { + Ok(guard) => break guard, + Err(std::sync::TryLockError::Poisoned(_)) => { + return Err(failed("backup writer lock failed")); + } + Err(std::sync::TryLockError::WouldBlock) => { + if Instant::now() >= deadline { + return Err(failed("backup writer unavailable")); + } + std::thread::sleep(Duration::from_millis(25)); + } + } + }; + if matches!( + request.operation, + BackupOperation::Backup | BackupOperation::Restore { .. } + ) { + if !request.target.track_folder && request.target.gameplay.is_empty() { + return Err(LocalError::Unsupported); + } + ensure_stopped(&request.target)?; + } + self.execute_serialized(&Execution::scoped(request), cancelled, authority) } } impl Ludusavi { fn execute_serialized( &self, - request: &BackupRequest, + request: &Execution, cancelled: &AtomicBool, + authority: &dyn BackupAuthority, ) -> Result { #[cfg(not(windows))] { - let _ = (request, cancelled); + let _ = (request, cancelled, authority); return Err(LocalError::Unsupported); } #[allow(unreachable_code)] { + authority.check()?; + if cancelled.load(Ordering::Relaxed) { + return Err(LocalError::Cancelled); + } if request.profile.title.trim().is_empty() { return Err(LocalError::InvalidTarget); } if self.checked.get().is_none() { - self.run(&["--version".into()], cancelled, None)?; + self.run(&["--version".into()], cancelled, None, authority)?; let _ = self.checked.set(()); } if request.profile.title.trim().is_empty() { return Err(LocalError::InvalidTarget); } - let active = Self::namespace(request)?; + let active = request.namespace()?; + if request.operation == BackupOperation::History { + match std::fs::metadata(&active) { + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + // A reachable destination with no namespace has no versions yet. Never + // create an archive folder just to list it, or hide an I/O/access error. + resolved_destination(Path::new(&request.destination))?; + return Ok(BackupReport { + state: JobState::Successful, + json: "{\"games\":{}}".into(), + }); + } + Err(error) => return Err(failed(error)), + Ok(metadata) if !metadata.is_dir() => return Err(LocalError::InvalidTarget), + Ok(_) => {} + } + } reconcile(&active)?; if matches!(request.operation, BackupOperation::Backup) && let Some(job_id) = &request.job_id @@ -382,7 +540,7 @@ impl Ludusavi { "--".into(), request.profile.title.clone(), ]; - let preview = self.run(&preview_args, cancelled, None)?; + let preview = self.run(&preview_args, cancelled, None, authority)?; let files = preview .get("games") .and_then(|g| g.get(&request.profile.title)) @@ -395,23 +553,30 @@ impl Ludusavi { &files .iter() .map(PathBuf::from) - .chain([PathBuf::from(&request.installation.root)]) + .chain([PathBuf::from(&request.target.root)]) .collect::>(), )?; + if preview + .get("games") + .and_then(|g| g.get(&request.profile.title)) + .is_some() + { + validate_report_targets(&preview, &request.profile.title, authority)?; + } if has_failure(&preview) { return Err(failed("save preview reported partial failure")); } } if let BackupOperation::Restore { backup } = &request.operation { - ensure_stopped(&request.installation)?; - let preview_request = BackupRequest { + ensure_stopped(&request.target)?; + let preview_request = Execution { operation: BackupOperation::RestorePreview { backup: backup.clone(), }, ..request.clone() }; - let preview = self.execute_serialized(&preview_request, cancelled)?; + let preview = self.execute_serialized(&preview_request, cancelled, authority)?; if preview.state == JobState::Partial { return Err(failed("restore preview failed")); } @@ -420,6 +585,7 @@ impl Ludusavi { .get("games") .and_then(|g| g.get(&request.profile.title)) .ok_or_else(|| failed("restore preview omitted game"))?; + validate_report_targets(&preview, &request.profile.title, authority)?; let mut definition = serde_json::json!({"files":{},"registry":{}}); for kind in ["files", "registry"] { if let Some(targets) = game.get(kind).and_then(Value::as_object) { @@ -445,13 +611,13 @@ impl Ludusavi { crate::random::session_id() ); recovery.profile.definition = definition.to_string(); - let report = self.execute_serialized(&recovery, cancelled)?; + let report = self.execute_serialized(&recovery, cancelled, authority)?; if !matches!(report.state, JobState::Successful | JobState::Unchanged) { return Err(failed("recovery backup failed; restore aborted")); } std::fs::create_dir_all(&active).map_err(failed)?; - std::fs::write(active.join(".gamenode-restore-recovery.json"), serde_json::to_vec(&serde_json::json!({"backup":backup,"recovery":Self::namespace(&recovery)?,"preview":preview,"state":report.state})).map_err(failed)?).map_err(failed)?; - ensure_stopped(&request.installation)?; + std::fs::write(active.join(".gamenode-restore-recovery.json"), serde_json::to_vec(&serde_json::json!({"backup":backup,"recovery":recovery.namespace()?,"preview":preview,"state":report.state})).map_err(failed)?).map_err(failed)?; + ensure_stopped(&request.target)?; } let stage = active.with_extension("staging"); @@ -515,10 +681,11 @@ impl Ludusavi { request.operation, BackupOperation::Backup | BackupOperation::Restore { .. } ) { - Some(&request.installation) + Some(&request.target) } else { None }, + authority, )?; if !report.get("games").is_some_and(|g| g.is_object()) { return Err(failed("backup helper report has no games")); @@ -551,6 +718,10 @@ impl Ludusavi { } else { JobState::Successful }; + authority.check()?; + if cancelled.load(Ordering::Relaxed) { + return Err(LocalError::Cancelled); + } if backup && matches!(state, JobState::Successful | JobState::Unchanged) { std::fs::write( stage.join(".gamenode-verified.json"), @@ -666,6 +837,62 @@ mod tests { "unknown values fall back to the default instead of reaching the helper" ); } + #[test] + fn scoped_namespaces_preserve_installation_identity_without_claiming_manual_ownership() { + let temp = tempfile::tempdir().unwrap(); + let request = ScopedBackupRequest { + owner: "owner_a".into(), + target: BackupTarget { + installation_id: "installation_a".into(), + root: "C:/Game".into(), + gameplay: vec![], + track_folder: true, + }, + job_id: None, + profile: SaveProfile { + id: "profile_a".into(), + installation: "opaque-store-installation".into(), + revision: 1, + title: "Profile".into(), + manifest_hash: String::new(), + definition: "{}".into(), + files: vec![], + registry: vec![], + support: SaveSupport::Supported, + automatic: None, + retention: None, + }, + destination: temp.path().to_string_lossy().into_owned(), + operation: BackupOperation::History, + }; + let execution = Execution::scoped(&request); + assert_eq!( + execution.namespace().unwrap(), + temp.path().join("plugins/owner_a/installation_a/profile_a") + ); + let mut other = request.clone(); + other.owner = "owner_b".into(); + assert_ne!( + Execution::scoped(&other).namespace().unwrap(), + execution.namespace().unwrap() + ); + other.owner = "../escape".into(); + assert_eq!( + Execution::scoped(&other).namespace(), + Err(LocalError::InvalidTarget) + ); + #[cfg(not(windows))] + { + let adapter = Ludusavi::bundled(temp.path()).unwrap(); + assert!(!adapter.scoped_available()); + assert_eq!( + adapter.execute_scoped(&request, &AtomicBool::new(false), &LegacyAuthority), + Err(LocalError::Unsupported) + ); + assert!(std::fs::read_dir(temp.path()).unwrap().next().is_none()); + } + } + #[test] fn partial_errors_and_glob_literals_are_preserved() { assert!(has_failure( diff --git a/crates/platform/src/covers.rs b/crates/platform/src/covers.rs index 6d3488697..522dbf379 100644 --- a/crates/platform/src/covers.rs +++ b/crates/platform/src/covers.rs @@ -260,21 +260,28 @@ pub fn cover_file_name(game_id: u64) -> String { /// Writes a game's cover atomically and returns its file name. pub fn write_cover(dir: &Path, game_id: u64, bytes: &[u8]) -> io::Result { - fs::create_dir_all(dir)?; let name = cover_file_name(game_id); + write_named(dir, &name, bytes)?; + Ok(name) +} + +/// Writes `bytes` to `dir/name` atomically: a reader never sees half an image and a failed write +/// leaves the previous file alone. `name` must be a plain file name. +pub fn write_named(dir: &Path, name: &str, bytes: &[u8]) -> io::Result<()> { + fs::create_dir_all(dir)?; let temp = dir.join(format!(".{name}.{}.part", std::process::id())); let written = (|| { let mut file = File::create(&temp)?; file.write_all(bytes)?; drop(file); - fs::rename(&temp, dir.join(&name)) + fs::rename(&temp, dir.join(name)) })(); if written.is_err() { // Best effort: a leftover `.part` file is harmless but should not pile up. let _ = fs::remove_file(&temp); } - written.map(|()| name) + written } #[cfg(test)] diff --git a/crates/platform/src/db.rs b/crates/platform/src/db.rs index 78bef23c6..38cce5bac 100644 --- a/crates/platform/src/db.rs +++ b/crates/platform/src/db.rs @@ -16,7 +16,7 @@ pub struct Migration { } /// The latest supported schema version. -pub const CURRENT_SCHEMA_VERSION: u32 = 16; +pub const CURRENT_SCHEMA_VERSION: u32 = 26; /// Every migration this build knows. Append new ones; never edit or reorder released ones. pub const MIGRATIONS: &[Migration] = &[ @@ -100,6 +100,56 @@ pub const MIGRATIONS: &[Migration] = &[ name: "sync_summary", sql: include_str!("../migrations/0016_sync_summary.sql"), }, + Migration { + version: 17, + name: "library_installations", + sql: include_str!("../migrations/0017_library_installations.sql"), + }, + Migration { + version: 18, + name: "library_display_overrides", + sql: include_str!("../migrations/0018_library_display_overrides.sql"), + }, + Migration { + version: 19, + name: "chosen_match_source", + sql: include_str!("../migrations/0019_chosen_match_source.sql"), + }, + Migration { + version: 20, + name: "library_artwork_overrides", + sql: include_str!("../migrations/0020_library_artwork_overrides.sql"), + }, + Migration { + version: 21, + name: "library_entry_targets", + sql: include_str!("../migrations/0021_library_entry_targets.sql"), + }, + Migration { + version: 22, + name: "plugin_custom_launch_recipes", + sql: include_str!("../migrations/0022_plugin_custom_launch_recipes.sql"), + }, + Migration { + version: 23, + name: "plugin_runtime_resources", + sql: include_str!("../migrations/0023_plugin_runtime_resources.sql"), + }, + Migration { + version: 24, + name: "library_launch_recipe_selection", + sql: include_str!("../migrations/0024_library_launch_recipe_selection.sql"), + }, + Migration { + version: 25, + name: "plugin_bundles", + sql: include_str!("../migrations/0025_plugin_bundles.sql"), + }, + Migration { + version: 26, + name: "plugin_bundle_history", + sql: include_str!("../migrations/0026_plugin_bundle_history.sql"), + }, ]; const BOOKKEEPING: &str = "CREATE TABLE IF NOT EXISTS schema_migrations ( @@ -132,26 +182,24 @@ pub fn migrate(conn: &mut Connection, migrations: &[Migration]) -> Result<(), St } let supported = latest_version(migrations); - // Inspect without writing, so a newer or foreign database stays byte-for-byte unchanged. - let has_history = conn - .query_row( - "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'schema_migrations'", - [], - |_| Ok(()), - ) - .optional() - .map_err(failed)? - .is_some(); - let applied = if has_history { - let found: Option = conn - .query_row("SELECT MAX(version) FROM schema_migrations", [], |row| { - row.get(0) - }) - .map_err(failed)?; - let found = found.unwrap_or(0); + // Inspect the full recorded history without writing, so mismatched, foreign or newer + // databases stay byte-for-byte unchanged. + let history = migration_history_from_connection(conn)?; + let applied = if let Some(history) = &history { + let found = history.last().map_or(0, |(version, _)| *version); if found > supported { return Err(StorageError::NewerSchema { found, supported }); } + let expected = migrations + .iter() + .take(history.len()) + .map(|migration| (migration.version, migration.name.to_owned())) + .collect::>(); + if history != &expected { + return Err(StorageError::Failed( + "the local database migration history does not match this version; the database was left unchanged".into(), + )); + } found } else { let foreign: i64 = conn @@ -166,6 +214,17 @@ pub fn migrate(conn: &mut Connection, migrations: &[Migration]) -> Result<(), St 0 }; + if applied < supported + && history.is_some() + && let Some(path) = conn.path().filter(|path| is_persistent_database_path(path)) + { + create_verified_migration_snapshot( + conn, + Path::new(path), + history.as_deref().unwrap_or_default(), + )?; + } + for migration in migrations.iter().filter(|m| m.version > applied) { run_migration(conn, migration).map_err(|_| StorageError::MigrationFailed { version: migration.version, @@ -174,6 +233,123 @@ pub fn migrate(conn: &mut Connection, migrations: &[Migration]) -> Result<(), St Ok(()) } +fn migration_history_from_connection( + conn: &Connection, +) -> Result>, StorageError> { + let has_history = conn + .query_row( + "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'schema_migrations'", + [], + |_| Ok(()), + ) + .optional() + .map_err(failed)? + .is_some(); + if !has_history { + return Ok(None); + } + + let mut statement = conn + .prepare("SELECT version, name FROM schema_migrations ORDER BY version") + .map_err(failed)?; + let rows = statement + .query_map([], |row| Ok((row.get(0)?, row.get(1)?))) + .map_err(failed)?; + rows.map(|row| row.map_err(failed)) + .collect::, _>>() + .map(Some) +} + +fn is_persistent_database_path(path: &str) -> bool { + path != ":memory:" && !path.starts_with("file::memory:") && Path::new(path).is_file() +} + +fn create_verified_migration_snapshot( + conn: &Connection, + database_path: &Path, + expected_history: &[(u32, String)], +) -> Result<(), StorageError> { + use std::time::{SystemTime, UNIX_EPOCH}; + + let parent = database_path + .parent() + .filter(|parent| !parent.as_os_str().is_empty()) + .unwrap_or_else(|| Path::new(".")); + let database_name = database_path + .file_name() + .ok_or_else(|| failed("could not identify the local database file"))? + .to_string_lossy(); + let prefix = format!("{database_name}.pre-migration-"); + let timestamp = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_err(failed)? + .as_nanos(); + let stem = format!("{prefix}{timestamp}-{}", std::process::id()); + let mut temporary = parent.join(format!(".{stem}.tmp")); + let mut snapshot = parent.join(format!("{stem}.sqlite")); + for suffix in 0..8 { + if !temporary.exists() && !snapshot.exists() { + break; + } + temporary = parent.join(format!(".{stem}-{suffix}.tmp")); + snapshot = parent.join(format!("{stem}-{suffix}.sqlite")); + } + if temporary.exists() || snapshot.exists() { + return Err(failed( + "could not reserve a migration snapshot file; the migration was not run", + )); + } + + let result = (|| -> Result<(), StorageError> { + conn.backup(rusqlite::MAIN_DB, &temporary, Some(|_| {})) + .map_err(failed)?; + let snapshot_conn = + Connection::open_with_flags(&temporary, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY) + .map_err(failed)?; + let integrity: String = snapshot_conn + .query_row("PRAGMA integrity_check", [], |row| row.get(0)) + .map_err(failed)?; + if integrity != "ok" + || migration_history_from_connection(&snapshot_conn)?.as_deref() + != Some(expected_history) + { + return Err(failed( + "the pre-migration snapshot did not pass verification; the migration was not run", + )); + } + drop(snapshot_conn); + std::fs::File::open(&temporary) + .and_then(|file| file.sync_all()) + .map_err(failed)?; + std::fs::rename(&temporary, &snapshot).map_err(failed)?; + #[cfg(unix)] + std::fs::File::open(parent) + .and_then(|directory| directory.sync_all()) + .map_err(failed)?; + Ok(()) + })(); + + if let Err(error) = result { + let _ = std::fs::remove_file(&temporary); + return Err(failed(format!( + "could not create a verified pre-migration snapshot; the migration was not run ({error})" + ))); + } + + if let Ok(entries) = std::fs::read_dir(parent) { + for entry in entries.flatten() { + let path = entry.path(); + let Some(name) = path.file_name().and_then(|name| name.to_str()) else { + continue; + }; + if name.starts_with(&prefix) && path != snapshot { + let _ = std::fs::remove_file(path); + } + } + } + Ok(()) +} + fn run_migration(conn: &mut Connection, migration: &Migration) -> rusqlite::Result<()> { let tx = conn.transaction()?; tx.execute_batch(migration.sql)?; @@ -291,6 +467,11 @@ impl SqliteSettingsStore { crate::achievement_db::SqliteAchievementStore::new(Arc::clone(&self.conn)) } + /// The plugin bundle mapping on the same serialized connection. + pub fn bundle_store(&self) -> crate::plugin_bundle_db::SqlitePluginBundleStore { + crate::plugin_bundle_db::SqlitePluginBundleStore::new(Arc::clone(&self.conn)) + } + /// Opens and migrates the database at `path`. pub fn open(path: &Path) -> Result { open(path).map(Self::new) @@ -540,8 +721,170 @@ impl SettingsStore for SqliteSettingsStore { mod tests { use super::*; use gamenode_core::{Locale, StartScope, ToolChannel}; + use rusqlite::types::ValueRef; + use sha2::{Digest, Sha256}; use tempfile::TempDir; + #[test] + fn shipped_migrations_have_pinned_versions_names_and_sha256() { + let expected: &[(u32, &str, &str)] = &[ + ( + 1, + "initial_settings", + "7b2a5ad625231bfeb90fda643fccbcc002a2e0f7ebf263f5bb28d064bda4d28c", + ), + ( + 2, + "library", + "65792096f8ab65454754859815d39171c44c908b319901fb2289477af7cc36d0", + ), + ( + 3, + "playtime", + "dd07f5a7f4729c0c96042c780b9e2f70916a6d5a1378fbad2a991c331573bc2b", + ), + ( + 4, + "drm_free_backups", + "762aaa51096ac00b04c348ab8459ecc4b28021a70759e8ec0e7df413c648ed27", + ), + ( + 5, + "game_tools", + "050b3530674c7e4ba55b612035334de9db0b0f5eb1a885f4a106d238258f7cec", + ), + ( + 6, + "store_accounts_and_catalog", + "e9c7347c027545367177a6e2b6b5d79e131cb6f09ac76e808f20392b668cf37b", + ), + ( + 7, + "favorites", + "e5d6983699c00e425cb3496ea916ab4c2358487a022116bc81da26fabf463bb8", + ), + ( + 8, + "ports", + "528fd37f9b5c90f71c2409faa120ee86a600f2646fcdef2b50c65db72a97d244", + ), + ( + 9, + "achievements", + "cf2636fb541ea76d52565025958043ae989f1956c9ed746f4025081c5f0f1ad8", + ), + ( + 10, + "library_organization", + "0c76ddb272825004121c405f0f106b55e5d06efcd0bd7d708327faa8855f3122", + ), + ( + 11, + "game_platforms", + "90c41bbf41c534c5ebb15e7cc9934bc3104f273aa4ae51df36b4bf1e79289833", + ), + ( + 12, + "achievement_rarity", + "c763e8534e424af2db51187f89870e93cb4c16504114465113be11be52aea18a", + ), + ( + 13, + "backup_metadata", + "8c07c9263930d88f12e8fbe86ffb729b72cc32632228e7a56d5922149f163a5d", + ), + ( + 14, + "local_cover", + "0c2f5ed702bb3fd50064c6df603a97e11c709a245f18ad823f982754587fb05c", + ), + ( + 15, + "app_preferences", + "af0f6df34d58e7e298549f277240b5a92ff78ae26398507528bf40fddb442231", + ), + ( + 16, + "sync_summary", + "75be332fee38fff0b1627ad095cbac3288b062321135f989d6721ff424cf65b4", + ), + ( + 17, + "library_installations", + "d2015385d8ea88b8b8313e8b8ab68d2d0991aa57dedc3d0bb8ec53b9e7f6a4c1", + ), + ( + 18, + "library_display_overrides", + "3af7b42d870a0a9d27f5f618f1be768ad8738b620414519e003ced935a5d3086", + ), + ( + 19, + "chosen_match_source", + "8d89fb6ed96fd3d11d707a9914b5be3f2c358a19db580137f6d993eab86c1c20", + ), + ( + 20, + "library_artwork_overrides", + "df4489fba8c4919a5dac008426b0b4e197a0020d8d9541f55ad83cb92dc2d7f3", + ), + ( + 21, + "library_entry_targets", + "32fe99e9201ca0872089eda9c4f9f1050f9b74ef8786f6e4ce3b3ee26f1ae074", + ), + ( + 22, + "plugin_custom_launch_recipes", + "08b87ebc20b8ee86939f19e855e0a149f922ea8d2f4a190e03d1d8b88edfd028", + ), + ( + 23, + "plugin_runtime_resources", + "5e1077e7dc8997eb08b3b6790932c6fc0f03e7c1c1fe92223d067cd288b72573", + ), + ( + 24, + "library_launch_recipe_selection", + "134c3902d5f4919cde7ab9d86370045b30674f0bb99d56c910c60af2c120b820", + ), + ( + 25, + "plugin_bundles", + "f5c58f3128a9561e4c129565be57b5f40fba7269108bc66dfad03efd7541c22c", + ), + ( + 26, + "plugin_bundle_history", + "55793358d3b21538e3ea73bf7389138900d1bc56253ab6844285dd61351f0ddd", + ), + ]; + assert_eq!(MIGRATIONS.len(), expected.len()); + for (migration, (version, name, digest)) in MIGRATIONS.iter().zip(expected) { + assert_eq!(migration.version, *version); + assert_eq!(migration.name, *name); + let actual = format!("{:x}", Sha256::digest(migration.sql.as_bytes())); + assert_eq!(actual, *digest, "{}", migration.name); + } + } + + #[test] + fn fresh_and_main_upgrade_databases_have_the_same_complete_schema() { + let dir = TempDir::new().unwrap(); + let fresh = db_path(&dir).with_file_name("fresh.sqlite"); + let upgraded = db_path(&dir).with_file_name("main.sqlite"); + let fresh_conn = open(&fresh).unwrap(); + let main_conn = open_with(&upgraded, &MIGRATIONS[..16]).unwrap(); + assert_eq!( + versions(&main_conn).last(), + Some(&(16, "sync_summary".to_owned())) + ); + drop(main_conn); + let main_conn = open(&upgraded).unwrap(); + assert_eq!(versions(&main_conn), versions(&fresh_conn)); + assert_eq!(schema_rows(&fresh_conn), schema_rows(&main_conn)); + } + fn db_path(dir: &TempDir) -> std::path::PathBuf { dir.path().join("test.sqlite3") } @@ -556,6 +899,251 @@ mod tests { .collect() } + fn migration_history(migrations: &[Migration]) -> Vec<(u32, String)> { + migrations + .iter() + .map(|migration| (migration.version, migration.name.to_owned())) + .collect() + } + + fn quote_identifier(name: &str) -> String { + format!("\"{}\"", name.replace('"', "\"\"")) + } + + fn table_names(conn: &Connection) -> Vec { + let mut statement = conn + .prepare( + "SELECT name FROM sqlite_master + WHERE type = 'table' AND name NOT LIKE 'sqlite_%' + ORDER BY name", + ) + .unwrap(); + statement + .query_map([], |row| row.get(0)) + .unwrap() + .map(Result::unwrap) + .collect() + } + + fn table_columns(conn: &Connection, table: &str) -> Vec { + let mut statement = conn + .prepare(&format!("PRAGMA table_info({})", quote_identifier(table))) + .unwrap(); + statement + .query_map([], |row| row.get(1)) + .unwrap() + .map(Result::unwrap) + .collect() + } + + fn encoded_value(value: ValueRef<'_>) -> Vec { + let (tag, bytes): (u8, Vec) = match value { + ValueRef::Null => (b'n', Vec::new()), + ValueRef::Integer(number) => (b'i', number.to_le_bytes().to_vec()), + ValueRef::Real(number) => (b'r', number.to_le_bytes().to_vec()), + ValueRef::Text(text) => (b't', text.to_vec()), + ValueRef::Blob(blob) => (b'b', blob.to_vec()), + }; + let mut encoded = Vec::with_capacity(bytes.len() + 9); + encoded.push(tag); + encoded.extend_from_slice(&(bytes.len() as u64).to_le_bytes()); + encoded.extend_from_slice(&bytes); + encoded + } + + /// Row count and a SHA-256 over the requested columns of every row, independent of row order. + fn table_digest(conn: &Connection, table: &str, columns: &[String]) -> (i64, String) { + let projection = columns + .iter() + .map(|column| quote_identifier(column)) + .collect::>() + .join(", "); + let mut statement = conn + .prepare(&format!( + "SELECT {projection} FROM {}", + quote_identifier(table) + )) + .unwrap(); + let mut rows = statement + .query_map([], |row| { + let mut encoded = Vec::new(); + for index in 0..columns.len() { + encoded.extend_from_slice(&encoded_value(row.get_ref(index)?)); + } + Ok(encoded) + }) + .unwrap() + .map(Result::unwrap) + .collect::>(); + rows.sort(); + let mut hasher = Sha256::new(); + for row in &rows { + hasher.update((row.len() as u64).to_le_bytes()); + hasher.update(row); + } + (rows.len() as i64, format!("{:x}", hasher.finalize())) + } + + /// Representative, fictional data for every table that `main` shipped (schema versions 1-16). + /// + /// `main` is `origin/main` at `e37ccd1`; the tests below build this shape with + /// `&MIGRATIONS[..16]`, whose SQL is byte-identical to `main`'s shipped migration files. + fn seed_main_shaped_database(conn: &Connection) { + conn.execute_batch( + r#" + INSERT INTO settings (key, value) VALUES ('window.width', '1280'); + INSERT INTO settings (key, value) VALUES ('account.last_id', 'acct-fixture'); + INSERT INTO library_entries + (key, provider, store_id, name, install_dir, fields_json, installed, + first_seen, last_seen, owned, family_shared) + VALUES ('fixture:1', 'fixture', '1', 'Fixture Game', '/games/fixture', + '{"state_flags":"4"}', 1, 100, 200, 1, 1); + INSERT INTO provider_scans + (provider, last_success_at, last_error, last_catalog_at, catalog_error, + last_family_at, family_error) + VALUES ('fixture', 200, 'scan warning', 190, 'catalog warning', 195, NULL); + INSERT INTO auto_matches (category, uid, game_ids_json, checked_at) + VALUES (1, 'uid-1', '[42]', 110); + INSERT INTO chosen_matches (account_id, entry_key, game_id, chosen_at) + VALUES ('acct-fixture', 'fixture:1', 42, 120); + INSERT INTO games + (game_id, name, release_year, cover_url, cover_file, cover_failed_at, platforms) + VALUES (42, 'Fixture Game', 2020, 'https://images.example/42.jpg', '42.jpg', NULL, + '["windows","linux"]'); + INSERT INTO playtime_sessions + (id, account_id, entry_key, game_id, source, platform_id, started_at, + checkpoint_at, ended_at) + VALUES ('session-1', 'acct-fixture', 'fixture:1', 42, 'fixture', 6, 100, 200, 300); + INSERT INTO playtime_totals + (account_id, entry_key, total_seconds, last_played_at, accepted_game_id, + accepted_seconds, rejected_seconds) + VALUES ('acct-fixture', 'fixture:1', 3600, 300, 42, 3600, 0); + INSERT INTO manual_registrations (id, file_identity, removed, payload) + VALUES ('reg-1', 'identity-1', 0, '{"title":"Fixture Registration"}'); + INSERT INTO discovery_watches (id, payload) + VALUES ('watch-1', '{"path":"/games/fixture"}'); + INSERT INTO discovery_candidates (fingerprint, payload) + VALUES ('candidate-1', '{"title":"Fixture Candidate"}'); + INSERT INTO local_inferences (account_id, installation_id, payload) + VALUES ('acct-fixture', 'installation-1', '{"game_id":42}'); + INSERT INTO save_profiles (id, installation_id, revision, payload) + VALUES ('profile-1', 'installation-1', 3, '{"label":"Fixture Save"}'); + INSERT INTO backup_jobs + (id, installation_id, profile_id, revision, play_period, destination, + state, payload) + VALUES ('backup-job-1', 'installation-1', 'profile-1', 3, '2020-01-01', + '/backups', 'completed', '{"ok":true}'); + INSERT INTO backup_destinations (path) VALUES ('/backups'); + INSERT INTO backup_version_meta + (installation, profile, backup_id, reason, play_seconds, created_at) + VALUES ('installation-1', 'profile-1', 'backup-1', 'manual', 3600, 300); + INSERT INTO tool_installations + (entry_key, tool_id, channel, version, target_exe, proxy_dll, state, + installed_at, updated_at) + VALUES ('fixture:1', 'fixture-tool', 'stable', '1.0.0', 'bin/game.exe', 'dxgi.dll', + 'installed', 1000, 1000); + INSERT INTO tool_files + (entry_key, tool_id, relative_path, installed_sha256, backup_path, + original_sha256, prior_owner_tool_id, created_dirs_json, ini_patches_json, + ini_section, ini_key, ini_value, ini_prior_value) + VALUES ('fixture:1', 'fixture-tool', 'dxgi.dll', 'installed-sha', '/backups/dxgi.dll', + 'original-sha', NULL, '["bin"]', '[]', 'section', 'key', 'value', 'prior'); + INSERT INTO tool_releases_cache + (tool_id, channel, version, tag_name, name, published_at, download_url, + asset_name, size_bytes, sha256, cached_path, fetched_at) + VALUES ('fixture-tool', 'stable', '1.0.0', 'v1.0.0', 'Fixture Tool', + '2026-01-01', 'https://downloads.example/tool.7z', 'tool.7z', 1024, + 'release-sha', NULL, 1000); + INSERT INTO store_accounts (provider, account_id, account_name, last_verified_at) + VALUES ('fixture', 'store-account-1', 'Fixture Account', 900); + INSERT INTO favorites (account_id, game_id, is_favorite, pending, updated_at) + VALUES ('acct-fixture', 42, 1, 0, 170); + INSERT INTO port_catalog_snapshot (id, payload, fetched_at, entry_count) + VALUES (1, '{"apps":["qcat_1"]}', 420, 1); + INSERT INTO port_overlay (id, version, etag, payload) + VALUES (1, 1, 'etag-v1', 'schema_version = 1'); + INSERT INTO port_install_jobs + (id, catalog_id, slug, port_name, release_version, state, phase, + install_folder, created_paths, registration_id, result_seen, + plan_json, release_json, created_at, updated_at, finished_at) + VALUES ('port-job-1', 'qcat_1', 'fixture-port', 'Fixture Port', 'v1', 'completed', + '"completed"', '/ports/fixture', '["/ports/fixture"]', 'port-reg-1', 1, + '{}', '{}', 430, 440, 440); + INSERT INTO port_installations + (registration_id, catalog_id, slug, port_name, installed_version, + install_folder, environment_json, job_id) + VALUES ('port-reg-1', 'qcat_1', 'fixture-port', 'Fixture Port', 'v1', + '/ports/fixture', '{"ROLE":"gameplay"}', 'port-job-1'); + INSERT INTO port_preferences (id, view_mode, filters_json, install_parent) + VALUES (1, 'list', '{"installed":true}', '/ports'); + INSERT INTO achievement_games + (provider, store_account_id, entry_id, state, language, last_success_at, + last_attempt_at, failure) + VALUES ('fixture', 'store-account-1', '1', 'ready', 'english', 500, 500, NULL); + INSERT INTO achievements + (provider, store_account_id, entry_id, achievement_id, name, description, + hidden, icon_url, icon_gray_url, unlocked, unlocked_at, position, + global_percent) + VALUES ('fixture', 'store-account-1', '1', 'achievement-1', 'First', 'Do it', 0, + 'https://images.example/icon.png', 'https://images.example/gray.png', + 1, 510, 0, 420); + INSERT INTO saved_views (account_id, name, payload, position, created_at) + VALUES ('acct-fixture', 'Fixture View', '{"sort":"name"}', 0, 600); + INSERT INTO hidden_entries (account_id, entry_key, hidden_at) + VALUES ('acct-fixture', 'fixture:1', 610); + INSERT INTO account_library_entries + (account_id, game_id, entry_id, status, collection_ids) + VALUES ('acct-fixture', 42, '1', 'owned', '["collection-1"]'); + INSERT INTO account_collections + (account_id, collection_id, name, default_status, position) + VALUES ('acct-fixture', 'collection-1', 'Fixture Collection', 'owned', 0); + INSERT INTO account_library_reads (account_id, read_at) + VALUES ('acct-fixture', 620); + INSERT INTO sync_summaries (account_id, completed_at, accepted_games, stores, held) + VALUES ('acct-fixture', 700, 1, 1, 0); + "#, + ) + .unwrap(); + } + + struct MainShapedSnapshot { + tables: Vec<(String, Vec, i64, String)>, + history: Vec<(u32, String, i64)>, + } + + fn snapshot_table_data(conn: &Connection) -> MainShapedSnapshot { + let mut history_statement = conn + .prepare("SELECT version, name, applied_at FROM schema_migrations ORDER BY version") + .unwrap(); + let history = history_statement + .query_map([], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?))) + .unwrap() + .map(Result::unwrap) + .collect(); + let mut tables = Vec::new(); + for table in table_names(conn) { + if table == "schema_migrations" { + continue; + } + let columns = table_columns(conn, &table); + let (rows, digest) = table_digest(conn, &table, &columns); + assert!( + rows > 0, + "the fixture has no representative row for {table}" + ); + tables.push((table, columns, rows, digest)); + } + MainShapedSnapshot { tables, history } + } + + fn snapshot_fingerprint(snapshot: &MainShapedSnapshot) -> String { + let mut hasher = Sha256::new(); + for (table, _, rows, digest) in &snapshot.tables { + hasher.update(format!("{table}:{rows}:{digest}\n")); + } + format!("{:x}", hasher.finalize()) + } + fn geometry() -> WindowGeometry { WindowGeometry { x: Some(-40), @@ -571,27 +1159,7 @@ mod tests { let dir = TempDir::new().unwrap(); let store = SqliteSettingsStore::open(&db_path(&dir)).unwrap(); assert_eq!(store.load().unwrap(), Settings::default()); - assert_eq!( - versions(&store.conn()), - vec![ - (1, "initial_settings".to_string()), - (2, "library".to_string()), - (3, "playtime".to_string()), - (4, "drm_free_backups".to_string()), - (5, "game_tools".to_string()), - (6, "store_accounts_and_catalog".to_string()), - (7, "favorites".to_string()), - (8, "ports".to_string()), - (9, "achievements".to_string()), - (10, "library_organization".to_string()), - (11, "game_platforms".to_string()), - (12, "achievement_rarity".to_string()), - (13, "backup_metadata".to_string()), - (14, "local_cover".to_string()), - (15, "app_preferences".to_string()), - (16, "sync_summary".to_string()) - ] - ); + assert_eq!(versions(&store.conn()), migration_history(MIGRATIONS)); } #[test] @@ -611,7 +1179,7 @@ mod tests { let conn = store.conn(); assert_eq!( versions(&conn).last(), - Some(&(16, "sync_summary".to_owned())) + Some(&(26, "plugin_bundle_history".to_owned())) ); let payload: String = conn .query_row( @@ -654,7 +1222,7 @@ mod tests { let conn = store.conn(); assert_eq!( versions(&conn).last(), - Some(&(16, "sync_summary".to_owned())) + Some(&(26, "plugin_bundle_history".to_owned())) ); let kind: String = conn .query_row( @@ -751,7 +1319,7 @@ mod tests { let store = SqliteSettingsStore::open(&path).unwrap(); assert_eq!( versions(&store.conn()).last(), - Some(&(16, "sync_summary".to_owned())) + Some(&(26, "plugin_bundle_history".to_owned())) ); assert_eq!(store.load().unwrap().preferences, AppPreferences::default()); @@ -1007,8 +1575,7 @@ mod tests { window: Some(geometry()), ..Settings::default() }; - SqliteSettingsStore::open(&db_path(&dir)) - .unwrap() + SqliteSettingsStore::open_with_for_test(&db_path(&dir), &MIGRATIONS[..16]) .save(&saved) .unwrap(); @@ -1078,8 +1645,7 @@ mod tests { window: None, ..Settings::default() }; - SqliteSettingsStore::open(&db_path(&dir)) - .unwrap() + SqliteSettingsStore::open_with_for_test(&db_path(&dir), &MIGRATIONS[..16]) .save(&saved) .unwrap(); @@ -1130,61 +1696,171 @@ mod tests { (16, "sync_summary".to_string()) ] ); - let leaked: i64 = conn + let leaked: i64 = conn + .query_row( + "SELECT COUNT(*) FROM sqlite_master WHERE name = 'half_done'", + [], + |r| r.get(0), + ) + .unwrap(); + assert_eq!(leaked, 0, "the partial migration was rolled back"); + assert_eq!(SqliteSettingsStore::new(conn).load().unwrap(), saved); + } + + #[test] + fn mismatched_migration_history_is_rejected_without_changing_the_file() { + let dir = TempDir::new().unwrap(); + let path = db_path(&dir); + drop(open_with(&path, &MIGRATIONS[..3]).unwrap()); + Connection::open(&path) + .unwrap() + .execute( + "UPDATE schema_migrations SET name = 'unexpected_name' WHERE version = 2", + [], + ) + .unwrap(); + let before = std::fs::read(&path).unwrap(); + + assert!(matches!(open(&path), Err(StorageError::Failed(_)))); + assert_eq!(std::fs::read(&path).unwrap(), before); + } + + #[test] + fn integration_branch_migration_history_is_rejected_without_changing_the_file() { + // This is the unpublished history used by the integration branch before reconciliation. + // Several version numbers overlap with main but identify different migrations. + let dir = TempDir::new().unwrap(); + let path = db_path(&dir); + let conn = Connection::open(&path).unwrap(); + conn.execute_batch( + "CREATE TABLE schema_migrations (version INTEGER PRIMARY KEY, name TEXT NOT NULL); + CREATE TABLE integration_user_data (id TEXT PRIMARY KEY, value TEXT NOT NULL); + INSERT INTO integration_user_data VALUES ('sentinel', 'preserve me');", + ) + .unwrap(); + let integration_history = [ + "initial_settings", + "library", + "playtime", + "drm_free_backups", + "game_tools", + "store_accounts_and_catalog", + "favorites", + "ports", + "achievements", + "library_installations", + "library_display_overrides", + "chosen_match_source", + "library_artwork_overrides", + "library_entry_targets", + "library_organization", + "plugin_custom_launch_recipes", + "plugin_runtime_resources", + "library_launch_recipe_selection", + ]; + for (index, name) in integration_history.iter().enumerate() { + conn.execute( + "INSERT INTO schema_migrations (version, name) VALUES (?1, ?2)", + params![index as u32 + 1, name], + ) + .unwrap(); + } + drop(conn); + + let before = std::fs::read(&path).unwrap(); + assert!(matches!(open(&path), Err(StorageError::Failed(_)))); + assert_eq!(std::fs::read(&path).unwrap(), before); + } + + #[test] + fn failed_upgrade_keeps_the_latest_verified_snapshot_with_user_data() { + const V18_BAD: Migration = Migration { + version: 18, + name: "broken_second_upgrade", + sql: "CREATE TABLE half_done (id INTEGER PRIMARY KEY); INSERT INTO missing_table VALUES (1);", + }; + + let dir = TempDir::new().unwrap(); + let path = db_path(&dir); + let saved = Settings { + window: Some(geometry()), + ..Settings::default() + }; + SqliteSettingsStore::open_with_for_test(&path, &MIGRATIONS[..16]) + .save(&saved) + .unwrap(); + + let mut through_v17 = MIGRATIONS[..16].to_vec(); + through_v17.push(V17_OK); + drop(open_with(&path, &through_v17).unwrap()); + + let mut failing_upgrade = through_v17.clone(); + failing_upgrade.push(V18_BAD); + let error = open_with(&path, &failing_upgrade).unwrap_err(); + assert_eq!(error, StorageError::MigrationFailed { version: 18 }); + assert_eq!( + error.to_string(), + "local database migration 18 failed and was rolled back" + ); + + let snapshot_prefix = format!( + "{}.pre-migration-", + path.file_name().unwrap().to_string_lossy() + ); + let snapshots = std::fs::read_dir(dir.path()) + .unwrap() + .map(Result::unwrap) + .map(|entry| entry.path()) + .filter(|candidate| { + candidate + .file_name() + .is_some_and(|name| name.to_string_lossy().starts_with(&snapshot_prefix)) + }) + .collect::>(); + assert_eq!(snapshots.len(), 1, "only the latest snapshot is retained"); + + let snapshot = + Connection::open_with_flags(&snapshots[0], rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY) + .unwrap(); + let integrity: String = snapshot + .query_row("PRAGMA integrity_check", [], |row| row.get(0)) + .unwrap(); + assert_eq!(integrity, "ok"); + assert_eq!(versions(&snapshot), migration_history(&through_v17)); + assert_eq!(SqliteSettingsStore::new(snapshot).load().unwrap(), saved); + + let upgraded = Connection::open(path).unwrap(); + assert_eq!(versions(&upgraded), migration_history(&through_v17)); + let leaked: i64 = upgraded .query_row( "SELECT COUNT(*) FROM sqlite_master WHERE name = 'half_done'", [], - |r| r.get(0), + |row| row.get(0), ) .unwrap(); - assert_eq!(leaked, 0, "the partial migration was rolled back"); - assert_eq!(SqliteSettingsStore::new(conn).load().unwrap(), saved); + assert_eq!(leaked, 0, "the failed migration rolled back"); } #[test] fn newer_schema_is_rejected_and_the_file_is_unchanged() { let dir = TempDir::new().unwrap(); let path = db_path(&dir); - drop( - open_with( - &path, - &[ - MIGRATIONS[0], - MIGRATIONS[1], - MIGRATIONS[2], - MIGRATIONS[3], - MIGRATIONS[4], - MIGRATIONS[5], - MIGRATIONS[6], - MIGRATIONS[7], - MIGRATIONS[8], - MIGRATIONS[9], - MIGRATIONS[10], - MIGRATIONS[11], - MIGRATIONS[12], - MIGRATIONS[13], - MIGRATIONS[14], - MIGRATIONS[15], - V17_OK, - ], - ) - .unwrap(), - ); + let mut future = MIGRATIONS.to_vec(); + future.push(Migration { + version: CURRENT_SCHEMA_VERSION + 1, + ..V17_OK + }); + drop(open_with(&path, &future).unwrap()); let before = std::fs::read(&path).unwrap(); - let err = open(&path).unwrap_err(); // this build only knows schema 16 assert_eq!( - err, + open(&path).unwrap_err(), StorageError::NewerSchema { - found: 17, - supported: 16 + found: CURRENT_SCHEMA_VERSION + 1, + supported: CURRENT_SCHEMA_VERSION, } ); - assert_eq!( - std::fs::read(&path).unwrap(), - before, - "a newer database is not modified" - ); + assert_eq!(std::fs::read(&path).unwrap(), before); } #[test] @@ -1199,7 +1875,7 @@ mod tests { assert_eq!( err, StorageError::NewerSchema { - found: 16, + found: CURRENT_SCHEMA_VERSION, supported: 7 } ); @@ -1229,27 +1905,7 @@ mod tests { let store = SqliteSettingsStore::open(&db_path(&dir)).unwrap(); assert_eq!(store.load().unwrap(), saved); - assert_eq!( - versions(&store.conn()), - vec![ - (1, "initial_settings".to_string()), - (2, "library".to_string()), - (3, "playtime".to_string()), - (4, "drm_free_backups".to_string()), - (5, "game_tools".to_string()), - (6, "store_accounts_and_catalog".to_string()), - (7, "favorites".to_string()), - (8, "ports".to_string()), - (9, "achievements".to_string()), - (10, "library_organization".to_string()), - (11, "game_platforms".to_string()), - (12, "achievement_rarity".to_string()), - (13, "backup_metadata".to_string()), - (14, "local_cover".to_string()), - (15, "app_preferences".to_string()), - (16, "sync_summary".to_string()) - ] - ); + assert_eq!(versions(&store.conn()), migration_history(MIGRATIONS)); for table in [ "library_entries", "provider_scans", @@ -1288,7 +1944,7 @@ mod tests { assert_eq!( err, StorageError::NewerSchema { - found: 16, + found: CURRENT_SCHEMA_VERSION, supported: 1 } ); @@ -1343,27 +1999,7 @@ mod tests { let conn = store.conn(); // Check versions - assert_eq!( - versions(&conn), - vec![ - (1, "initial_settings".to_string()), - (2, "library".to_string()), - (3, "playtime".to_string()), - (4, "drm_free_backups".to_string()), - (5, "game_tools".to_string()), - (6, "store_accounts_and_catalog".to_string()), - (7, "favorites".to_string()), - (8, "ports".to_string()), - (9, "achievements".to_string()), - (10, "library_organization".to_string()), - (11, "game_platforms".to_string()), - (12, "achievement_rarity".to_string()), - (13, "backup_metadata".to_string()), - (14, "local_cover".to_string()), - (15, "app_preferences".to_string()), - (16, "sync_summary".to_string()) - ] - ); + assert_eq!(versions(&conn), migration_history(MIGRATIONS)); // Verify tool tables exist and are empty for table in ["tool_installations", "tool_files", "tool_releases_cache"] { @@ -1480,27 +2116,7 @@ mod tests { let store = SqliteSettingsStore::open(&path).unwrap(); let conn = store.conn(); - assert_eq!( - versions(&conn), - vec![ - (1, "initial_settings".to_string()), - (2, "library".to_string()), - (3, "playtime".to_string()), - (4, "drm_free_backups".to_string()), - (5, "game_tools".to_string()), - (6, "store_accounts_and_catalog".to_string()), - (7, "favorites".to_string()), - (8, "ports".to_string()), - (9, "achievements".to_string()), - (10, "library_organization".to_string()), - (11, "game_platforms".to_string()), - (12, "achievement_rarity".to_string()), - (13, "backup_metadata".to_string()), - (14, "local_cover".to_string()), - (15, "app_preferences".to_string()), - (16, "sync_summary".to_string()) - ] - ); + assert_eq!(versions(&conn), migration_history(MIGRATIONS)); let entry: (String, String, i64, i64, i64, i64) = conn .query_row( @@ -1684,27 +2300,7 @@ mod tests { let store = SqliteSettingsStore::open(&path).unwrap(); let conn = store.conn(); - assert_eq!( - versions(&conn), - vec![ - (1, "initial_settings".to_string()), - (2, "library".to_string()), - (3, "playtime".to_string()), - (4, "drm_free_backups".to_string()), - (5, "game_tools".to_string()), - (6, "store_accounts_and_catalog".to_string()), - (7, "favorites".to_string()), - (8, "ports".to_string()), - (9, "achievements".to_string()), - (10, "library_organization".to_string()), - (11, "game_platforms".to_string()), - (12, "achievement_rarity".to_string()), - (13, "backup_metadata".to_string()), - (14, "local_cover".to_string()), - (15, "app_preferences".to_string()), - (16, "sync_summary".to_string()) - ] - ); + assert_eq!(versions(&conn), migration_history(MIGRATIONS)); // Every table that existed at the favorites schema keeps its row. for table in [ @@ -1949,10 +2545,10 @@ mod tests { let store = SqliteSettingsStore::open(&path).unwrap(); let conn = store.conn(); - assert_eq!(CURRENT_SCHEMA_VERSION, 16); + assert_eq!(CURRENT_SCHEMA_VERSION, 26); assert_eq!( versions(&conn).last(), - Some(&(16, "sync_summary".to_owned())) + Some(&(26, "plugin_bundle_history".to_owned())) ); let steam: (String, String, i64, i64, i64) = conn .query_row( @@ -2052,10 +2648,10 @@ mod tests { let reopened = SqliteSettingsStore::open(&path).unwrap(); let conn = reopened.conn(); - assert_eq!(CURRENT_SCHEMA_VERSION, 16); + assert_eq!(CURRENT_SCHEMA_VERSION, 26); assert_eq!( versions(&conn).last(), - Some(&(16, "sync_summary".to_owned())) + Some(&(26, "plugin_bundle_history".to_owned())) ); assert_eq!( conn.query_row( @@ -2230,10 +2826,10 @@ mod tests { let store = SqliteSettingsStore::open(&path).unwrap(); let conn = store.conn(); - assert_eq!(CURRENT_SCHEMA_VERSION, 16); + assert_eq!(CURRENT_SCHEMA_VERSION, 26); assert_eq!( versions(&conn).last(), - Some(&(16, "sync_summary".to_owned())) + Some(&(26, "plugin_bundle_history".to_owned())) ); // Every table that existed at schema 9 keeps its row. @@ -2435,6 +3031,193 @@ mod tests { .unwrap(); } + #[test] + fn a_populated_main_shaped_database_upgrades_to_the_complete_schema_without_losing_data() { + let dir = TempDir::new().unwrap(); + let path = db_path(&dir); + let before = { + let conn = open_with(&path, &MIGRATIONS[..16]).unwrap(); + assert_eq!(versions(&conn), migration_history(&MIGRATIONS[..16])); + seed_main_shaped_database(&conn); + snapshot_table_data(&conn) + }; + assert_eq!(before.history.len(), 16); + println!( + "main-shaped fixture: {} tables, {} rows, fingerprint {}", + before.tables.len(), + before.tables.iter().map(|(.., rows, _)| rows).sum::(), + snapshot_fingerprint(&before), + ); + + let upgraded = open(&path).unwrap(); + + // The runner appends this build's migrations to main's history without rewriting it. + assert_eq!( + versions(&upgraded), + migration_history(MIGRATIONS), + "the full migration history is recorded in order" + ); + let history_after: Vec<(u32, String, i64)> = upgraded + .prepare("SELECT version, name, applied_at FROM schema_migrations ORDER BY version") + .unwrap() + .query_map([], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?))) + .unwrap() + .map(Result::unwrap) + .collect(); + assert_eq!( + &history_after[..16], + before.history.as_slice(), + "main's recorded versions, names and applied times are untouched" + ); + + // Every table that main shipped still exists with the same rows in the same columns. + let columns_after = table_columns_by_table(&upgraded); + for (table, columns, rows, digest) in &before.tables { + let current_columns = columns_after + .get(table) + .unwrap_or_else(|| panic!("{table} disappeared during the upgrade")); + for column in columns { + assert!( + current_columns.contains(column), + "{table}.{column} disappeared during the upgrade" + ); + } + let (rows_after, digest_after) = table_digest(&upgraded, table, columns); + assert_eq!(rows_after, *rows, "{table} kept its row count"); + assert_eq!(digest_after, *digest, "{table} kept its row data"); + } + + // Tables added by this build start empty and the additive columns use their defaults. + for table in table_names(&upgraded) { + if table == "schema_migrations" || before.tables.iter().any(|(old, ..)| *old == table) { + continue; + } + let (rows, _) = table_digest(&upgraded, &table, &table_columns(&upgraded, &table)); + assert_eq!(rows, 0, "{table} is new in this build and starts empty"); + } + let (source, target): (String, Option) = upgraded + .query_row( + "SELECT source, (SELECT target_json FROM library_entries WHERE key = 'fixture:1') + FROM chosen_matches WHERE account_id = 'acct-fixture'", + [], + |row| Ok((row.get(0)?, row.get(1)?)), + ) + .unwrap(); + assert_eq!(source, "user", "pre-existing choices stay user-made"); + assert_eq!(target, None, "an entry starts without a detected target"); + println!( + "upgraded database: {} tables, history {} entries (1-{}), main tables preserved, new tables empty", + table_names(&upgraded).len(), + versions(&upgraded).len(), + versions(&upgraded).last().unwrap().0, + ); + + // The upgraded database has the same complete schema as a database created now. + let fresh_path = dir.path().join("fresh.sqlite3"); + let fresh = open(&fresh_path).unwrap(); + assert_eq!(schema_rows(&upgraded), schema_rows(&fresh)); + + // The verified pre-migration snapshot was kept beside the upgraded database. + let snapshots = snapshots_for(&dir, &path); + assert_eq!(snapshots.len(), 1, "one verified snapshot is retained"); + let snapshot = + Connection::open_with_flags(&snapshots[0], rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY) + .unwrap(); + let integrity: String = snapshot + .query_row("PRAGMA integrity_check", [], |row| row.get(0)) + .unwrap(); + assert_eq!(integrity, "ok"); + assert_eq!(versions(&snapshot), migration_history(&MIGRATIONS[..16])); + for (table, columns, rows, digest) in &before.tables { + assert_eq!( + table_digest(&snapshot, table, columns), + (*rows, digest.clone()), + "the snapshot preserves {table}" + ); + } + } + + #[test] + fn a_main_shaped_build_refuses_the_upgraded_database_untouched() { + let dir = TempDir::new().unwrap(); + let path = db_path(&dir); + { + let conn = open_with(&path, &MIGRATIONS[..16]).unwrap(); + seed_main_shaped_database(&conn); + } + drop(open(&path).unwrap()); + let before = std::fs::read(&path).unwrap(); + + // Simulates the shipped main build (`origin/main` at `e37ccd1`, schema 16), whose runner + // refuses any database whose highest recorded version is newer than its own list. + let error = open_with(&path, &MIGRATIONS[..16]).unwrap_err(); + assert_eq!( + error, + StorageError::NewerSchema { + found: CURRENT_SCHEMA_VERSION, + supported: 16 + } + ); + println!( + "older build refusal: {error}; sha256 before {:x} after {:x}", + Sha256::digest(&before), + Sha256::digest(std::fs::read(&path).unwrap()), + ); + assert_eq!( + std::fs::read(&path).unwrap(), + before, + "an older build leaves the upgraded database byte-for-byte unchanged" + ); + assert_eq!( + versions(&Connection::open(&path).unwrap()), + migration_history(MIGRATIONS), + "refusal neither truncates nor rewrites the history" + ); + } + + fn table_columns_by_table(conn: &Connection) -> std::collections::HashMap> { + table_names(conn) + .into_iter() + .map(|table| { + let columns = table_columns(conn, &table); + (table, columns) + }) + .collect() + } + + fn schema_rows(conn: &Connection) -> Vec<(String, String, String, String)> { + let mut statement = conn + .prepare( + "SELECT type, name, tbl_name, COALESCE(sql, '') FROM sqlite_master + WHERE name NOT LIKE 'sqlite_%' ORDER BY type, name", + ) + .unwrap(); + statement + .query_map([], |row| { + Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?)) + }) + .unwrap() + .map(Result::unwrap) + .collect() + } + + fn snapshots_for(dir: &TempDir, database: &Path) -> Vec { + let prefix = format!( + "{}.pre-migration-", + database.file_name().unwrap().to_string_lossy() + ); + std::fs::read_dir(dir.path()) + .unwrap() + .map(Result::unwrap) + .map(|entry| entry.path()) + .filter(|candidate| { + candidate + .file_name() + .is_some_and(|name| name.to_string_lossy().starts_with(&prefix)) + }) + .collect() + } + #[test] fn a_populated_schema11_profile_upgrades_to_schema12_with_nullable_rarity() { let dir = TempDir::new().unwrap(); @@ -2464,10 +3247,10 @@ mod tests { let store = SqliteSettingsStore::open(&path).unwrap(); let conn = store.conn(); - assert_eq!(CURRENT_SCHEMA_VERSION, 16); + assert_eq!(CURRENT_SCHEMA_VERSION, 26); assert_eq!( versions(&conn).last(), - Some(&(16, "sync_summary".to_owned())) + Some(&(26, "plugin_bundle_history".to_owned())) ); let (name, rarity): (String, Option) = conn .query_row( @@ -2493,6 +3276,92 @@ mod tests { assert_eq!(rarity, 420); } + #[test] + fn a_populated_schema24_profile_upgrades_to_schema25_with_empty_bundle_tables() { + let dir = TempDir::new().unwrap(); + let path = db_path(&dir); + { + let conn = open_with(&path, &MIGRATIONS[..24]).unwrap(); + conn.execute_batch( + r#" + INSERT INTO settings (key, value) VALUES ('window.width', '1280'); + INSERT INTO library_entries + (key, provider, store_id, name, install_dir, fields_json, installed, + first_seen, last_seen, owned, family_shared) + VALUES ('steam:620', 'steam', '620', 'Portal 2', 'D:/Steam/Portal 2', + '{}', 1, 100, 200, 1, 0); + INSERT INTO plugin_custom_launch_recipes + (owner_key, recipe_id, installation_id, revision, recipe_json) + VALUES ('owner', 'recipe', 'installation', 1, '{"recipe_id":"recipe"}'); + "#, + ) + .unwrap(); + assert_eq!( + versions(&conn).last(), + Some(&(24, "library_launch_recipe_selection".to_owned())) + ); + } + + let store = SqliteSettingsStore::open(&path).unwrap(); + let conn = store.conn(); + assert_eq!(CURRENT_SCHEMA_VERSION, 26); + assert_eq!( + versions(&conn).last(), + Some(&(26, "plugin_bundle_history".to_owned())) + ); + for table in [ + "plugin_bundles", + "plugin_bundle_components", + "plugin_bundle_history", + "plugin_bundle_history_components", + ] { + let (rows, strict): (i64, i64) = conn + .query_row( + &format!("SELECT COUNT(*), (SELECT strict FROM pragma_table_list WHERE name = '{table}') FROM {table}"), + [], + |row| Ok((row.get(0)?, row.get(1)?)), + ) + .unwrap(); + assert_eq!(rows, 0, "{table} starts empty"); + assert_eq!(strict, 1, "{table} is STRICT"); + } + let foreign_key: String = conn + .query_row( + "SELECT \"table\" FROM pragma_foreign_key_list('plugin_bundle_components') + WHERE \"from\" = 'bundle_id'", + [], + |row| row.get(0), + ) + .unwrap(); + assert_eq!(foreign_key, "plugin_bundles"); + + // The rows that existed before the upgrade are untouched. + let width: String = conn + .query_row( + "SELECT value FROM settings WHERE key = 'window.width'", + [], + |row| row.get(0), + ) + .unwrap(); + assert_eq!(width, "1280"); + let entry: String = conn + .query_row( + "SELECT name FROM library_entries WHERE key = 'steam:620'", + [], + |row| row.get(0), + ) + .unwrap(); + assert_eq!(entry, "Portal 2"); + let recipe: String = conn + .query_row( + "SELECT recipe_json FROM plugin_custom_launch_recipes WHERE recipe_id = 'recipe'", + [], + |row| row.get(0), + ) + .unwrap(); + assert_eq!(recipe, "{\"recipe_id\":\"recipe\"}"); + } + #[test] fn database_never_holds_credentials_or_callback_urls() { let dir = TempDir::new().unwrap(); @@ -2532,11 +3401,23 @@ mod tests { "favorites", "games", "hidden_entries", + "library_artwork_overrides", + "library_display_overrides", "library_entries", + "library_installations", + "library_launch_recipe_selection", "local_inferences", "manual_registrations", "playtime_sessions", "playtime_totals", + "plugin_bundle_components", + "plugin_bundle_history", + "plugin_bundle_history_components", + "plugin_bundles", + "plugin_custom_launch_recipes", + "plugin_runtime_catalog_state", + "plugin_runtime_content_bindings", + "plugin_runtime_resources", "port_catalog_snapshot", "port_install_jobs", "port_installations", diff --git a/crates/platform/src/installations.rs b/crates/platform/src/installations.rs index 441782dcb..3eb6b945d 100644 --- a/crates/platform/src/installations.rs +++ b/crates/platform/src/installations.rs @@ -1,17 +1,307 @@ -//! Worker-only executable inspection and direct Windows launch. +//! Worker-only executable inspection and custom launch adapters. +#[cfg(any(windows, target_os = "linux", test))] +use gamenode_core::drm_free::LaunchEnvironmentDelta; use gamenode_core::drm_free::{ - Evidence, InstallationHost, LaunchEnvironment, LocalError, Registration, + CustomLaunchCommand, Evidence, InstallationHost, LaunchEnvironment, LocalError, Registration, }; /// Adds a port's provenance environment to the command that launches it (design D7). /// /// The variables are added to the inherited environment; the launcher's own variables stay. -#[cfg(any(windows, test))] +#[cfg(any(windows, target_os = "linux", test))] fn apply_environment(command: &mut std::process::Command, environment: &LaunchEnvironment) { command.envs(environment); } + +#[cfg(any(windows, target_os = "linux", test))] +fn apply_environment_delta( + command: &mut std::process::Command, + environment: &LaunchEnvironmentDelta, +) -> Result<(), LocalError> { + if !environment.validate() { + return Err(LocalError::InvalidTarget); + } + command.env_clear(); + for (key, value) in std::env::vars_os().filter(|(key, _)| safe_game_environment_key(key)) { + command.env(key, value); + } + command.envs(&environment.set); + for key in &environment.unset { + command.env_remove(key); + } + Ok(()) +} + +#[cfg(any(windows, target_os = "linux", test))] +fn safe_game_environment_key(key: &std::ffi::OsStr) -> bool { + let key = key.to_string_lossy(); + #[cfg(windows)] + { + matches!( + key.to_ascii_uppercase().as_str(), + "PATH" + | "PATHEXT" + | "SYSTEMROOT" + | "WINDIR" + | "TEMP" + | "TMP" + | "USERPROFILE" + | "HOMEDRIVE" + | "HOMEPATH" + | "APPDATA" + | "LOCALAPPDATA" + | "PROGRAMDATA" + | "COMSPEC" + | "NUMBER_OF_PROCESSORS" + | "PROCESSOR_ARCHITECTURE" + | "PROCESSOR_IDENTIFIER" + | "PROCESSOR_LEVEL" + | "PROCESSOR_REVISION" + ) + } + #[cfg(not(windows))] + { + key == "PATH" + || key == "HOME" + || key == "USER" + || key == "LOGNAME" + || key == "LANG" + || key == "DISPLAY" + || key == "WAYLAND_DISPLAY" + || key == "XAUTHORITY" + || key.starts_with("QT_") + || key.starts_with("LC_") + || key.starts_with("XDG_") + || key == "DBUS_SESSION_BUS_ADDRESS" + } +} + +#[cfg(any(windows, target_os = "linux", test))] +fn custom_command( + executable: &str, + arguments: &[String], + working_directory: &str, + environment: &LaunchEnvironmentDelta, +) -> Result { + if executable.is_empty() + || executable.contains('\0') + || working_directory.is_empty() + || working_directory.contains('\0') + || arguments.iter().any(|argument| argument.contains('\0')) + { + return Err(LocalError::InvalidTarget); + } + let mut command = std::process::Command::new(executable); + command.args(arguments).current_dir(working_directory); + apply_environment_delta(&mut command, environment)?; + Ok(command) +} #[derive(Default)] pub struct WindowsInstallations; + +/// Linux executable inspection and direct launch, including explicit wrapper recipes such as +/// Proton. The launch plan is already resolved and reviewed by the host before this adapter runs. +#[derive(Default)] +pub struct LinuxInstallations; + +#[cfg(target_os = "linux")] +fn linux_canonical(path: &str) -> Result { + std::fs::canonicalize(path).map_err(|_| LocalError::InvalidTarget) +} + +#[cfg(target_os = "linux")] +fn linux_identity(path: &std::path::Path) -> Result { + use std::os::unix::{fs::MetadataExt, fs::PermissionsExt}; + let metadata = std::fs::metadata(path).map_err(|_| LocalError::InvalidTarget)?; + if !metadata.is_file() || metadata.permissions().mode() & 0o111 == 0 { + return Err(LocalError::InvalidTarget); + } + Ok(format!( + "linux:{}:{}:{}:{}:{}:{}:{}:{}", + metadata.dev(), + metadata.ino(), + metadata.mode() & 0o7777, + metadata.len(), + metadata.mtime(), + metadata.mtime_nsec(), + metadata.ctime(), + metadata.ctime_nsec(), + )) +} + +#[cfg(target_os = "linux")] +impl LinuxInstallations { + fn spawn_custom(&self, request: &CustomLaunchCommand) -> Result<(), LocalError> { + let executable = linux_canonical(&request.executable)?; + if linux_identity(&executable)? != request.file_identity { + return Err(LocalError::InvalidTarget); + } + let working = linux_canonical(&request.working_directory)?; + if !working.is_dir() { + return Err(LocalError::InvalidTarget); + } + let mut command = custom_command( + &executable.to_string_lossy(), + &request.arguments, + &working.to_string_lossy(), + &request.environment, + )?; + command + .spawn() + .map_err(|error| LocalError::Failed(error.to_string()))?; + Ok(()) + } +} + +impl InstallationHost for LinuxInstallations { + fn inspect(&self, executable: &str) -> Result { + #[cfg(not(target_os = "linux"))] + { + let _ = executable; + Err(LocalError::Unsupported) + } + #[cfg(target_os = "linux")] + { + let path = linux_canonical(executable)?; + let file_identity = linux_identity(&path)?; + let root = path + .parent() + .ok_or(LocalError::InvalidTarget)? + .to_string_lossy() + .into_owned(); + let executable = path.to_string_lossy().into_owned(); + let title = path + .file_stem() + .ok_or(LocalError::InvalidTarget)? + .to_string_lossy() + .into_owned(); + Ok(Registration { + id: crate::random::session_id(), + title, + executable: executable.clone(), + file_identity, + root: root.clone(), + working_directory: root, + arguments: vec![], + gameplay: vec![executable], + launchers: vec![], + revision: 1, + removed: false, + rediscovery_allowed: false, + transferred_from: None, + custom_cover: None, + available: true, + }) + } + } + + fn validate_registration( + &self, + registration: &Registration, + ) -> Result { + #[cfg(not(target_os = "linux"))] + { + let _ = registration; + Err(LocalError::Unsupported) + } + #[cfg(target_os = "linux")] + { + let executable = linux_canonical(®istration.executable)?; + let root = linux_canonical(®istration.root)?; + let working = linux_canonical(®istration.working_directory)?; + if registration.removed + || !root.is_dir() + || !working.is_dir() + || !executable.starts_with(&root) + || linux_identity(&executable)? != registration.file_identity + { + return Err(LocalError::InvalidTarget); + } + let mut result = registration.clone(); + result.executable = executable.to_string_lossy().into_owned(); + result.root = root.to_string_lossy().into_owned(); + result.working_directory = working.to_string_lossy().into_owned(); + Ok(result) + } + } + + fn launch(&self, registration: &Registration) -> Result<(), LocalError> { + #[cfg(not(target_os = "linux"))] + { + let _ = registration; + Err(LocalError::Unsupported) + } + #[cfg(target_os = "linux")] + { + let registration = self.validate_registration(registration)?; + let mut command = std::process::Command::new(®istration.executable); + command + .args(®istration.arguments) + .current_dir(®istration.working_directory); + command + .spawn() + .map_err(|error| LocalError::Failed(error.to_string()))?; + Ok(()) + } + } + + fn launch_with_environment( + &self, + registration: &Registration, + environment: &LaunchEnvironment, + ) -> Result<(), LocalError> { + #[cfg(not(target_os = "linux"))] + { + let _ = (registration, environment); + Err(LocalError::Unsupported) + } + #[cfg(target_os = "linux")] + { + let registration = self.validate_registration(registration)?; + let mut command = std::process::Command::new(®istration.executable); + command + .args(®istration.arguments) + .current_dir(®istration.working_directory); + apply_environment(&mut command, environment); + command + .spawn() + .map_err(|error| LocalError::Failed(error.to_string()))?; + Ok(()) + } + } + + fn launch_custom(&self, request: &CustomLaunchCommand) -> Result<(), LocalError> { + #[cfg(not(target_os = "linux"))] + { + let _ = request; + Err(LocalError::Unsupported) + } + #[cfg(target_os = "linux")] + { + self.spawn_custom(request) + } + } + + fn evidence(&self, registration: &Registration) -> Result, LocalError> { + #[cfg(not(target_os = "linux"))] + { + let _ = registration; + Err(LocalError::Unsupported) + } + #[cfg(target_os = "linux")] + { + Ok(vec![Evidence { + kind: gamenode_core::drm_free::EvidenceKind::Executable, + value: std::path::Path::new(®istration.executable) + .file_name() + .unwrap_or_default() + .to_string_lossy() + .into_owned(), + strong: false, + }]) + } + } +} #[cfg(windows)] pub(crate) fn canonical(path: &str) -> Result { std::fs::canonicalize(path) @@ -131,6 +421,30 @@ impl WindowsInstallations { .map_err(|e| LocalError::Failed(e.to_string()))?; Ok(()) } + + /// Starts a fully resolved custom executable after repeating identity checks on the worker. + #[cfg(windows)] + fn spawn_custom(&self, request: &CustomLaunchCommand) -> Result<(), LocalError> { + let path = canonical(&request.executable)?; + validate(&path)?; + if identity(&path)? != request.file_identity { + return Err(LocalError::InvalidTarget); + } + let working = canonical(&request.working_directory)?; + if !working.is_dir() { + return Err(LocalError::InvalidTarget); + } + let mut command = custom_command( + &path.to_string_lossy(), + &request.arguments, + &working.to_string_lossy(), + &request.environment, + )?; + command + .spawn() + .map_err(|error| LocalError::Failed(error.to_string()))?; + Ok(()) + } } impl InstallationHost for WindowsInstallations { @@ -278,6 +592,17 @@ impl InstallationHost for WindowsInstallations { self.spawn(registration, environment) } } + fn launch_custom(&self, request: &CustomLaunchCommand) -> Result<(), LocalError> { + #[cfg(not(windows))] + { + let _ = request; + Err(LocalError::Unsupported) + } + #[cfg(windows)] + { + self.spawn_custom(request) + } + } fn evidence(&self, registration: &Registration) -> Result, LocalError> { #[cfg(not(windows))] { @@ -505,6 +830,100 @@ pub fn pick_save_location(folder: bool) -> Result, LocalError> { pick_folder(None) } +#[cfg(test)] +mod custom_launch_tests { + use super::*; + + #[test] + fn spawned_fixture_receives_literal_arguments_cwd_and_environment_delta() { + let directory = tempfile::tempdir().unwrap(); + let interpreter = std::process::Command::new("python3") + .args(["-c", "import sys; print(sys.executable)"]) + .output() + .expect("Python is available to the repository tooling"); + assert!(interpreter.status.success()); + let interpreter = String::from_utf8(interpreter.stdout).unwrap(); + let interpreter = interpreter.trim(); + let script = "import json,os,sys; print(json.dumps({'executable':sys.executable, 'argv':sys.argv[1:], 'cwd':os.getcwd(), 'set':os.environ.get('GAMENODE_TEST_SET'), 'unset':'PATH' not in os.environ}))"; + let arguments = vec![ + "-c".into(), + script.into(), + "space and & literal".into(), + "$(not-a-shell)".into(), + ]; + let environment = LaunchEnvironmentDelta { + set: LaunchEnvironment::from([("GAMENODE_TEST_SET".into(), "one value".into())]), + unset: ["PATH".into()].into(), + }; + let mut command = custom_command( + interpreter, + &arguments, + &directory.path().to_string_lossy(), + &environment, + ) + .unwrap(); + // Process creation and waiting happen on a worker, matching the production contract. + let output = std::thread::spawn(move || command.output()) + .join() + .expect("launch worker should finish") + .expect("fixture process should start without a shell"); + + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let result: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(result["executable"], interpreter); + assert_eq!( + result["argv"], + serde_json::json!(["space and & literal", "$(not-a-shell)"]) + ); + assert_eq!(result["cwd"], directory.path().to_string_lossy().as_ref()); + assert_eq!(result["set"], "one value"); + assert_eq!(result["unset"], true); + } + + #[test] + fn invalid_environment_deltas_are_rejected_before_process_creation() { + let invalid_name = LaunchEnvironmentDelta { + set: LaunchEnvironment::from([("BAD=KEY".into(), "value".into())]), + unset: Default::default(), + }; + assert!(!invalid_name.validate()); + assert!(custom_command("python3", &[], ".", &invalid_name).is_err()); + + let credential_name = LaunchEnvironmentDelta { + set: LaunchEnvironment::from([("STEAM_SESSION".into(), "value".into())]), + unset: Default::default(), + }; + assert!(!credential_name.validate()); + } + + #[test] + fn inherited_custom_launch_environment_is_restricted_to_host_allowlisted_keys() { + assert!(safe_game_environment_key(std::ffi::OsStr::new("PATH"))); + #[cfg(not(windows))] + assert!(safe_game_environment_key(std::ffi::OsStr::new("HOME"))); + #[cfg(not(windows))] + { + assert!(safe_game_environment_key(std::ffi::OsStr::new( + "XAUTHORITY" + ))); + assert!(safe_game_environment_key(std::ffi::OsStr::new( + "QT_QPA_PLATFORM" + ))); + } + assert!(!safe_game_environment_key(std::ffi::OsStr::new( + "STEAM_SESSION" + ))); + assert!(!safe_game_environment_key(std::ffi::OsStr::new( + "TAURI_PLUGIN_TOKEN" + ))); + assert!(!safe_game_environment_key(std::ffi::OsStr::new("RUST_LOG"))); + } +} + fn pick_folder(initial: Option<&str>) -> Result, LocalError> { #[cfg(not(windows))] { @@ -593,7 +1012,9 @@ mod tests { #[test] #[cfg(not(windows))] fn unsupported_on_linux() { - use gamenode_core::drm_free::{InstallationHost, Registration}; + use gamenode_core::drm_free::{ + CustomLaunchCommand, InstallationHost, LaunchEnvironmentDelta, Registration, + }; let host = super::WindowsInstallations; let registration = Registration { id: "test".into(), @@ -631,6 +1052,16 @@ mod tests { ), Err(super::LocalError::Unsupported) ); + assert_eq!( + host.launch_custom(&CustomLaunchCommand { + executable: "game.exe".into(), + file_identity: "1:2:3".into(), + arguments: vec!["--profile".into()], + working_directory: "/game".into(), + environment: LaunchEnvironmentDelta::default(), + }), + Err(super::LocalError::Unsupported) + ); assert_eq!( host.evidence(®istration), Err(super::LocalError::Unsupported) @@ -842,3 +1273,191 @@ mod windows_tests { ); } } + +#[cfg(all(test, target_os = "linux"))] +mod linux_tests { + use super::*; + use gamenode_core::drm_free::LaunchEnvironmentDelta; + use std::{collections::BTreeSet, os::unix::fs::PermissionsExt}; + + fn executable(directory: &std::path::Path, name: &str) -> std::path::PathBuf { + let path = directory.join(name); + std::fs::write( + &path, + "#!/bin/sh\nprintf '%s\\n' \"$PWD\" \"$@\" \"$PLAN_MARKER\" > \"$CAPTURE\"\n", + ) + .unwrap(); + let mut permissions = std::fs::metadata(&path).unwrap().permissions(); + permissions.set_mode(0o755); + std::fs::set_permissions(&path, permissions).unwrap(); + path + } + + fn wait_for_capture(path: &std::path::Path) -> String { + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(3); + loop { + if let Ok(result) = std::fs::read_to_string(path) { + return result; + } + assert!( + std::time::Instant::now() < deadline, + "launch fixture timed out" + ); + std::thread::sleep(std::time::Duration::from_millis(10)); + } + } + + #[test] + fn direct_linux_launch_keeps_approved_identity_and_reviewed_fields() { + let directory = tempfile::tempdir().unwrap(); + let working = directory.path().join("game folder"); + std::fs::create_dir(&working).unwrap(); + let game = executable(&working, "game"); + let capture = directory.path().join("direct.out"); + let host = LinuxInstallations; + let approved = host.inspect(game.to_str().unwrap()).unwrap(); + let request = CustomLaunchCommand { + executable: approved.executable.clone(), + file_identity: approved.file_identity.clone(), + arguments: vec!["--profile".into(), "two words".into(), "semi;colon".into()], + working_directory: working.to_string_lossy().into_owned(), + environment: LaunchEnvironmentDelta { + set: [ + ("CAPTURE".into(), capture.to_string_lossy().into_owned()), + ("PLAN_MARKER".into(), "reviewed".into()), + ] + .into(), + unset: BTreeSet::new(), + }, + }; + host.launch_custom(&request).unwrap(); + assert_eq!( + wait_for_capture(&capture), + format!( + "{}\n--profile\ntwo words\nsemi;colon\nreviewed\n", + working.display() + ) + ); + + let mut stale = request; + stale.file_identity.push_str(":stale"); + assert_eq!(host.launch_custom(&stale), Err(LocalError::InvalidTarget)); + } + + #[test] + fn proton_style_wrapper_receives_the_exact_reviewed_game_arguments_and_context() { + let directory = tempfile::tempdir().unwrap(); + let working = directory.path().join("prefix"); + std::fs::create_dir(&working).unwrap(); + let wrapper = executable(&working, "approved-proton-wrapper"); + let capture = directory.path().join("wrapper.out"); + let host = LinuxInstallations; + let approved = host.inspect(wrapper.to_str().unwrap()).unwrap(); + let request = CustomLaunchCommand { + executable: approved.executable, + file_identity: approved.file_identity, + arguments: vec![ + "run".into(), + "--prefix".into(), + "/approved/prefix with spaces".into(), + "--".into(), + "Z:/Games/Example/game.exe".into(), + "--name".into(), + "value with spaces".into(), + ], + working_directory: working.to_string_lossy().into_owned(), + environment: LaunchEnvironmentDelta { + set: [ + ("CAPTURE".into(), capture.to_string_lossy().into_owned()), + ("PLAN_MARKER".into(), "proton-reviewed".into()), + ] + .into(), + unset: BTreeSet::new(), + }, + }; + host.launch_custom(&request).unwrap(); + assert_eq!( + wait_for_capture(&capture), + format!( + "{}\nrun\n--prefix\n/approved/prefix with spaces\n--\nZ:/Games/Example/game.exe\n--name\nvalue with spaces\nproton-reviewed\n", + working.display() + ) + ); + } + + #[test] + fn linux_custom_launch_rejects_non_executable_and_missing_working_directory() { + let directory = tempfile::tempdir().unwrap(); + let non_executable = directory.path().join("not-executable"); + std::fs::write(&non_executable, "data").unwrap(); + assert_eq!( + LinuxInstallations.inspect(non_executable.to_str().unwrap()), + Err(LocalError::InvalidTarget) + ); + + let game = executable(directory.path(), "game"); + let approved = LinuxInstallations.inspect(game.to_str().unwrap()).unwrap(); + let request = CustomLaunchCommand { + executable: approved.executable, + file_identity: approved.file_identity, + arguments: vec![], + working_directory: directory + .path() + .join("missing") + .to_string_lossy() + .into_owned(), + environment: LaunchEnvironmentDelta::default(), + }; + assert_eq!( + LinuxInstallations.launch_custom(&request), + Err(LocalError::InvalidTarget) + ); + } + + #[test] + fn missing_wrapper_and_unsupported_environment_fields_fail_before_spawn() { + let directory = tempfile::tempdir().unwrap(); + let game = executable(directory.path(), "game"); + let approved = LinuxInstallations.inspect(game.to_str().unwrap()).unwrap(); + let missing_output = directory.path().join("should-not-exist.out"); + let request = CustomLaunchCommand { + executable: directory + .path() + .join("removed-wrapper") + .to_string_lossy() + .into_owned(), + file_identity: approved.file_identity.clone(), + arguments: vec!["run".into()], + working_directory: directory.path().to_string_lossy().into_owned(), + environment: LaunchEnvironmentDelta { + set: [( + "CAPTURE".into(), + missing_output.to_string_lossy().into_owned(), + )] + .into(), + unset: BTreeSet::new(), + }, + }; + assert_eq!( + LinuxInstallations.launch_custom(&request), + Err(LocalError::InvalidTarget) + ); + assert!(!missing_output.exists()); + + let unsupported_environment = CustomLaunchCommand { + executable: approved.executable, + file_identity: approved.file_identity, + arguments: vec![], + working_directory: directory.path().to_string_lossy().into_owned(), + environment: LaunchEnvironmentDelta { + set: [("STEAM_SESSION".into(), "must-not-leak".into())].into(), + unset: BTreeSet::new(), + }, + }; + assert_eq!( + LinuxInstallations.launch_custom(&unsupported_environment), + Err(LocalError::InvalidTarget) + ); + assert!(!missing_output.exists()); + } +} diff --git a/crates/platform/src/lib.rs b/crates/platform/src/lib.rs index a17cb1fe5..666bfffa6 100644 --- a/crates/platform/src/lib.rs +++ b/crates/platform/src/lib.rs @@ -22,10 +22,25 @@ pub mod local_game_db; pub mod manifest_cache; pub mod paths; pub mod playtime_db; +pub mod plugin_artwork; +pub mod plugin_bundle_db; +pub mod plugin_bundles; +pub mod plugin_environment; +pub mod plugin_files; +pub mod plugin_locations; +pub mod plugin_network; +pub mod plugin_packages; +pub mod plugin_persistence; +pub mod plugin_registry; +pub mod plugin_shared_data; +pub mod plugin_storage; +pub mod plugin_telemetry; +pub mod plugin_updates; pub mod ports; pub mod ports_db; pub mod processes; pub mod random; +pub mod sealed; pub mod storage; pub mod system; pub mod tools; @@ -34,3 +49,5 @@ pub mod uri; #[cfg(windows)] pub mod autostart; + +pub mod volume; diff --git a/crates/platform/src/library_db.rs b/crates/platform/src/library_db.rs index 8767e5682..cec383737 100644 --- a/crates/platform/src/library_db.rs +++ b/crates/platform/src/library_db.rs @@ -8,10 +8,12 @@ use std::sync::{Arc, Mutex}; use gamenode_core::game_api::{AccountEntry, Collection}; use gamenode_core::library::{ - AccountLibrary, AutoMatch, CatalogError, CatalogRecord, CatalogUpdate, ChosenMatch, - EntryStatus, FavoriteRecord, GameRecord, LastAccount, LibraryCache, LibraryLayout, - LibraryStore, ProviderScanState, SavedView, SavedViewPayload, StoreAccount, StoredEntry, - entry_key, + AccountLibrary, ArtworkOverride, ArtworkWrite, AutoMatch, CatalogError, CatalogRecord, + CatalogUpdate, ChoiceSource, ChosenMatch, DisplayOverride, DisplayWrite, EntryStatus, + FavoriteRecord, GameRecord, LastAccount, LaunchRecipeSelection, LaunchRecipeSelectionWrite, + LibraryCache, LibraryLayout, LibraryStore, ProviderScanState, RuntimeAvailabilityEntry, + RuntimeContentBinding, RuntimeMutation, RuntimeResource, SavedView, SavedViewPayload, + StoreAccount, StoredEntry, entry_key, }; use gamenode_core::ports::StorageError; use gamenode_core::provider::Record; @@ -38,6 +40,27 @@ fn game_id(raw: i64) -> Option { u64::try_from(raw).ok() } +fn bump_runtime_catalog_revision( + tx: &rusqlite::Transaction<'_>, + owner_key: &str, +) -> Result { + tx.execute( + "INSERT INTO plugin_runtime_catalog_state (owner_key, catalog_revision) + VALUES (?1, 1) + ON CONFLICT(owner_key) DO UPDATE SET + catalog_revision = plugin_runtime_catalog_state.catalog_revision + 1", + [owner_key], + ) + .map_err(failed)?; + tx.query_row( + "SELECT catalog_revision FROM plugin_runtime_catalog_state WHERE owner_key = ?1", + [owner_key], + |row| row.get::<_, i64>(0), + ) + .map_err(failed) + .and_then(|revision| u64::try_from(revision).map_err(failed)) +} + impl SqliteLibraryStore { pub(crate) fn new(conn: Arc>) -> Self { Self { conn } @@ -100,7 +123,7 @@ fn read_catalog_error(provider: &str, column: &str, value: Option) -> Op fn load_entries(conn: &Connection) -> rusqlite::Result> { let mut stmt = conn.prepare( "SELECT key, provider, store_id, name, install_dir, fields_json, installed, owned, - family_shared, first_seen, last_seen + family_shared, first_seen, last_seen, target_json FROM library_entries ORDER BY key", )?; let rows = stmt.query_map([], |row| { @@ -120,6 +143,7 @@ fn load_entries(conn: &Connection) -> rusqlite::Result> { install_dir: row.get(4)?, fields, installed: row.get::<_, i64>(6)? != 0, + target: read_target(row.get::<_, Option>(11)?), first_seen: row.get(9)?, last_seen: row.get(10)?, }) @@ -127,6 +151,19 @@ fn load_entries(conn: &Connection) -> rusqlite::Result> { rows.collect() } +/// A stored detected target, or `None` when the entry has none. An unreadable value is dropped +/// with a warning: the entry stays usable and the next scan registers the target again. +fn read_target(value: Option) -> Option { + let value = value?; + match serde_json::from_str(&value) { + Ok(target) => Some(target), + Err(error) => { + tracing::warn!(%error, "ignored an unreadable detected target"); + None + } + } +} + /// Which catalog fact set a phase covers. The SQL columns keep their historical /// `family_shared` / `family_error` / `last_family_at` names; the values are provider-neutral. #[derive(Clone, Copy)] @@ -512,7 +549,7 @@ impl LibraryStore for SqliteLibraryStore { None => Vec::new(), Some(account) => conn .prepare( - "SELECT entry_key, game_id, chosen_at FROM chosen_matches + "SELECT entry_key, game_id, chosen_at, source FROM chosen_matches WHERE account_id = ?1 ORDER BY entry_key", ) .map_err(failed)? @@ -521,6 +558,8 @@ impl LibraryStore for SqliteLibraryStore { entry_key: row.get(0)?, game_id: row.get::<_, Option>(1)?.and_then(game_id), chosen_at: row.get(2)?, + // The column is constrained to the known values. + source: ChoiceSource::parse(&row.get::<_, String>(3)?).unwrap_or_default(), }) }) .map_err(failed)? @@ -578,8 +617,26 @@ impl LibraryStore for SqliteLibraryStore { }) .unwrap_or_default(); - // Organization and the account library are per account. Signing out (no account) keeps - // the rows for that account's next sign-in but exposes nothing. + let display_overrides = conn + .prepare("SELECT entry_key, display_name, revision FROM library_display_overrides ORDER BY entry_key") + .map_err(failed)? + .query_map([], |row| Ok((row.get::<_, String>(0)?, row.get::<_, Option>(1)?, row.get::<_, i64>(2)?))) + .map_err(failed)? + .collect::, _>>() + .map_err(failed)? + .into_iter() + .filter_map(|(entry_key, display_name, revision)| Some(DisplayOverride { entry_key, display_name, revision: u64::try_from(revision).ok()? })) + .collect(); + let artwork_overrides = conn + .prepare("SELECT entry_key, file, revision FROM library_artwork_overrides ORDER BY entry_key") + .map_err(failed)? + .query_map([], |row| Ok((row.get::<_, String>(0)?, row.get::<_, Option>(1)?, row.get::<_, i64>(2)?))) + .map_err(failed)? + .collect::, _>>() + .map_err(failed)? + .into_iter() + .filter_map(|(entry_key, file, revision)| Some(ArtworkOverride { entry_key, file, revision: u64::try_from(revision).ok()? })) + .collect(); let (saved_views, hidden, account_library) = match account_id { None => (Vec::new(), Vec::new(), None), Some(account) => ( @@ -597,15 +654,44 @@ impl LibraryStore for SqliteLibraryStore { favorites, games, excluded, + display_overrides, + artwork_overrides, saved_views, hidden, account_library, }) } - fn save_scan(&self, provider: &str, records: &[Record], now: i64) -> Result<(), StorageError> { + fn save_scan( + &self, + provider: &str, + records: &[Record], + targets: &BTreeMap, + now: i64, + ) -> Result<(), StorageError> { let mut conn = self.conn(); let tx = conn.transaction().map_err(failed)?; + // Targets the scan does not report stay stored but unavailable, so a later scan can offer + // repair and an unavailable target can never launch. + let existing = { + let mut stmt = tx + .prepare( + "SELECT key, target_json FROM library_entries + WHERE provider = ?1 AND target_json IS NOT NULL", + ) + .map_err(failed)?; + let rows = stmt + .query_map([provider], |row| { + Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?)) + }) + .map_err(failed)?; + rows.collect::>>().map_err(failed)? + }; + let reported: BTreeSet = records + .iter() + .filter(|record| targets.contains_key(&record.id)) + .map(|record| entry_key(provider, &record.id)) + .collect(); tx.execute( "UPDATE library_entries SET installed = 0 WHERE provider = ?1", [provider], @@ -615,27 +701,77 @@ impl LibraryStore for SqliteLibraryStore { let mut upsert = tx .prepare( "INSERT INTO library_entries - (key, provider, store_id, name, install_dir, fields_json, installed, first_seen, last_seen) - VALUES (?1, ?2, ?3, ?4, ?5, ?6, 1, ?7, ?7) + (key, provider, store_id, name, install_dir, fields_json, installed, first_seen, last_seen, target_json) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, 1, ?7, ?7, ?8) ON CONFLICT(key) DO UPDATE SET name = excluded.name, install_dir = excluded.install_dir, fields_json = excluded.fields_json, installed = 1, - last_seen = excluded.last_seen", + last_seen = excluded.last_seen, + target_json = excluded.target_json", ) .map_err(failed)?; + let existing_targets: BTreeMap<&str, &str> = existing + .iter() + .map(|(key, json)| (key.as_str(), json.as_str())) + .collect(); for record in records { let fields = serde_json::to_string(&record.fields).map_err(failed)?; + let key = entry_key(provider, &record.id); + let prior = existing_targets + .get(key.as_str()) + .and_then(|json| serde_json::from_str(json).ok()); + let target = match targets.get(&record.id) { + Some(spec) => Some(gamenode_core::library::DetectedTarget::reported( + prior.as_ref(), + spec.clone(), + now, + )), + None => prior + .as_ref() + .map(|target| gamenode_core::library::DetectedTarget::missing(target, now)), + }; + let target_json = target + .as_ref() + .map(serde_json::to_string) + .transpose() + .map_err(failed)?; upsert .execute(params![ - entry_key(provider, &record.id), + key, provider, record.id, record.name, record.install_dir, fields, - now + now, + target_json + ]) + .map_err(failed)?; + } + } + { + let mut clear = tx + .prepare( + "UPDATE library_entries SET target_json = ?1 + WHERE key = ?2 AND target_json IS NOT NULL", + ) + .map_err(failed)?; + for (key, json) in &existing { + if reported.contains(key) { + continue; + } + let Ok(target) = + serde_json::from_str::(json) + else { + continue; + }; + let missing = gamenode_core::library::DetectedTarget::missing(&target, now); + clear + .execute(params![ + serde_json::to_string(&missing).map_err(failed)?, + key ]) .map_err(failed)?; } @@ -649,6 +785,956 @@ impl LibraryStore for SqliteLibraryStore { tx.commit().map_err(failed) } + fn save_target_review( + &self, + entry_key: &str, + expected_revision: u64, + replacement: &gamenode_core::library::DetectedTarget, + ) -> Result { + use gamenode_core::library::TargetApproval; + let mut conn = self.conn(); + let tx = conn.transaction().map_err(failed)?; + let stored: Option> = tx + .query_row( + "SELECT target_json FROM library_entries WHERE key = ?1", + [entry_key], + |row| row.get(0), + ) + .optional() + .map_err(failed)?; + let Some(Some(json)) = stored else { + return Ok(TargetApproval::Missing); + }; + let Ok(target) = serde_json::from_str::(&json) + else { + return Ok(TargetApproval::Missing); + }; + if target.revision != expected_revision { + return Ok(TargetApproval::Conflict { + current: target.revision, + }); + } + if replacement.revision < target.revision + || replacement.revision > target.revision.saturating_add(1) + || (replacement.spec != target.spec && replacement.revision == target.revision) + || !replacement.spec.validate_shape() + { + return Ok(TargetApproval::Conflict { + current: target.revision, + }); + } + tx.execute( + "UPDATE library_entries SET target_json = ?1 WHERE key = ?2", + params![ + serde_json::to_string(replacement).map_err(failed)?, + entry_key + ], + ) + .map_err(failed)?; + tx.commit().map_err(failed)?; + Ok(TargetApproval::Applied { + revision: replacement.revision, + }) + } + + fn custom_launch_recipe( + &self, + owner_key: &str, + recipe_id: &str, + ) -> Result, StorageError> { + let conn = self.conn(); + let json: Option = conn + .query_row( + "SELECT recipe_json FROM plugin_custom_launch_recipes + WHERE owner_key = ?1 AND recipe_id = ?2", + params![owner_key, recipe_id], + |row| row.get(0), + ) + .optional() + .map_err(failed)?; + json.map(|json| serde_json::from_str(&json).map_err(failed)) + .transpose() + } + + fn save_custom_launch_recipe( + &self, + owner_key: &str, + recipe: &gamenode_core::library::CustomLaunchRecipe, + ) -> Result { + use gamenode_core::library::CustomLaunchMutation; + if owner_key.is_empty() || !recipe.validate() { + return Err(failed("invalid custom launch recipe")); + } + let mut conn = self.conn(); + let tx = conn.transaction().map_err(failed)?; + let current: Option = tx + .query_row( + "SELECT revision FROM plugin_custom_launch_recipes + WHERE owner_key = ?1 AND recipe_id = ?2", + params![owner_key, recipe.recipe_id], + |row| row.get::<_, i64>(0).map(|value| value as u64), + ) + .optional() + .map_err(failed)?; + let expected = match current { + Some(revision) => revision + .checked_add(1) + .ok_or_else(|| failed("custom launch recipe revision is exhausted"))?, + None => 1, + }; + if recipe.revision != expected { + return Ok(match current { + Some(current) => CustomLaunchMutation::Conflict { current }, + None => CustomLaunchMutation::Conflict { current: 0 }, + }); + } + tx.execute( + "INSERT INTO plugin_custom_launch_recipes + (owner_key, recipe_id, installation_id, revision, recipe_json) + VALUES (?1, ?2, ?3, ?4, ?5) + ON CONFLICT(owner_key, recipe_id) DO UPDATE SET + installation_id = excluded.installation_id, + revision = excluded.revision, + recipe_json = excluded.recipe_json", + params![ + owner_key, + recipe.recipe_id, + recipe.installation_id, + i64::try_from(recipe.revision).map_err(failed)?, + serde_json::to_string(recipe).map_err(failed)?, + ], + ) + .map_err(failed)?; + tx.commit().map_err(failed)?; + Ok(CustomLaunchMutation::Applied { + revision: recipe.revision, + }) + } + + fn remove_custom_launch_recipe( + &self, + owner_key: &str, + recipe_id: &str, + expected_revision: u64, + ) -> Result { + use gamenode_core::library::CustomLaunchMutation; + let mut conn = self.conn(); + let tx = conn.transaction().map_err(failed)?; + let current: Option = tx + .query_row( + "SELECT revision FROM plugin_custom_launch_recipes + WHERE owner_key = ?1 AND recipe_id = ?2", + params![owner_key, recipe_id], + |row| row.get::<_, i64>(0).map(|value| value as u64), + ) + .optional() + .map_err(failed)?; + let Some(current) = current else { + return Ok(CustomLaunchMutation::Missing); + }; + if current != expected_revision { + return Ok(CustomLaunchMutation::Conflict { current }); + } + tx.execute( + "DELETE FROM plugin_custom_launch_recipes + WHERE owner_key = ?1 AND recipe_id = ?2 AND revision = ?3", + params![ + owner_key, + recipe_id, + i64::try_from(expected_revision).map_err(failed)? + ], + ) + .map_err(failed)?; + tx.commit().map_err(failed)?; + Ok(CustomLaunchMutation::Applied { + revision: expected_revision, + }) + } + + fn custom_launch_recipes( + &self, + owner_key: &str, + game_id: u64, + ) -> Result, StorageError> { + let conn = self.conn(); + let mut statement = conn + .prepare( + "SELECT recipe_json FROM plugin_custom_launch_recipes + WHERE owner_key = ?1 ORDER BY recipe_id", + ) + .map_err(failed)?; + let rows = statement + .query_map([owner_key], |row| row.get::<_, String>(0)) + .map_err(failed)?; + rows.map(|row| { + let json = row.map_err(failed)?; + let recipe: gamenode_core::library::CustomLaunchRecipe = + serde_json::from_str(&json).map_err(failed)?; + Ok((recipe.game_id == game_id).then_some(recipe)) + }) + .collect::, StorageError>>() + .map(|recipes| recipes.into_iter().flatten().collect()) + } + + fn launch_recipe_selection( + &self, + entry_key: &str, + ) -> Result, StorageError> { + self.conn() + .query_row( + "SELECT entry_key, owner_key, plugin_id, publisher_fingerprint, recipe_id, + recipe_revision, base_target_revision, approved_plan_fingerprint + FROM library_launch_recipe_selection WHERE entry_key = ?1", + [entry_key], + |row| { + Ok(LaunchRecipeSelection { + entry_key: row.get(0)?, + owner_key: row.get(1)?, + plugin_id: row.get(2)?, + publisher_fingerprint: row.get(3)?, + recipe_id: row.get(4)?, + recipe_revision: row.get::<_, i64>(5)? as u64, + base_target_revision: row.get::<_, i64>(6)? as u64, + approved_plan_fingerprint: row.get(7)?, + }) + }, + ) + .optional() + .map_err(failed) + } + + fn save_launch_recipe_selection( + &self, + selection: &LaunchRecipeSelection, + expected_target_revision: u64, + ) -> Result { + let mut conn = self.conn(); + let tx = conn.transaction().map_err(failed)?; + let entry: Option<(String, Option)> = tx + .query_row( + "SELECT li.installation_id, le.target_json + FROM library_installations li + JOIN library_entries le ON le.key = li.entry_key + WHERE li.entry_key = ?1", + [&selection.entry_key], + |row| Ok((row.get(0)?, row.get(1)?)), + ) + .optional() + .map_err(failed)?; + let Some((installation_id, target_json)) = entry else { + return Ok(LaunchRecipeSelectionWrite::RecipeMissing); + }; + // A ROM store reports no detected target. Revision zero is a valid selection there; a + // runtime recipe is the launch. A provider with a target still needs that exact revision. + let target_revision = match target_json { + Some(target_json) => { + let target: gamenode_core::library::DetectedTarget = + serde_json::from_str(&target_json).map_err(failed)?; + target.revision + } + None if expected_target_revision == 0 => 0, + None => return Ok(LaunchRecipeSelectionWrite::Conflict), + }; + if target_revision != expected_target_revision + || selection.base_target_revision != expected_target_revision + || selection.entry_key.is_empty() + || selection.owner_key.is_empty() + || selection.plugin_id.is_empty() + || selection.publisher_fingerprint.is_empty() + || selection.recipe_id.is_empty() + || selection.recipe_revision == 0 + { + return Ok(LaunchRecipeSelectionWrite::Conflict); + } + let recipe_json: Option = tx + .query_row( + "SELECT recipe_json FROM plugin_custom_launch_recipes + WHERE owner_key = ?1 AND recipe_id = ?2 AND installation_id = ?3 + AND revision = ?4", + params![ + selection.owner_key, + selection.recipe_id, + installation_id, + selection.recipe_revision as i64, + ], + |row| row.get(0), + ) + .optional() + .map_err(failed)?; + let Some(recipe_json) = recipe_json else { + return Ok(LaunchRecipeSelectionWrite::RecipeMissing); + }; + let recipe: gamenode_core::library::CustomLaunchRecipe = + serde_json::from_str(&recipe_json).map_err(failed)?; + if recipe.installation_id != installation_id + || recipe.base_target_revision != expected_target_revision + || !recipe.validate() + { + return Ok(LaunchRecipeSelectionWrite::Conflict); + } + tx.execute( + "INSERT INTO library_launch_recipe_selection + (entry_key, owner_key, plugin_id, publisher_fingerprint, recipe_id, + recipe_revision, base_target_revision, approved_plan_fingerprint) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, '') + ON CONFLICT(entry_key) DO UPDATE SET + owner_key = excluded.owner_key, + plugin_id = excluded.plugin_id, + publisher_fingerprint = excluded.publisher_fingerprint, + recipe_id = excluded.recipe_id, + recipe_revision = excluded.recipe_revision, + base_target_revision = excluded.base_target_revision, + approved_plan_fingerprint = ''", + params![ + selection.entry_key, + selection.owner_key, + selection.plugin_id, + selection.publisher_fingerprint, + selection.recipe_id, + selection.recipe_revision as i64, + selection.base_target_revision as i64, + ], + ) + .map_err(failed)?; + tx.commit().map_err(failed)?; + Ok(LaunchRecipeSelectionWrite::Applied) + } + + fn clear_launch_recipe_selection( + &self, + entry_key: &str, + expected_target_revision: u64, + ) -> Result { + let mut conn = self.conn(); + let tx = conn.transaction().map_err(failed)?; + let target_json: Option> = tx + .query_row( + "SELECT target_json FROM library_entries WHERE key = ?1", + [entry_key], + |row| row.get(0), + ) + .optional() + .map_err(failed)?; + let Some(target_json) = target_json else { + return Ok(LaunchRecipeSelectionWrite::RecipeMissing); + }; + match target_json { + Some(target_json) => { + let target: gamenode_core::library::DetectedTarget = + serde_json::from_str(&target_json).map_err(failed)?; + if target.revision != expected_target_revision { + return Ok(LaunchRecipeSelectionWrite::Conflict); + } + } + None if expected_target_revision != 0 => { + return Ok(LaunchRecipeSelectionWrite::Conflict); + } + None => {} + } + tx.execute( + "DELETE FROM library_launch_recipe_selection WHERE entry_key = ?1", + [entry_key], + ) + .map_err(failed)?; + tx.commit().map_err(failed)?; + Ok(LaunchRecipeSelectionWrite::Applied) + } + + fn approve_launch_recipe_plan( + &self, + entry_key: &str, + recipe_id: &str, + recipe_revision: u64, + expected_target_revision: u64, + fingerprint: &str, + ) -> Result { + let mut conn = self.conn(); + let tx = conn.transaction().map_err(failed)?; + let selection: Option<(u64, u64)> = tx + .query_row( + "SELECT recipe_revision, base_target_revision + FROM library_launch_recipe_selection + WHERE entry_key = ?1 AND recipe_id = ?2", + params![entry_key, recipe_id], + |row| Ok((row.get::<_, i64>(0)? as u64, row.get::<_, i64>(1)? as u64)), + ) + .optional() + .map_err(failed)?; + let Some((current_recipe_revision, base_revision)) = selection else { + return Ok(LaunchRecipeSelectionWrite::RecipeMissing); + }; + let target_json: Option = tx + .query_row( + "SELECT target_json FROM library_entries WHERE key = ?1", + [entry_key], + |row| row.get(0), + ) + .optional() + .map_err(failed)? + .flatten(); + let Some(target_json) = target_json else { + return Ok(LaunchRecipeSelectionWrite::RecipeMissing); + }; + let target: gamenode_core::library::DetectedTarget = + serde_json::from_str(&target_json).map_err(failed)?; + if current_recipe_revision != recipe_revision + || base_revision != expected_target_revision + || target.revision != expected_target_revision + || fingerprint.is_empty() + { + return Ok(LaunchRecipeSelectionWrite::Conflict); + } + tx.execute( + "UPDATE library_launch_recipe_selection SET approved_plan_fingerprint = ?2 + WHERE entry_key = ?1", + params![entry_key, fingerprint], + ) + .map_err(failed)?; + tx.commit().map_err(failed)?; + Ok(LaunchRecipeSelectionWrite::Applied) + } + + fn runtime_resources(&self, owner_key: &str) -> Result, StorageError> { + if owner_key.is_empty() { + return Err(failed("runtime owner is required")); + } + let conn = self.conn(); + let mut statement = conn + .prepare( + "SELECT runtime_json FROM plugin_runtime_resources + WHERE owner_key = ?1 ORDER BY runtime_id", + ) + .map_err(failed)?; + let rows = statement + .query_map([owner_key], |row| row.get::<_, String>(0)) + .map_err(failed)?; + rows.map(|row| { + let json = row.map_err(failed)?; + let runtime: RuntimeResource = serde_json::from_str(&json).map_err(failed)?; + if !runtime.validate() { + return Err(failed("stored runtime resource is invalid")); + } + Ok(runtime) + }) + .collect() + } + + fn runtime_resource( + &self, + owner_key: &str, + runtime_id: &str, + ) -> Result, StorageError> { + if owner_key.is_empty() || runtime_id.is_empty() { + return Err(failed("runtime owner and id are required")); + } + let conn = self.conn(); + let json: Option = conn + .query_row( + "SELECT runtime_json FROM plugin_runtime_resources + WHERE owner_key = ?1 AND runtime_id = ?2", + params![owner_key, runtime_id], + |row| row.get(0), + ) + .optional() + .map_err(failed)?; + json.map(|json| { + let runtime: RuntimeResource = serde_json::from_str(&json).map_err(failed)?; + if runtime.validate() { + Ok(runtime) + } else { + Err(failed("stored runtime resource is invalid")) + } + }) + .transpose() + } + + fn save_runtime_resource( + &self, + owner_key: &str, + runtime: &RuntimeResource, + ) -> Result { + if owner_key.is_empty() || !runtime.validate() { + return Err(failed("invalid runtime resource")); + } + let mut conn = self.conn(); + let tx = conn.transaction().map_err(failed)?; + let current: Option = tx + .query_row( + "SELECT revision FROM plugin_runtime_resources + WHERE owner_key = ?1 AND runtime_id = ?2", + params![owner_key, runtime.id], + |row| row.get::<_, i64>(0).map(|value| value as u64), + ) + .optional() + .map_err(failed)?; + let expected = match current { + Some(revision) => revision + .checked_add(1) + .ok_or_else(|| failed("runtime revision is exhausted"))?, + None => 1, + }; + if runtime.revision != expected { + return Ok(match current { + Some(current) => RuntimeMutation::Conflict { current }, + None => RuntimeMutation::Conflict { current: 0 }, + }); + } + tx.execute( + "INSERT INTO plugin_runtime_resources + (owner_key, runtime_id, revision, runtime_json) + VALUES (?1, ?2, ?3, ?4) + ON CONFLICT(owner_key, runtime_id) DO UPDATE SET + revision = excluded.revision, + runtime_json = excluded.runtime_json", + params![ + owner_key, + runtime.id, + i64::try_from(runtime.revision).map_err(failed)?, + serde_json::to_string(runtime).map_err(failed)?, + ], + ) + .map_err(failed)?; + bump_runtime_catalog_revision(&tx, owner_key)?; + tx.commit().map_err(failed)?; + Ok(RuntimeMutation::Applied { + revision: runtime.revision, + }) + } + + fn remove_runtime_resource( + &self, + owner_key: &str, + runtime_id: &str, + expected_revision: u64, + ) -> Result { + if owner_key.is_empty() || runtime_id.is_empty() || expected_revision == 0 { + return Err(failed("invalid runtime removal")); + } + let mut conn = self.conn(); + let tx = conn.transaction().map_err(failed)?; + let current: Option = tx + .query_row( + "SELECT revision FROM plugin_runtime_resources + WHERE owner_key = ?1 AND runtime_id = ?2", + params![owner_key, runtime_id], + |row| row.get::<_, i64>(0).map(|value| value as u64), + ) + .optional() + .map_err(failed)?; + let Some(current) = current else { + return Ok(RuntimeMutation::Missing); + }; + if current != expected_revision { + return Ok(RuntimeMutation::Conflict { current }); + } + // Bindings intentionally outlive a runtime so the game remains identifiable and can be + // rebound later. This delete does not touch games, saves or play history. + tx.execute( + "DELETE FROM plugin_runtime_resources + WHERE owner_key = ?1 AND runtime_id = ?2 AND revision = ?3", + params![ + owner_key, + runtime_id, + i64::try_from(expected_revision).map_err(failed)? + ], + ) + .map_err(failed)?; + bump_runtime_catalog_revision(&tx, owner_key)?; + tx.commit().map_err(failed)?; + Ok(RuntimeMutation::Applied { + revision: expected_revision, + }) + } + + fn shared_runtime_resources(&self) -> Result, StorageError> { + let conn = self.conn(); + let mut statement = conn + .prepare( + "SELECT owner_key, runtime_json FROM plugin_runtime_resources + ORDER BY owner_key, runtime_id", + ) + .map_err(failed)?; + let rows = statement + .query_map([], |row| { + Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?)) + }) + .map_err(failed)?; + rows.map(|row| { + let (owner_key, json) = row.map_err(failed)?; + let runtime: RuntimeResource = serde_json::from_str(&json).map_err(failed)?; + if !runtime.validate() { + return Err(failed("stored runtime resource is invalid")); + } + Ok((owner_key, runtime)) + }) + .collect() + } + + fn shared_runtime_catalog_revision(&self) -> Result { + let conn = self.conn(); + let revision: i64 = conn + .query_row( + "SELECT COALESCE(MAX(catalog_revision), 0) FROM plugin_runtime_catalog_state", + [], + |row| row.get(0), + ) + .map_err(failed)?; + u64::try_from(revision).map_err(failed) + } + + fn runtime_availability( + &self, + owner_key: Option<&str>, + installation_ids: &[String], + ) -> Result, StorageError> { + if installation_ids.is_empty() { + return Ok(Vec::new()); + } + if installation_ids.len() > 1024 { + return Err(failed("too many installations requested")); + } + let placeholders = std::iter::repeat_n("?", installation_ids.len()) + .collect::>() + .join(", "); + let owner_clause = if owner_key.is_some() { + " AND b.owner_key = ?" + } else { + "" + }; + let sql = format!( + "SELECT b.installation_id, b.binding_json, r.runtime_json + FROM plugin_runtime_content_bindings b + LEFT JOIN plugin_runtime_resources r + ON r.owner_key = b.owner_key + AND r.runtime_id = json_extract(b.binding_json, '$.runtimeId') + WHERE b.installation_id IN ({placeholders}){owner_clause} + ORDER BY b.installation_id, b.owner_key, b.content_id, b.runtime_id" + ); + let conn = self.conn(); + let mut statement = conn.prepare(&sql).map_err(failed)?; + let mut values: Vec = installation_ids + .iter() + .map(|id| rusqlite::types::Value::Text(id.clone())) + .collect(); + if let Some(owner_key) = owner_key { + values.push(rusqlite::types::Value::Text(owner_key.to_owned())); + } + let rows = statement + .query_map(rusqlite::params_from_iter(values), |row| { + Ok(( + row.get::<_, String>(0)?, + row.get::<_, String>(1)?, + row.get::<_, Option>(2)?, + )) + }) + .map_err(failed)?; + let mut availability = Vec::new(); + for row in rows { + let (installation_id, binding_json, runtime_json) = row.map_err(failed)?; + let binding: RuntimeContentBinding = + serde_json::from_str(&binding_json).map_err(failed)?; + if !binding.validate() { + return Err(failed("stored runtime binding is invalid")); + } + let runtime = runtime_json + .map(|json| serde_json::from_str::(&json)) + .transpose() + .map_err(failed)?; + let runtime = runtime.filter(RuntimeResource::validate); + availability.push(RuntimeAvailabilityEntry { + installation_id, + content_id: binding.content_id, + content_kind: binding.content_kind, + runtime_id: binding.runtime_id, + runtime_name: runtime + .as_ref() + .map(|value| value.name.clone()) + .unwrap_or_default(), + platform: runtime + .as_ref() + .map(|value| value.platform.clone()) + .or_else(|| binding.supported_platforms.first().cloned()) + .unwrap_or_default(), + publisher_id: runtime + .as_ref() + .map(|value| value.provenance.plugin_id.clone()) + .unwrap_or_default(), + revision: binding.revision, + }); + } + Ok(availability) + } + + fn runtime_content_bindings( + &self, + owner_key: &str, + game_id: u64, + installation_id: &str, + ) -> Result, StorageError> { + if owner_key.is_empty() || game_id == 0 || installation_id.is_empty() { + return Err(failed("runtime binding identity is required")); + } + let conn = self.conn(); + let mut statement = conn + .prepare( + "SELECT binding_json FROM plugin_runtime_content_bindings + WHERE owner_key = ?1 AND game_id = ?2 AND installation_id = ?3 + ORDER BY content_id, runtime_id", + ) + .map_err(failed)?; + let rows = statement + .query_map( + params![owner_key, db_id(game_id)?, installation_id], + |row| row.get::<_, String>(0), + ) + .map_err(failed)?; + rows.map(|row| { + let json = row.map_err(failed)?; + let binding: RuntimeContentBinding = serde_json::from_str(&json).map_err(failed)?; + if !binding.validate() { + return Err(failed("stored runtime binding is invalid")); + } + Ok(binding) + }) + .collect() + } + + fn runtime_catalog_revision(&self, owner_key: &str) -> Result { + if owner_key.is_empty() { + return Err(failed("runtime owner is required")); + } + let conn = self.conn(); + let revision: Option = conn + .query_row( + "SELECT catalog_revision FROM plugin_runtime_catalog_state WHERE owner_key = ?1", + [owner_key], + |row| row.get(0), + ) + .optional() + .map_err(failed)?; + revision + .map(u64::try_from) + .transpose() + .map_err(failed) + .map(|revision| revision.unwrap_or(0)) + } + + fn save_runtime_content_binding( + &self, + owner_key: &str, + binding: &RuntimeContentBinding, + ) -> Result { + if owner_key.is_empty() || !binding.validate() { + return Err(failed("invalid runtime content binding")); + } + let mut conn = self.conn(); + let tx = conn.transaction().map_err(failed)?; + let runtime_exists: Option = tx + .query_row( + "SELECT 1 FROM plugin_runtime_resources + WHERE owner_key = ?1 AND runtime_id = ?2", + params![owner_key, binding.runtime_id], + |row| row.get(0), + ) + .optional() + .map_err(failed)?; + if runtime_exists.is_none() { + return Ok(RuntimeMutation::Missing); + } + let current: Option = tx + .query_row( + "SELECT revision FROM plugin_runtime_content_bindings + WHERE owner_key = ?1 AND game_id = ?2 AND installation_id = ?3 + AND content_id = ?4 AND runtime_id = ?5", + params![ + owner_key, + db_id(binding.game_id)?, + binding.installation_id, + binding.content_id, + binding.runtime_id, + ], + |row| row.get::<_, i64>(0).map(|value| value as u64), + ) + .optional() + .map_err(failed)?; + let expected = match current { + Some(revision) => revision + .checked_add(1) + .ok_or_else(|| failed("runtime binding revision is exhausted"))?, + None => 1, + }; + if binding.revision != expected { + return Ok(match current { + Some(current) => RuntimeMutation::Conflict { current }, + None => RuntimeMutation::Conflict { current: 0 }, + }); + } + let mut stored_binding = binding.clone(); + if current.is_none() { + // Adding another runtime for an existing content_id must use its already-current + // locator. A caller can move/rename it by revision-updating an existing binding first; + // a new runtime binding cannot accidentally roll the shared locator back from stale + // data. + let sibling_json: Option = tx + .query_row( + "SELECT binding_json FROM plugin_runtime_content_bindings + WHERE owner_key = ?1 AND game_id = ?2 AND installation_id = ?3 + AND content_id = ?4 ORDER BY runtime_id LIMIT 1", + params![ + owner_key, + db_id(binding.game_id)?, + binding.installation_id, + binding.content_id, + ], + |row| row.get(0), + ) + .optional() + .map_err(failed)?; + if let Some(json) = sibling_json { + let sibling: RuntimeContentBinding = serde_json::from_str(&json).map_err(failed)?; + stored_binding.content = sibling.content; + stored_binding.content_kind = sibling.content_kind; + } + } + tx.execute( + "INSERT INTO plugin_runtime_content_bindings + (owner_key, game_id, installation_id, content_id, runtime_id, revision, binding_json) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7) + ON CONFLICT(owner_key, game_id, installation_id, content_id, runtime_id) DO UPDATE SET + revision = excluded.revision, + binding_json = excluded.binding_json", + params![ + owner_key, + db_id(binding.game_id)?, + binding.installation_id, + binding.content_id, + binding.runtime_id, + i64::try_from(binding.revision).map_err(failed)?, + serde_json::to_string(&stored_binding).map_err(failed)?, + ], + ) + .map_err(failed)?; + // A content locator is keyed by stable content_id, not by the runtime. Refresh every + // sibling binding in the same transaction so choosing another runtime cannot resolve the + // same moved/renamed content through a stale handle. Sibling revisions advance so stale + // clients cannot overwrite the new location. + let siblings = { + let mut statement = tx + .prepare( + "SELECT runtime_id, revision, binding_json + FROM plugin_runtime_content_bindings + WHERE owner_key = ?1 AND game_id = ?2 AND installation_id = ?3 + AND content_id = ?4 AND runtime_id <> ?5", + ) + .map_err(failed)?; + let rows = statement + .query_map( + params![ + owner_key, + db_id(binding.game_id)?, + binding.installation_id, + binding.content_id, + binding.runtime_id, + ], + |row| { + Ok(( + row.get::<_, String>(0)?, + row.get::<_, i64>(1)?, + row.get::<_, String>(2)?, + )) + }, + ) + .map_err(failed)?; + rows.collect::, _>>().map_err(failed)? + }; + for (runtime_id, revision, json) in siblings { + let mut sibling: RuntimeContentBinding = serde_json::from_str(&json).map_err(failed)?; + if sibling.content != stored_binding.content + || sibling.content_kind != stored_binding.content_kind + { + sibling.content = stored_binding.content.clone(); + sibling.content_kind = stored_binding.content_kind.clone(); + sibling.revision = u64::try_from(revision) + .map_err(failed)? + .checked_add(1) + .ok_or_else(|| failed("runtime binding revision is exhausted"))?; + tx.execute( + "UPDATE plugin_runtime_content_bindings + SET revision = ?1, binding_json = ?2 + WHERE owner_key = ?3 AND game_id = ?4 AND installation_id = ?5 + AND content_id = ?6 AND runtime_id = ?7 AND revision = ?8", + params![ + i64::try_from(sibling.revision).map_err(failed)?, + serde_json::to_string(&sibling).map_err(failed)?, + owner_key, + db_id(binding.game_id)?, + binding.installation_id, + binding.content_id, + runtime_id, + revision, + ], + ) + .map_err(failed)?; + } + } + tx.commit().map_err(failed)?; + Ok(RuntimeMutation::Applied { + revision: binding.revision, + }) + } + + fn remove_runtime_content_binding( + &self, + owner_key: &str, + binding: &RuntimeContentBinding, + ) -> Result { + if owner_key.is_empty() || !binding.validate() { + return Err(failed("invalid runtime binding removal")); + } + let mut conn = self.conn(); + let tx = conn.transaction().map_err(failed)?; + let current: Option = tx + .query_row( + "SELECT revision FROM plugin_runtime_content_bindings + WHERE owner_key = ?1 AND game_id = ?2 AND installation_id = ?3 + AND content_id = ?4 AND runtime_id = ?5", + params![ + owner_key, + db_id(binding.game_id)?, + binding.installation_id, + binding.content_id, + binding.runtime_id, + ], + |row| row.get::<_, i64>(0).map(|value| value as u64), + ) + .optional() + .map_err(failed)?; + let Some(current) = current else { + return Ok(RuntimeMutation::Missing); + }; + if current != binding.revision { + return Ok(RuntimeMutation::Conflict { current }); + } + tx.execute( + "DELETE FROM plugin_runtime_content_bindings + WHERE owner_key = ?1 AND game_id = ?2 AND installation_id = ?3 + AND content_id = ?4 AND runtime_id = ?5 AND revision = ?6", + params![ + owner_key, + db_id(binding.game_id)?, + binding.installation_id, + binding.content_id, + binding.runtime_id, + i64::try_from(binding.revision).map_err(failed)?, + ], + ) + .map_err(failed)?; + tx.commit().map_err(failed)?; + Ok(RuntimeMutation::Applied { + revision: binding.revision, + }) + } + fn save_scan_failure(&self, provider: &str, error: &str) -> Result<(), StorageError> { self.conn() .execute( @@ -767,11 +1853,18 @@ impl LibraryStore for SqliteLibraryStore { let game = choice.game_id.map(db_id).transpose()?; self.conn() .execute( - "INSERT INTO chosen_matches (account_id, entry_key, game_id, chosen_at) - VALUES (?1, ?2, ?3, ?4) + "INSERT INTO chosen_matches (account_id, entry_key, game_id, chosen_at, source) + VALUES (?1, ?2, ?3, ?4, ?5) ON CONFLICT(account_id, entry_key) DO UPDATE SET - game_id = excluded.game_id, chosen_at = excluded.chosen_at", - params![account_id, choice.entry_key, game, choice.chosen_at], + game_id = excluded.game_id, chosen_at = excluded.chosen_at, + source = excluded.source", + params![ + account_id, + choice.entry_key, + game, + choice.chosen_at, + choice.source.as_str() + ], ) .map(drop) .map_err(failed) @@ -1095,6 +2188,133 @@ impl LibraryStore for SqliteLibraryStore { write_setting(&self.conn(), KEY_EXCLUDED, &json).map_err(failed) } + fn save_display_name( + &self, + entry_key: &str, + expected_revision: u64, + display_name: Option<&str>, + ) -> Result { + let mut conn = self.conn(); + let tx = conn.transaction().map_err(failed)?; + let current: Option<(Option, i64)> = tx + .query_row( + "SELECT display_name, revision FROM library_display_overrides WHERE entry_key = ?1", + [entry_key], + |row| Ok((row.get(0)?, row.get(1)?)), + ) + .optional() + .map_err(failed)?; + let (current_name, current_revision) = match current { + Some((name, revision)) => (name, u64::try_from(revision).map_err(failed)?), + None => (None, 0), + }; + if current_revision != expected_revision { + return Ok(DisplayWrite::Conflict { + current: current_revision, + }); + } + if current_name.as_deref() == display_name { + return Ok(DisplayWrite::Unchanged { + revision: current_revision, + }); + } + let revision = current_revision + 1; + tx.execute( + "INSERT INTO library_display_overrides (entry_key, display_name, revision) + VALUES (?1, ?2, ?3) + ON CONFLICT(entry_key) DO UPDATE SET + display_name = excluded.display_name, revision = excluded.revision", + params![ + entry_key, + display_name, + i64::try_from(revision).map_err(failed)? + ], + ) + .map_err(failed)?; + tx.commit().map_err(failed)?; + Ok(DisplayWrite::Applied { revision }) + } + + fn save_artwork( + &self, + entry_key: &str, + expected_revision: u64, + file: Option<&str>, + ) -> Result { + let mut conn = self.conn(); + let tx = conn.transaction().map_err(failed)?; + let current: Option<(Option, i64)> = tx + .query_row( + "SELECT file, revision FROM library_artwork_overrides WHERE entry_key = ?1", + [entry_key], + |row| Ok((row.get(0)?, row.get(1)?)), + ) + .optional() + .map_err(failed)?; + let (current_file, current_revision) = match current { + Some((file, revision)) => (file, u64::try_from(revision).map_err(failed)?), + None => (None, 0), + }; + if current_revision != expected_revision { + return Ok(ArtworkWrite::Conflict { + current: current_revision, + }); + } + if current_file.as_deref() == file { + return Ok(ArtworkWrite::Unchanged { + revision: current_revision, + }); + } + let revision = current_revision + 1; + tx.execute( + "INSERT INTO library_artwork_overrides (entry_key, file, revision) + VALUES (?1, ?2, ?3) + ON CONFLICT(entry_key) DO UPDATE SET + file = excluded.file, revision = excluded.revision", + params![entry_key, file, i64::try_from(revision).map_err(failed)?], + ) + .map_err(failed)?; + tx.commit().map_err(failed)?; + Ok(ArtworkWrite::Applied { + revision, + replaced: current_file, + }) + } + + fn installation_ids( + &self, + entry_keys: &[String], + ) -> Result, StorageError> { + let mut conn = self.conn(); + let tx = conn.transaction().map_err(failed)?; + let mut ids = Vec::with_capacity(entry_keys.len()); + { + // 128 random bits from SQLite's CSPRNG; an (astronomically unlikely) duplicate id + // is ignored and the key simply has no id until the next request. + let mut assign = tx + .prepare( + "INSERT OR IGNORE INTO library_installations (entry_key, installation_id) + VALUES (?1, lower(hex(randomblob(16))))", + ) + .map_err(failed)?; + let mut read = tx + .prepare("SELECT installation_id FROM library_installations WHERE entry_key = ?1") + .map_err(failed)?; + for key in entry_keys { + assign.execute([key]).map_err(failed)?; + if let Some(id) = read + .query_row([key], |row| row.get::<_, String>(0)) + .optional() + .map_err(failed)? + { + ids.push((key.clone(), id)); + } + } + } + tx.commit().map_err(failed)?; + Ok(ids) + } + fn load_last_account(&self) -> Result, StorageError> { let conn = self.conn(); let id = read_setting(&conn, KEY_ACCOUNT_ID).map_err(failed)?; diff --git a/crates/platform/src/library_db/tests.rs b/crates/platform/src/library_db/tests.rs index b677fd37e..2a733e178 100644 --- a/crates/platform/src/library_db/tests.rs +++ b/crates/platform/src/library_db/tests.rs @@ -47,7 +47,7 @@ fn a_scan_is_saved_and_loaded_with_its_fields() { let dir = TempDir::new().unwrap(); let store = open(&dir).library_store(); store - .save_scan("steam", &[record("620", "Portal 2")], 100) + .save_scan("steam", &[record("620", "Portal 2")], &BTreeMap::new(), 100) .unwrap(); let cache = store.load_cache(None).unwrap(); @@ -86,13 +86,18 @@ fn a_rescan_updates_entries_adds_new_ones_and_keeps_first_seen() { let dir = TempDir::new().unwrap(); let store = open(&dir).library_store(); store - .save_scan("steam", &[record("620", "Portal 2")], 100) + .save_scan("steam", &[record("620", "Portal 2")], &BTreeMap::new(), 100) .unwrap(); let mut moved = record("620", "Portal 2"); moved.install_dir = "/other/Portal 2".into(); store - .save_scan("steam", &[moved, record("570", "Dota 2")], 200) + .save_scan( + "steam", + &[moved, record("570", "Dota 2")], + &BTreeMap::new(), + 200, + ) .unwrap(); let cache = store.load_cache(None).unwrap(); @@ -108,7 +113,7 @@ fn an_uninstalled_game_is_kept_with_its_matches_and_returns_with_them() { let dir = TempDir::new().unwrap(); let store = open(&dir).library_store(); store - .save_scan("steam", &[record("620", "Portal 2")], 100) + .save_scan("steam", &[record("620", "Portal 2")], &BTreeMap::new(), 100) .unwrap(); store .save_auto_matches(&[AutoMatch { @@ -125,6 +130,7 @@ fn an_uninstalled_game_is_kept_with_its_matches_and_returns_with_them() { entry_key: "steam:620".into(), game_id: Some(72), chosen_at: 110, + source: gamenode_core::library::ChoiceSource::User, }, ) .unwrap(); @@ -137,7 +143,9 @@ fn an_uninstalled_game_is_kept_with_its_matches_and_returns_with_them() { store.save_cover_ready(72, "72.jpg").unwrap(); // Steam no longer lists it. - store.save_scan("steam", &[], 200).unwrap(); + store + .save_scan("steam", &[], &BTreeMap::new(), 200) + .unwrap(); let cache = store.load_cache(Some("acct")).unwrap(); assert_eq!(keys(&cache), [("steam:620", false)]); assert_eq!(cache.auto_matches.len(), 1); @@ -146,7 +154,7 @@ fn an_uninstalled_game_is_kept_with_its_matches_and_returns_with_them() { // Reinstalled: same entry, same match and cover. store - .save_scan("steam", &[record("620", "Portal 2")], 300) + .save_scan("steam", &[record("620", "Portal 2")], &BTreeMap::new(), 300) .unwrap(); let cache = store.load_cache(Some("acct")).unwrap(); assert_eq!(keys(&cache), [("steam:620", true)]); @@ -160,10 +168,10 @@ fn a_failed_scan_keeps_the_previous_entries_and_only_marks_that_provider() { let dir = TempDir::new().unwrap(); let store = open(&dir).library_store(); store - .save_scan("steam", &[record("620", "Portal 2")], 100) + .save_scan("steam", &[record("620", "Portal 2")], &BTreeMap::new(), 100) .unwrap(); store - .save_scan("gog", &[record("g1", "Witcher")], 100) + .save_scan("gog", &[record("g1", "Witcher")], &BTreeMap::new(), 100) .unwrap(); store @@ -178,7 +186,7 @@ fn a_failed_scan_keeps_the_previous_entries_and_only_marks_that_provider() { assert_eq!(gog.last_error, None); store - .save_scan("steam", &[record("620", "Portal 2")], 200) + .save_scan("steam", &[record("620", "Portal 2")], &BTreeMap::new(), 200) .unwrap(); let steam = store .load_cache(None) @@ -205,7 +213,7 @@ fn a_scan_that_fails_part_way_changes_nothing() { let dir = TempDir::new().unwrap(); let store = open(&dir).library_store(); store - .save_scan("steam", &[record("620", "Portal 2")], 100) + .save_scan("steam", &[record("620", "Portal 2")], &BTreeMap::new(), 100) .unwrap(); // Make the second insert fail, after the first has already been written. store @@ -218,6 +226,7 @@ fn a_scan_that_fails_part_way_changes_nothing() { let result = store.save_scan( "steam", &[record("570", "Dota 2"), record("bad", "Bad")], + &BTreeMap::new(), 200, ); assert!(result.is_err()); @@ -240,6 +249,7 @@ fn chosen_matches_are_separate_per_account() { entry_key: "steam:620".into(), game_id, chosen_at: 5, + source: gamenode_core::library::ChoiceSource::User, }; store.save_chosen_match("alice", &choice(Some(72))).unwrap(); store.save_chosen_match("bob", &choice(None)).unwrap(); @@ -453,7 +463,7 @@ fn sign_out_removes_the_account_keys_and_keeps_everything_else() { }) .unwrap(); store - .save_scan("steam", &[record("620", "Portal 2")], 1) + .save_scan("steam", &[record("620", "Portal 2")], &BTreeMap::new(), 1) .unwrap(); store .save_chosen_match( @@ -462,6 +472,7 @@ fn sign_out_removes_the_account_keys_and_keeps_everything_else() { entry_key: "steam:620".into(), game_id: Some(1), chosen_at: 1, + source: gamenode_core::library::ChoiceSource::User, }, ) .unwrap(); @@ -546,7 +557,7 @@ fn nothing_stored_is_a_credential_or_a_callback_url() { }) .unwrap(); store - .save_scan("steam", &[record("620", "Portal 2")], 1) + .save_scan("steam", &[record("620", "Portal 2")], &BTreeMap::new(), 1) .unwrap(); store .save_games(&[game( @@ -635,7 +646,7 @@ fn catalog_fields_fill_missing_keys_and_survive_a_restart() { { let store = open(&dir).library_store(); store - .save_scan("steam", &[record("620", "Portal 2")], 100) + .save_scan("steam", &[record("620", "Portal 2")], &BTreeMap::new(), 100) .unwrap(); store .save_catalog( @@ -698,6 +709,7 @@ fn catalog_sync_replaces_its_facts_and_lets_owned_win_over_shared() { .save_scan( "steam", &[record("620", "Portal 2"), record("570", "Dota 2")], + &BTreeMap::new(), 100, ) .unwrap(); @@ -1002,7 +1014,12 @@ fn catalog_names_follow_installed_then_existing_then_catalog_precedence() { // Once installed, the installed scan's name wins over a catalog name. store - .save_scan("steam", &[record("730", "Installed name")], 400) + .save_scan( + "steam", + &[record("730", "Installed name")], + &BTreeMap::new(), + 400, + ) .unwrap(); store .save_catalog( @@ -1033,7 +1050,7 @@ fn save_scan_never_changes_owned_or_shared_facts() { .unwrap(); store - .save_scan("steam", &[record("620", "Portal 2")], 200) + .save_scan("steam", &[record("620", "Portal 2")], &BTreeMap::new(), 200) .unwrap(); let cache = store.load_cache(None).unwrap(); let portal = cache.entries.iter().find(|e| e.key == "steam:620").unwrap(); @@ -1052,7 +1069,9 @@ fn save_scan_never_changes_owned_or_shared_facts() { ); // A scan that no longer finds an entry only clears installed. - store.save_scan("steam", &[], 300).unwrap(); + store + .save_scan("steam", &[], &BTreeMap::new(), 300) + .unwrap(); let cache = store.load_cache(None).unwrap(); let portal = cache.entries.iter().find(|e| e.key == "steam:620").unwrap(); assert_eq!( @@ -1074,7 +1093,7 @@ fn clear_catalog_keeps_entries_matches_and_covers() { let dir = TempDir::new().unwrap(); let store = open(&dir).library_store(); store - .save_scan("steam", &[record("620", "Portal 2")], 100) + .save_scan("steam", &[record("620", "Portal 2")], &BTreeMap::new(), 100) .unwrap(); store .save_auto_matches(&[AutoMatch { @@ -1091,6 +1110,7 @@ fn clear_catalog_keeps_entries_matches_and_covers() { entry_key: "steam:620".into(), game_id: Some(72), chosen_at: 110, + source: gamenode_core::library::ChoiceSource::User, }, ) .unwrap(); @@ -1261,7 +1281,7 @@ fn unreadable_flags_and_error_categories_degrade_without_hiding_installed_games( let dir = TempDir::new().unwrap(); let store = open(&dir).library_store(); store - .save_scan("steam", &[record("620", "Portal 2")], 100) + .save_scan("steam", &[record("620", "Portal 2")], &BTreeMap::new(), 100) .unwrap(); store .save_catalog( @@ -1329,6 +1349,7 @@ fn a_chosen_match_can_be_forgotten_for_one_account_only() { entry_key: "steam:620".to_owned(), game_id, chosen_at: 5, + source: gamenode_core::library::ChoiceSource::User, }; store.save_chosen_match("alice", &choice(Some(72))).unwrap(); store.save_chosen_match("bob", &choice(None)).unwrap(); @@ -1843,3 +1864,973 @@ fn unknown_account_statuses_and_damaged_collections_degrade_to_none_and_empty() assert_eq!(library.collections[0].default_status, None); assert_eq!(library.collections[0].name, "Coop"); } + +// Tests retained from the plugin branch during main integration. + +#[test] +fn a_detected_target_approval_is_revision_checked_and_survives_reopening() { + use gamenode_core::library::{DetectedTarget, TargetApproval, TargetSpec}; + + let dir = TempDir::new().unwrap(); + let path = dir.path().join("test.sqlite3"); + let db = SqliteSettingsStore::open(&path).unwrap(); + let store = db.library_store(); + let spec = TargetSpec::Executable { + root: r"C:\Games\Portal 2".into(), + path: "Portal2.exe".into(), + arguments: vec![], + working_directory: String::new(), + }; + store + .save_scan( + "steam", + &[record("620", "Portal 2")], + &BTreeMap::from([("620".into(), spec)]), + 100, + ) + .unwrap(); + let candidate = store + .load_cache(None) + .unwrap() + .entries + .remove(0) + .target + .unwrap(); + assert!(!candidate.approved); + assert_eq!(candidate.revision, 1); + + let approved = DetectedTarget { + approved: true, + identity: Some("volume:file-id".into()), + ..candidate.clone() + }; + assert_eq!( + store.save_target_review("steam:620", 1, &approved).unwrap(), + TargetApproval::Applied { revision: 1 } + ); + assert_eq!( + store.save_target_review("steam:620", 0, &approved).unwrap(), + TargetApproval::Conflict { current: 1 } + ); + + store + .save_scan( + "steam", + &[record("620", "Portal 2")], + &BTreeMap::from([("620".into(), approved.spec.clone())]), + 200, + ) + .unwrap(); + + drop(store); + drop(db); + let reopened = SqliteSettingsStore::open(&path).unwrap().library_store(); + let target = reopened + .load_cache(None) + .unwrap() + .entries + .remove(0) + .target + .unwrap(); + assert!(target.approved); + assert_eq!(target.identity.as_deref(), Some("volume:file-id")); +} + +#[test] +fn a_choice_keeps_who_made_it_and_older_rows_read_as_the_users() { + use gamenode_core::library::ChoiceSource; + let dir = TempDir::new().unwrap(); + let store = open(&dir).library_store(); + let choice = |source| ChosenMatch { + entry_key: "epic:abc".into(), + game_id: Some(9), + chosen_at: 5, + source, + }; + store + .save_chosen_match("alice", &choice(ChoiceSource::Plugin)) + .unwrap(); + assert_eq!( + store.load_cache(Some("alice")).unwrap().chosen_matches, + [choice(ChoiceSource::Plugin)] + ); + // The user choosing again takes the entry over. + store + .save_chosen_match("alice", &choice(ChoiceSource::User)) + .unwrap(); + assert_eq!( + store.load_cache(Some("alice")).unwrap().chosen_matches, + [choice(ChoiceSource::User)] + ); + // A row written without the column (before migration 12) is the user's. + open(&dir) + .conn() + .execute( + "INSERT INTO chosen_matches (account_id, entry_key, game_id, chosen_at) + VALUES ('bob', 'steam:1', 2, 3)", + [], + ) + .unwrap(); + assert_eq!( + store.load_cache(Some("bob")).unwrap().chosen_matches[0].source, + ChoiceSource::User + ); +} + +#[test] +fn installation_ids_are_random_durable_and_never_change_for_their_key() { + let dir = TempDir::new().unwrap(); + let store = open(&dir); + let library = store.library_store(); + let keys = ["steam:620".to_owned(), "epic:abc".to_owned()]; + let first = library.installation_ids(&keys).unwrap(); + assert_eq!(first.len(), 2); + assert_eq!(first[0].0, "steam:620"); + assert_ne!(first[0].1, first[1].1); + for (key, id) in &first { + assert_eq!(id.len(), 32, "{key}"); + assert!(id.chars().all(|c| c.is_ascii_hexdigit())); + } + // A rescan, a match change or another request does not touch the ids. + library + .save_scan( + "steam", + &[record("620", "Portal 2 GOTY")], + &BTreeMap::new(), + 2, + ) + .unwrap(); + library + .save_auto_matches(&[AutoMatch { + category: 1, + uid: "620".into(), + game_ids: vec![9], + checked_at: 3, + }]) + .unwrap(); + let again = library + .installation_ids(&["epic:abc".to_owned(), "steam:620".to_owned()]) + .unwrap(); + assert_eq!(again[0], first[1]); + assert_eq!(again[1], first[0]); + drop(library); + drop(store); + // And they survive a restart. + let reopened = open(&dir); + assert_eq!( + reopened.library_store().installation_ids(&keys).unwrap(), + first + ); +} + +#[test] +fn display_names_are_guarded_by_a_revision_and_reset_keeps_counting() { + let dir = TempDir::new().unwrap(); + let store = open(&dir); + let library = store.library_store(); + let key = "steam:620"; + // Never written: revision 0, and a stale expectation conflicts without writing. + assert_eq!( + library.save_display_name(key, 3, Some("X")).unwrap(), + DisplayWrite::Conflict { current: 0 } + ); + assert!( + library + .load_cache(None) + .unwrap() + .display_overrides + .is_empty() + ); + assert_eq!( + library + .save_display_name(key, 0, Some("Portal Two")) + .unwrap(), + DisplayWrite::Applied { revision: 1 } + ); + // The same value again changes nothing and keeps the revision. + assert_eq!( + library + .save_display_name(key, 1, Some("Portal Two")) + .unwrap(), + DisplayWrite::Unchanged { revision: 1 } + ); + // An obsolete revision does not overwrite the newer value. + assert_eq!( + library.save_display_name(key, 0, Some("Other")).unwrap(), + DisplayWrite::Conflict { current: 1 } + ); + // Clearing restores the detected name, keeps the row and the revision keeps growing. + assert_eq!( + library.save_display_name(key, 1, None).unwrap(), + DisplayWrite::Applied { revision: 2 } + ); + assert_eq!( + library.save_display_name(key, 2, None).unwrap(), + DisplayWrite::Unchanged { revision: 2 } + ); + assert_eq!( + library.save_display_name(key, 2, Some("Back")).unwrap(), + DisplayWrite::Applied { revision: 3 } + ); + drop(library); + drop(store); + let reopened = open(&dir); + assert_eq!( + reopened + .library_store() + .load_cache(None) + .unwrap() + .display_overrides, + [DisplayOverride { + entry_key: key.to_owned(), + display_name: Some("Back".to_owned()), + revision: 3, + }] + ); +} + +#[test] +fn artwork_overrides_are_guarded_by_a_revision_and_report_the_file_they_replace() { + use gamenode_core::library::{ArtworkOverride, ArtworkWrite}; + let dir = TempDir::new().unwrap(); + let store = open(&dir); + let library = store.library_store(); + let key = "steam:620"; + assert_eq!( + library.save_artwork(key, 2, Some("a.jpg")).unwrap(), + ArtworkWrite::Conflict { current: 0 } + ); + assert!( + library + .load_cache(None) + .unwrap() + .artwork_overrides + .is_empty() + ); + assert_eq!( + library.save_artwork(key, 0, Some("a.jpg")).unwrap(), + ArtworkWrite::Applied { + revision: 1, + replaced: None + } + ); + assert_eq!( + library.save_artwork(key, 1, Some("a.jpg")).unwrap(), + ArtworkWrite::Unchanged { revision: 1 } + ); + assert_eq!( + library.save_artwork(key, 0, Some("b.jpg")).unwrap(), + ArtworkWrite::Conflict { current: 1 } + ); + // Replacing names the file that is no longer used, so the caller can delete it. + assert_eq!( + library.save_artwork(key, 1, Some("b.jpg")).unwrap(), + ArtworkWrite::Applied { + revision: 2, + replaced: Some("a.jpg".to_owned()) + } + ); + // Clearing restores the game's cover and keeps counting. + assert_eq!( + library.save_artwork(key, 2, None).unwrap(), + ArtworkWrite::Applied { + revision: 3, + replaced: Some("b.jpg".to_owned()) + } + ); + assert_eq!( + library.save_artwork(key, 3, None).unwrap(), + ArtworkWrite::Unchanged { revision: 3 } + ); + drop(library); + drop(store); + let reopened = open(&dir); + assert_eq!( + reopened + .library_store() + .load_cache(None) + .unwrap() + .artwork_overrides, + [ArtworkOverride { + entry_key: key.to_owned(), + file: None, + revision: 3, + }] + ); +} + +#[test] +fn custom_launch_recipes_are_plugin_scoped_revision_checked_and_persistent() { + use gamenode_core::library::{CustomLaunchMutation, CustomLaunchRecipe}; + + let dir = TempDir::new().unwrap(); + let path = dir.path().join("test.sqlite3"); + let db = SqliteSettingsStore::open(&path).unwrap(); + let store = db.library_store(); + let recipe = CustomLaunchRecipe { + recipe_id: "recipe-1".into(), + revision: 1, + requester_package_version: "1.0".into(), + game_id: 620, + installation_id: "install-1".into(), + base_target_revision: 1, + base_launch_fingerprint: 9, + executable_handle: "approved-executable-handle".into(), + executable: None, + uri: String::new(), + arguments: vec!["--profile".into(), "a profile & literal".into()], + working_directory_handle: "approved-directory-handle".into(), + working_directory: None, + runtime_handle: String::new(), + content_id: String::new(), + environment_set: BTreeMap::from([("GAME_MODE".into(), "custom".into())]), + environment_unset: Default::default(), + mod_layers: Vec::new(), + }; + assert_eq!( + store + .save_custom_launch_recipe("plugin-a/profile-1", &recipe) + .unwrap(), + CustomLaunchMutation::Applied { revision: 1 } + ); + assert_eq!( + store + .custom_launch_recipe("plugin-b/profile-1", "recipe-1") + .unwrap(), + None, + "another plugin cannot read this recipe" + ); + assert_eq!( + store + .save_custom_launch_recipe("plugin-a/profile-1", &recipe) + .unwrap(), + CustomLaunchMutation::Conflict { current: 1 } + ); + assert_eq!( + store + .remove_custom_launch_recipe("plugin-a/profile-1", "recipe-1", 0) + .unwrap(), + CustomLaunchMutation::Conflict { current: 1 } + ); + drop(store); + drop(db); + + let reopened = SqliteSettingsStore::open(&path).unwrap().library_store(); + assert_eq!( + reopened + .custom_launch_recipe("plugin-a/profile-1", "recipe-1") + .unwrap(), + Some(recipe.clone()), + "recipe and literal argv survive restarting the store" + ); + assert_eq!( + reopened + .remove_custom_launch_recipe("plugin-a/profile-1", "recipe-1", 1) + .unwrap(), + CustomLaunchMutation::Applied { revision: 1 } + ); + assert_eq!( + reopened + .custom_launch_recipe("plugin-a/profile-1", "recipe-1") + .unwrap(), + None + ); +} + +#[test] +fn a_runtime_recipe_selection_is_saved_without_a_detected_target() { + use gamenode_core::library::{ + CustomLaunchMutation, CustomLaunchRecipe, LaunchRecipeSelection, LaunchRecipeSelectionWrite, + }; + + let dir = TempDir::new().unwrap(); + let path = dir.path().join("test.sqlite3"); + let db = SqliteSettingsStore::open(&path).unwrap(); + let store = db.library_store(); + store + .save_scan( + "dolphin-emu", + &[record("GPIE01", "Pikmin")], + &BTreeMap::new(), + 100, + ) + .unwrap(); + db.conn() + .execute( + "INSERT INTO library_installations (entry_key, installation_id) + VALUES ('dolphin-emu:GPIE01', 'install-1')", + [], + ) + .unwrap(); + let recipe = CustomLaunchRecipe { + recipe_id: "recipe-1".into(), + revision: 1, + requester_package_version: "0.3.1".into(), + game_id: 2239, + installation_id: "install-1".into(), + base_target_revision: 0, + base_launch_fingerprint: 9, + runtime_handle: "runtime-1".into(), + content_id: "content-1".into(), + ..CustomLaunchRecipe::default() + }; + assert_eq!( + store + .save_custom_launch_recipe("plugin-owner", &recipe) + .unwrap(), + CustomLaunchMutation::Applied { revision: 1 } + ); + let selection = LaunchRecipeSelection { + entry_key: "dolphin-emu:GPIE01".into(), + owner_key: "plugin-owner".into(), + plugin_id: "dev.richmont.gamenode.dolphin-emu-launch".into(), + publisher_fingerprint: "publisher-key-fingerprint".into(), + recipe_id: recipe.recipe_id.clone(), + recipe_revision: recipe.revision, + base_target_revision: 0, + approved_plan_fingerprint: String::new(), + }; + assert_eq!( + store.save_launch_recipe_selection(&selection, 0).unwrap(), + LaunchRecipeSelectionWrite::Applied + ); + assert_eq!( + store + .launch_recipe_selection("dolphin-emu:GPIE01") + .unwrap() + .unwrap() + .base_target_revision, + 0 + ); + assert_eq!( + store + .clear_launch_recipe_selection("dolphin-emu:GPIE01", 0) + .unwrap(), + LaunchRecipeSelectionWrite::Applied + ); + assert!( + store + .launch_recipe_selection("dolphin-emu:GPIE01") + .unwrap() + .is_none() + ); +} + +#[test] +fn selected_launch_recipe_is_revision_checked_persistent_and_never_falls_back_silently() { + use gamenode_core::library::{ + CustomLaunchMutation, CustomLaunchRecipe, LaunchRecipeSelection, + LaunchRecipeSelectionWrite, TargetSpec, + }; + + let dir = TempDir::new().unwrap(); + let path = dir.path().join("test.sqlite3"); + let db = SqliteSettingsStore::open(&path).unwrap(); + let store = db.library_store(); + store + .save_scan( + "steam", + &[record("620", "Portal 2")], + &BTreeMap::from([( + "620".into(), + TargetSpec::Executable { + root: r"C:\Games\Portal 2".into(), + path: "Portal2.exe".into(), + arguments: vec![], + working_directory: String::new(), + }, + )]), + 100, + ) + .unwrap(); + let target = store + .load_cache(None) + .unwrap() + .entries + .into_iter() + .find(|entry| entry.key == "steam:620") + .unwrap() + .target + .unwrap(); + db.conn() + .execute( + "INSERT INTO library_installations (entry_key, installation_id) VALUES ('steam:620', 'install-1')", + [], + ) + .unwrap(); + let recipe = CustomLaunchRecipe { + recipe_id: "recipe-1".into(), + revision: 1, + requester_package_version: "1.0".into(), + game_id: 620, + installation_id: "install-1".into(), + base_target_revision: target.revision, + base_launch_fingerprint: 9, + executable_handle: "approved-executable-handle".into(), + executable: None, + uri: String::new(), + arguments: vec!["--custom".into()], + working_directory_handle: String::new(), + working_directory: None, + runtime_handle: String::new(), + content_id: String::new(), + environment_set: Default::default(), + environment_unset: Default::default(), + mod_layers: Vec::new(), + }; + assert_eq!( + store + .save_custom_launch_recipe("plugin-owner", &recipe) + .unwrap(), + CustomLaunchMutation::Applied { revision: 1 } + ); + let selection = LaunchRecipeSelection { + entry_key: "steam:620".into(), + owner_key: "plugin-owner".into(), + plugin_id: "example.launcher".into(), + publisher_fingerprint: "publisher-key-fingerprint".into(), + recipe_id: recipe.recipe_id.clone(), + recipe_revision: recipe.revision, + base_target_revision: target.revision, + approved_plan_fingerprint: String::new(), + }; + assert_eq!( + store + .save_launch_recipe_selection(&selection, target.revision) + .unwrap(), + LaunchRecipeSelectionWrite::Applied + ); + assert_eq!( + store + .save_launch_recipe_selection(&selection, target.revision + 1) + .unwrap(), + LaunchRecipeSelectionWrite::Conflict + ); + drop(store); + drop(db); + + let reopened = SqliteSettingsStore::open(&path).unwrap(); + let store = reopened.library_store(); + assert_eq!( + store.launch_recipe_selection("steam:620").unwrap(), + Some(selection) + ); + assert_eq!( + store + .remove_custom_launch_recipe("plugin-owner", "recipe-1", 1) + .unwrap(), + CustomLaunchMutation::Applied { revision: 1 } + ); + assert_eq!( + store + .launch_recipe_selection("steam:620") + .unwrap() + .unwrap() + .recipe_id, + "recipe-1", + "a removed recipe stays selected and unavailable until the user chooses a route" + ); + assert_eq!( + store + .clear_launch_recipe_selection("steam:620", target.revision) + .unwrap(), + LaunchRecipeSelectionWrite::Applied + ); + assert_eq!(store.launch_recipe_selection("steam:620").unwrap(), None); +} + +#[test] +fn runtime_resources_and_content_bindings_keep_identity_and_survive_runtime_removal() { + use gamenode_core::library::{ + ApprovedFileReference, RuntimeArgumentTemplate, RuntimeContentBinding, RuntimeExtension, + RuntimeMutation, RuntimeProvenance, RuntimeResource, + }; + + let dir = TempDir::new().unwrap(); + let path = dir.path().join("test.sqlite3"); + let db = SqliteSettingsStore::open(&path).unwrap(); + let store = db.library_store(); + db.conn() + .execute( + "INSERT INTO games (game_id, name) VALUES (72, 'Game A'), (73, 'Game B')", + [], + ) + .unwrap(); + db.conn() + .execute( + "INSERT INTO playtime_totals (account_id, entry_key, total_seconds) + VALUES ('account-1', 'steam:72', 600)", + [], + ) + .unwrap(); + db.conn() + .execute( + "INSERT INTO save_profiles (id, installation_id, revision, payload) + VALUES ('save-1', 'steam:72', 1, '{}')", + [], + ) + .unwrap(); + + let runtime = |id: &str| RuntimeResource { + id: id.into(), + name: format!("Runtime {id}"), + version: "1.0".into(), + executable: ApprovedFileReference { + approval_id: format!("approval-{id}"), + relative_path: vec!["bin".into(), "emulator".into()], + }, + platform: "linux".into(), + supported_formats: vec!["snes-rom".into()], + launch_arguments: vec![ + RuntimeArgumentTemplate::Literal("--fullscreen".into()), + RuntimeArgumentTemplate::ContentPath, + ], + revision: 1, + observed_at: 100, + provenance: Default::default(), + extensions: Default::default(), + }; + let plugin = "plugin-a/profile-1"; + let runtime_a = runtime("runtime-a"); + let runtime_b = runtime("runtime-b"); + assert_eq!( + store.save_runtime_resource(plugin, &runtime_a).unwrap(), + RuntimeMutation::Applied { revision: 1 } + ); + assert_eq!( + store.save_runtime_resource(plugin, &runtime_b).unwrap(), + RuntimeMutation::Applied { revision: 1 } + ); + // A separate runtime owner can add its own binding to the same GameNode game/content. This + // is the DeSmuME -> melonDS migration path: it does not need to delete or mutate the old + // owner's record in order to make the new runtime selectable. + let next_owner = "plugin-b/profile-1"; + let melonds = runtime("melonds"); + assert_eq!( + store.save_runtime_resource(next_owner, &melonds).unwrap(), + RuntimeMutation::Applied { revision: 1 } + ); + assert_eq!( + store.save_runtime_resource(plugin, &runtime_a).unwrap(), + RuntimeMutation::Conflict { current: 1 } + ); + let mut updated_runtime = runtime_a.clone(); + updated_runtime.revision = 2; + updated_runtime.version = "1.1".into(); + updated_runtime.provenance = RuntimeProvenance { + plugin_id: "org.example.runtime".into(), + declared_developer: "Example developer".into(), + origin: "example".into(), + publisher_fingerprint: "ab".repeat(32), + package_version: "1.1.0".into(), + package_digest: vec![5; 32], + }; + updated_runtime.extensions.insert( + "org.example.compatibility".into(), + RuntimeExtension { + schema_id: "org.example.compatibility.v1".into(), + schema_version: 1, + schema_digest: vec![3; 32], + data: serde_json::json!({"console": "snes"}), + }, + ); + assert_eq!( + store + .save_runtime_resource(plugin, &updated_runtime) + .unwrap(), + RuntimeMutation::Applied { revision: 2 } + ); + drop(store); + let reopened = SqliteSettingsStore::open(&path).unwrap(); + let store = reopened.library_store(); + let reopened_a = store + .runtime_resource(plugin, "runtime-a") + .unwrap() + .unwrap(); + assert_eq!( + reopened_a.extensions["org.example.compatibility"].schema_version, + 1 + ); + assert_eq!( + reopened_a.extensions["org.example.compatibility"].data, + serde_json::json!({"console": "snes"}) + ); + assert_eq!( + store.save_runtime_resource(plugin, &runtime_a).unwrap(), + RuntimeMutation::Conflict { current: 2 }, + "a concurrent stale writer cannot replace the reopened revision" + ); + let race_store_a = reopened.library_store(); + let race_store_b = reopened.library_store(); + let gate = std::sync::Barrier::new(2); + let (left, right) = std::thread::scope(|scope| { + let left_gate = &gate; + let right_gate = &gate; + let mut left = runtime_b.clone(); + left.revision = 2; + left.version = "writer-a".into(); + let mut right = runtime_b.clone(); + right.revision = 2; + right.version = "writer-b".into(); + let a = scope.spawn(move || { + left_gate.wait(); + race_store_a.save_runtime_resource(plugin, &left).unwrap() + }); + let b = scope.spawn(move || { + right_gate.wait(); + race_store_b.save_runtime_resource(plugin, &right).unwrap() + }); + (a.join().unwrap(), b.join().unwrap()) + }); + assert!(matches!( + (left, right), + ( + RuntimeMutation::Applied { revision: 2 }, + RuntimeMutation::Conflict { current: 2 } + ) | ( + RuntimeMutation::Conflict { current: 2 }, + RuntimeMutation::Applied { revision: 2 } + ) + )); + assert_eq!( + store + .runtime_resource("plugin-b/profile-1", "runtime-a") + .unwrap(), + None, + "runtime records are scoped to their registering plugin" + ); + assert_eq!(store.runtime_catalog_revision(plugin).unwrap(), 4); + + let binding = |game_id, content_id: &str, runtime_id: &str, path: &str| RuntimeContentBinding { + game_id, + installation_id: format!("steam:{game_id}"), + content_id: content_id.into(), + content: ApprovedFileReference { + approval_id: format!("content-approval-{content_id}"), + relative_path: vec![path.into()], + }, + content_kind: "snes-rom".into(), + runtime_id: runtime_id.into(), + supported_platforms: vec!["linux".into()], + revision: 1, + }; + let content_a_runtime_a = binding(72, "content-a", "runtime-a", "a.sfc"); + let content_a_runtime_b = binding(72, "content-a", "runtime-b", "a.sfc"); + let content_a_variant = binding(72, "content-a-patched", "runtime-a", "a-patched.sfc"); + let content_b_runtime_a = binding(73, "content-b", "runtime-a", "b.sfc"); + let desmume_owner = "plugin-desmume/profile-1"; + let desmume = runtime("desmume"); + assert_eq!( + store + .save_runtime_resource(desmume_owner, &desmume) + .unwrap(), + RuntimeMutation::Applied { revision: 1 } + ); + let desmume_binding = binding(72, "content-a", "desmume", "a.sfc"); + assert_eq!( + store + .save_runtime_content_binding(desmume_owner, &desmume_binding) + .unwrap(), + RuntimeMutation::Applied { revision: 1 } + ); + for binding in [ + &content_a_runtime_a, + &content_a_runtime_b, + &content_a_variant, + &content_b_runtime_a, + ] { + assert_eq!( + store.save_runtime_content_binding(plugin, binding).unwrap(), + RuntimeMutation::Applied { revision: 1 } + ); + } + let melonds_binding = binding(72, "content-a", "melonds", "a.sfc"); + assert_eq!( + store + .save_runtime_content_binding(next_owner, &melonds_binding) + .unwrap(), + RuntimeMutation::Applied { revision: 1 } + ); + + // The shared catalog exposes every owner's typed metadata, while the safe availability + // projection joins bindings to runtime names without a path or handle. + let shared = store.shared_runtime_resources().unwrap(); + assert_eq!(shared.len(), 4); + let stored = shared + .iter() + .find(|(owner, runtime)| owner == plugin && runtime.id == "runtime-a") + .map(|(_, runtime)| runtime) + .unwrap(); + assert_eq!(stored.provenance.plugin_id, "org.example.runtime"); + assert_eq!( + stored.extensions["org.example.compatibility"].schema_version, + 1 + ); + assert!(store.shared_runtime_catalog_revision().unwrap() >= 3); + + let private = store + .runtime_availability(Some(plugin), &["steam:72".to_owned()]) + .unwrap(); + assert_eq!(private.len(), 3); + assert!(private.iter().all( + |entry| entry.publisher_id == "org.example.runtime" || entry.runtime_id != "runtime-a" + )); + let all = store + .runtime_availability(None, &["steam:72".to_owned()]) + .unwrap(); + assert_eq!(all.len(), 5); + let melonds = all + .iter() + .find(|entry| entry.runtime_id == "melonds") + .unwrap(); + assert_eq!(melonds.runtime_name, "Runtime melonds"); + assert_eq!(melonds.content_id, "content-a"); + assert_eq!(melonds.platform, "linux"); + + // Moving a file updates its approved location under the same stable content identity. + let mut moved_content = content_a_runtime_a.clone(); + moved_content.revision = 2; + moved_content.content.relative_path = vec!["moved".into(), "renamed.sfc".into()]; + assert_eq!( + store + .save_runtime_content_binding(plugin, &moved_content) + .unwrap(), + RuntimeMutation::Applied { revision: 2 } + ); + assert_eq!(store.runtime_catalog_revision(plugin).unwrap(), 4); + let migrated = store + .runtime_content_bindings(next_owner, 72, "steam:72") + .unwrap(); + assert_eq!(migrated.len(), 1); + assert_eq!(migrated[0].content_id, "content-a"); + assert_eq!(migrated[0].runtime_id, "melonds"); + assert_eq!( + migrated[0].content.approval_id, + "content-approval-content-a" + ); + assert!( + store + .runtime_resource(desmume_owner, "desmume") + .unwrap() + .is_some() + ); + assert_eq!( + store + .runtime_content_bindings(desmume_owner, 72, "steam:72") + .unwrap()[0] + .runtime_id, + "desmume", + "the migration leaves the foreign DeSmuME runtime and binding intact" + ); + + assert_eq!( + store + .remove_runtime_resource(plugin, "runtime-a", 1) + .unwrap(), + RuntimeMutation::Conflict { current: 2 } + ); + assert_eq!( + store + .remove_runtime_resource(plugin, "runtime-a", 2) + .unwrap(), + RuntimeMutation::Applied { revision: 2 } + ); + assert_eq!(store.runtime_resource(plugin, "runtime-a").unwrap(), None); + let bindings = store + .runtime_content_bindings(plugin, 72, "steam:72") + .unwrap(); + assert_eq!( + bindings.len(), + 3, + "two content variants and both runtime choices remain" + ); + assert_eq!( + bindings + .iter() + .find(|binding| binding.runtime_id == "runtime-a") + .unwrap() + .content + .relative_path, + ["moved", "renamed.sfc"] + ); + let sibling = bindings + .iter() + .find(|binding| binding.runtime_id == "runtime-b") + .unwrap(); + assert_eq!(sibling.content_id, "content-a"); + assert_eq!(sibling.revision, 2); + assert_eq!( + sibling.content.relative_path, + ["moved", "renamed.sfc"], + "all runtime choices for one content follow its moved locator" + ); + assert!( + store + .runtime_content_bindings(plugin, 72, "steam:72") + .unwrap() + .iter() + .any(|binding| binding.runtime_id == "runtime-a"), + "migrating to another owner's runtime does not require deleting the original binding" + ); + assert!(bindings.iter().any(|binding| { + binding.content_id == "content-a-patched" + && binding.content.relative_path == ["a-patched.sfc"] + })); + assert_eq!( + store + .runtime_content_bindings(plugin, 73, "steam:73") + .unwrap() + .len(), + 1, + "one runtime can bind content from another game" + ); + assert_eq!( + store + .runtime_resources(plugin) + .unwrap() + .iter() + .map(|runtime| runtime.id.as_str()) + .collect::>(), + ["runtime-b"] + ); + assert_eq!(store.runtime_catalog_revision(plugin).unwrap(), 5); + + let games: i64 = db + .conn() + .query_row( + "SELECT COUNT(*) FROM games WHERE game_id IN (72, 73)", + [], + |row| row.get(0), + ) + .unwrap(); + let registered_game_count: i64 = db + .conn() + .query_row("SELECT COUNT(*) FROM games WHERE game_id = 72", [], |row| { + row.get(0) + }) + .unwrap(); + let history: i64 = db + .conn() + .query_row( + "SELECT total_seconds FROM playtime_totals + WHERE account_id = 'account-1' AND entry_key = 'steam:72'", + [], + |row| row.get(0), + ) + .unwrap(); + let saves: i64 = db + .conn() + .query_row( + "SELECT COUNT(*) FROM save_profiles WHERE id = 'save-1'", + [], + |row| row.get(0), + ) + .unwrap(); + assert_eq!(games, 2); + assert_eq!( + registered_game_count, 1, + "multiple runtime bindings do not duplicate the game" + ); + assert_eq!(history, 600); + assert_eq!(saves, 1); +} diff --git a/crates/platform/src/paths.rs b/crates/platform/src/paths.rs index 0d60425fe..d97aa98f8 100644 --- a/crates/platform/src/paths.rs +++ b/crates/platform/src/paths.rs @@ -118,6 +118,23 @@ impl DataPaths { self.data_dir.join(COVERS_DIR) } + /// Per-user immutable third-party plugin versions and activation pointers. + pub fn plugin_packages_dir(&self) -> PathBuf { + self.data_dir.join("plugin-packages") + } + + /// Private data of third-party plugins, one namespace per plugin and account profile. Only + /// the host reads or reveals this location; the plugin API never accepts or returns it. + pub fn plugin_data_dir(&self) -> PathBuf { + self.data_dir.join("plugin-data") + } + + /// The host-owned durable public shared-data pool. Separate from the settings database and + /// from private plugin storage; only the host reads or reveals its location. + pub fn plugin_shared_data_file(&self) -> PathBuf { + self.data_dir.join(crate::plugin_shared_data::FILE_NAME) + } + pub fn private_dir(&self) -> PathBuf { self.data_dir.join(PRIVATE_DIR) } @@ -226,8 +243,17 @@ mod tests { paths.tool_backups_dir(), paths.private_dir().join("tool-backups") ); + assert_eq!( + paths.plugin_shared_data_file(), + paths.data_dir().join("plugin-shared-data.gnpersistence") + ); assert!(paths.tools_cache_dir().starts_with(paths.data_dir())); assert!(paths.tool_backups_dir().starts_with(paths.data_dir())); + assert!( + paths + .plugin_shared_data_file() + .starts_with(paths.data_dir()) + ); } #[test] diff --git a/crates/platform/src/plugin_artwork.rs b/crates/platform/src/plugin_artwork.rs new file mode 100644 index 000000000..29daf7698 --- /dev/null +++ b/crates/platform/src/plugin_artwork.rs @@ -0,0 +1,309 @@ +//! Cover images a provider's plugin sets for its own library entries. +//! +//! A plugin hands over encoded bytes it got from anywhere, so nothing about them is trusted. +//! [`prepare`] is the only door: it bounds the encoded size, identifies the format from the +//! bytes themselves (the declared media type must agree), rejects animations, reads the +//! dimensions from the header and refuses oversized pixel counts *before* decoding, then decodes +//! under an allocation limit, applies the EXIF orientation, shrinks the picture to the cover size +//! and encodes it again. Metadata, trailing data and anything the decoder skipped never reach the +//! disk. The work is CPU-bound: callers run it on a blocking worker, never on the UI thread or an +//! async executor. +//! +//! A prepared cover is stored under a name that only its entry owns, derived from the entry and +//! the content, so storing the same picture twice is the same file and replacing it never touches +//! another entry's cover. + +use std::fs::{self, File}; +use std::io::{self, Cursor, Read}; +use std::path::Path; + +use image::codecs::jpeg::JpegEncoder; +use image::codecs::png::PngEncoder; +use image::imageops::FilterType; +use image::{DynamicImage, ImageDecoder, ImageFormat, ImageReader, Limits}; +use sha2::{Digest, Sha256}; + +use crate::covers::write_named; + +/// The largest encoded image accepted. The host's messages are capped at 8 MiB; this leaves room +/// for the request around the bytes. +pub const MAX_INPUT_BYTES: usize = 4 * 1024 * 1024; +/// The most pixels a source image may have (4096 x 4096) before it is decoded. +pub const MAX_SOURCE_PIXELS: u64 = 16 * 1024 * 1024; +/// The longest side a source image may have, whatever its pixel count. +pub const MAX_SOURCE_SIDE: u32 = 8192; +/// What decoding may allocate: a 16 megapixel RGBA16 image is 128 MiB. +const MAX_DECODE_BYTES: u64 = 128 * 1024 * 1024; +/// A cover is shrunk to fit in this box (2:3), keeping its proportions and never enlarged. +pub const COVER_MAX_WIDTH: u32 = 600; +pub const COVER_MAX_HEIGHT: u32 = 900; +const JPEG_QUALITY: u8 = 88; + +/// Why an image was refused. +#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)] +pub enum ArtworkError { + #[error("the image is larger than {MAX_INPUT_BYTES} bytes")] + TooLarge, + #[error("the image is not a PNG, JPEG or WebP picture")] + UnsupportedFormat, + #[error("the declared media type does not match the image")] + MediaTypeMismatch, + #[error("animated images are not supported")] + Animated, + #[error("the image has more than {MAX_SOURCE_PIXELS} pixels or a side over {MAX_SOURCE_SIDE}")] + TooManyPixels, + #[error("the image is damaged")] + Malformed, +} + +/// A decoded, shrunk and re-encoded cover, ready to store. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Prepared { + pub bytes: Vec, + /// `image/png` when the picture has transparency, else `image/jpeg`. + pub media_type: &'static str, + pub width: u32, + pub height: u32, +} + +/// The format of `bytes`, judged by their signature alone. +fn sniff(bytes: &[u8]) -> Option { + if bytes.starts_with(b"\x89PNG\r\n\x1a\n") { + Some(ImageFormat::Png) + } else if bytes.starts_with(&[0xFF, 0xD8, 0xFF]) { + Some(ImageFormat::Jpeg) + } else if bytes.len() >= 12 && &bytes[..4] == b"RIFF" && &bytes[8..12] == b"WEBP" { + Some(ImageFormat::WebP) + } else { + None + } +} + +fn declared(format: ImageFormat) -> &'static str { + match format { + ImageFormat::Png => "image/png", + ImageFormat::Jpeg => "image/jpeg", + _ => "image/webp", + } +} + +/// Whether a PNG carries an animation control chunk (APNG) before its image data. +fn png_is_animated(bytes: &[u8]) -> bool { + let mut at = 8; + while let (Some(length), Some(kind)) = ( + bytes + .get(at..at + 4) + .and_then(|b| <[u8; 4]>::try_from(b).ok()), + bytes.get(at + 4..at + 8), + ) { + match kind { + b"acTL" => return true, + b"IDAT" | b"IEND" => return false, + _ => {} + } + // length + type + data + crc + let Some(next) = (u32::from_be_bytes(length) as usize) + .checked_add(12) + .and_then(|step| at.checked_add(step)) + else { + return false; + }; + at = next; + } + false +} + +/// Whether a WebP file is animated: an extended header with the animation flag, or frame data. +fn webp_is_animated(bytes: &[u8]) -> bool { + let mut at = 12; + while let (Some(kind), Some(length)) = ( + bytes.get(at..at + 4), + bytes + .get(at + 4..at + 8) + .and_then(|b| <[u8; 4]>::try_from(b).ok()), + ) { + match kind { + b"ANIM" | b"ANMF" => return true, + b"VP8X" => { + if bytes.get(at + 8).is_some_and(|flags| flags & 0x02 != 0) { + return true; + } + } + b"VP8 " | b"VP8L" => return false, + _ => {} + } + let padded = (u32::from_le_bytes(length) as usize).saturating_add(1) & !1; + let Some(next) = at.checked_add(8).and_then(|head| head.checked_add(padded)) else { + return false; + }; + at = next; + } + false +} + +fn limits() -> Limits { + let mut limits = Limits::default(); + limits.max_image_width = Some(MAX_SOURCE_SIDE); + limits.max_image_height = Some(MAX_SOURCE_SIDE); + limits.max_alloc = Some(MAX_DECODE_BYTES); + limits +} + +/// Validates, decodes, shrinks and re-encodes `bytes` as a cover. `media_type` is what the +/// caller declared; it must name the format the bytes really are. Blocking and CPU-heavy. +pub fn prepare(bytes: &[u8], media_type: &str) -> Result { + if bytes.len() > MAX_INPUT_BYTES { + return Err(ArtworkError::TooLarge); + } + let format = sniff(bytes).ok_or(ArtworkError::UnsupportedFormat)?; + if !media_type.trim().eq_ignore_ascii_case(declared(format)) { + return Err(ArtworkError::MediaTypeMismatch); + } + let animated = match format { + ImageFormat::Png => png_is_animated(bytes), + ImageFormat::WebP => webp_is_animated(bytes), + _ => false, + }; + if animated { + return Err(ArtworkError::Animated); + } + + let mut decoder = ImageReader::with_format(Cursor::new(bytes), format) + .into_decoder() + .map_err(|_| ArtworkError::Malformed)?; + let (width, height) = decoder.dimensions(); + if width == 0 + || height == 0 + || width > MAX_SOURCE_SIDE + || height > MAX_SOURCE_SIDE + || u64::from(width) * u64::from(height) > MAX_SOURCE_PIXELS + { + return Err(ArtworkError::TooManyPixels); + } + decoder + .set_limits(limits()) + .map_err(|_| ArtworkError::TooManyPixels)?; + let orientation = decoder + .orientation() + .unwrap_or(image::metadata::Orientation::NoTransforms); + let mut picture = DynamicImage::from_decoder(decoder).map_err(|_| ArtworkError::Malformed)?; + picture.apply_orientation(orientation); + + if picture.width() > COVER_MAX_WIDTH || picture.height() > COVER_MAX_HEIGHT { + picture = picture.resize(COVER_MAX_WIDTH, COVER_MAX_HEIGHT, FilterType::Lanczos3); + } + let (width, height) = (picture.width(), picture.height()); + + let transparent = picture.color().has_alpha() + && picture + .to_rgba8() + .pixels() + .any(|pixel| pixel.0[3] < u8::MAX); + let mut out = Vec::new(); + let media_type = if transparent { + picture + .write_with_encoder(PngEncoder::new(&mut out)) + .map_err(|_| ArtworkError::Malformed)?; + "image/png" + } else { + DynamicImage::ImageRgb8(picture.to_rgb8()) + .write_with_encoder(JpegEncoder::new_with_quality(&mut out, JPEG_QUALITY)) + .map_err(|_| ArtworkError::Malformed)?; + "image/jpeg" + }; + Ok(Prepared { + bytes: out, + media_type, + width, + height, + }) +} + +fn hex_prefix(bytes: &[u8]) -> String { + use std::fmt::Write; + bytes.iter().take(8).fold(String::new(), |mut text, byte| { + let _ = write!(text, "{byte:02x}"); + text + }) +} + +/// The file name a prepared cover is stored under: `plugin--.`. Only this +/// entry ever uses it, and the same picture always has the same name. +pub fn file_name(entry_key: &str, prepared: &Prepared) -> String { + let entry = hex_prefix(&Sha256::digest(entry_key.as_bytes())); + let content = hex_prefix(&Sha256::digest(&prepared.bytes)); + let extension = if prepared.media_type == "image/png" { + "png" + } else { + "jpg" + }; + format!("plugin-{entry}-{content}.{extension}") +} + +/// The media type of a stored cover, from its file name. +pub fn media_type_of(file: &str) -> &'static str { + match file.rsplit('.').next() { + Some("png") => "image/png", + Some("webp") => "image/webp", + _ => "image/jpeg", + } +} + +/// Where a stored cover goes: written atomically into `dir`. Returns whether the file was +/// already there (so a refused write need not delete it). +pub fn store(dir: &Path, name: &str, prepared: &Prepared) -> io::Result { + let existed = dir.join(name).is_file(); + write_named(dir, name, &prepared.bytes)?; + Ok(existed) +} + +/// Deletes a stored cover. Best effort: a leftover file is harmless and never read again. +pub fn remove(dir: &Path, name: &str) { + if is_plain_name(name) { + let _ = fs::remove_file(dir.join(name)); + } +} + +/// A file name with no directory part. +fn is_plain_name(name: &str) -> bool { + !name.is_empty() + && !name.starts_with('.') + && name + .bytes() + .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.')) +} + +/// The ways reading a stored cover back can fail. +#[derive(Debug, PartialEq, Eq)] +pub enum ReadError { + /// The file is missing, unreadable or not a plain name. + Unavailable, + /// The file is larger than the caller allows. + TooLarge, +} + +/// Reads `dir/name`, refusing more than `max_bytes`. Blocking. +pub fn read(dir: &Path, name: &str, max_bytes: u64) -> Result, ReadError> { + if !is_plain_name(name) { + return Err(ReadError::Unavailable); + } + let file = File::open(dir.join(name)).map_err(|_| ReadError::Unavailable)?; + let metadata = file.metadata().map_err(|_| ReadError::Unavailable)?; + if !metadata.is_file() { + return Err(ReadError::Unavailable); + } + if metadata.len() > max_bytes { + return Err(ReadError::TooLarge); + } + let mut bytes = Vec::new(); + file.take(max_bytes.saturating_add(1)) + .read_to_end(&mut bytes) + .map_err(|_| ReadError::Unavailable)?; + if bytes.len() as u64 > max_bytes { + return Err(ReadError::TooLarge); + } + Ok(bytes) +} + +#[cfg(test)] +mod tests; diff --git a/crates/platform/src/plugin_artwork/tests.rs b/crates/platform/src/plugin_artwork/tests.rs new file mode 100644 index 000000000..de3fa6050 --- /dev/null +++ b/crates/platform/src/plugin_artwork/tests.rs @@ -0,0 +1,331 @@ +use super::*; +use image::codecs::webp::WebPEncoder; +use image::{ExtendedColorType, ImageEncoder, Rgb, RgbImage, Rgba, RgbaImage}; +use tempfile::TempDir; + +fn png_of(image: &DynamicImage) -> Vec { + let mut out = Vec::new(); + image.write_with_encoder(PngEncoder::new(&mut out)).unwrap(); + out +} + +fn jpeg_of(image: &RgbImage) -> Vec { + let mut out = Vec::new(); + DynamicImage::ImageRgb8(image.clone()) + .write_with_encoder(JpegEncoder::new(&mut out)) + .unwrap(); + out +} + +fn webp_of(image: &RgbaImage) -> Vec { + let mut out = Vec::new(); + WebPEncoder::new_lossless(&mut out) + .write_image( + image.as_raw(), + image.width(), + image.height(), + ExtendedColorType::Rgba8, + ) + .unwrap(); + out +} + +fn opaque(width: u32, height: u32) -> DynamicImage { + DynamicImage::ImageRgb8(RgbImage::from_pixel(width, height, Rgb([200, 30, 30]))) +} + +fn decoded(prepared: &Prepared) -> DynamicImage { + image::load_from_memory(&prepared.bytes).unwrap() +} + +#[test] +fn a_large_picture_is_shrunk_to_fit_the_cover_box_keeping_its_proportions() { + // 1200 x 1200 is limited by the width: 600 x 600. + let square = prepare(&png_of(&opaque(1200, 1200)), "image/png").unwrap(); + assert_eq!((square.width, square.height), (600, 600)); + // 1800 x 3600 is limited by the height: 450 x 900. + let tall = prepare(&png_of(&opaque(1800, 3600)), "image/png").unwrap(); + assert_eq!((tall.width, tall.height), (450, 900)); + let out = decoded(&tall); + assert_eq!((out.width(), out.height()), (450, 900)); +} + +#[test] +fn a_small_picture_is_not_enlarged() { + let small = prepare(&png_of(&opaque(120, 180)), "image/png").unwrap(); + assert_eq!((small.width, small.height), (120, 180)); +} + +#[test] +fn an_opaque_picture_is_stored_as_jpeg_and_a_transparent_one_as_png() { + let flat = prepare(&png_of(&opaque(64, 64)), "image/png").unwrap(); + assert_eq!(flat.media_type, "image/jpeg"); + assert!(flat.bytes.starts_with(&[0xFF, 0xD8, 0xFF])); + + let mut glass = RgbaImage::from_pixel(64, 64, Rgba([10, 20, 30, 255])); + glass.put_pixel(3, 3, Rgba([10, 20, 30, 0])); + let see_through = prepare(&png_of(&DynamicImage::ImageRgba8(glass)), "image/png").unwrap(); + assert_eq!(see_through.media_type, "image/png"); + assert_eq!(decoded(&see_through).to_rgba8().get_pixel(3, 3).0[3], 0); + + // An alpha channel that is fully opaque costs nothing. + let solid = RgbaImage::from_pixel(8, 8, Rgba([1, 2, 3, 255])); + let kept = prepare(&png_of(&DynamicImage::ImageRgba8(solid)), "image/png").unwrap(); + assert_eq!(kept.media_type, "image/jpeg"); +} + +#[test] +fn jpeg_and_webp_pictures_are_accepted_and_the_media_type_is_case_insensitive() { + let jpeg = prepare(&jpeg_of(&RgbImage::new(40, 60)), " IMAGE/JPEG ").unwrap(); + assert_eq!((jpeg.width, jpeg.height), (40, 60)); + let webp = prepare( + &webp_of(&RgbaImage::from_pixel(40, 60, Rgba([9, 9, 9, 255]))), + "image/webp", + ) + .unwrap(); + assert_eq!((webp.width, webp.height), (40, 60)); +} + +#[test] +fn what_the_bytes_are_decides_not_what_the_caller_says() { + let png = png_of(&opaque(8, 8)); + assert_eq!( + prepare(&png, "image/jpeg"), + Err(ArtworkError::MediaTypeMismatch) + ); + assert_eq!(prepare(&png, ""), Err(ArtworkError::MediaTypeMismatch)); + assert_eq!( + prepare(&png, "image/svg+xml"), + Err(ArtworkError::MediaTypeMismatch) + ); +} + +#[test] +fn things_that_are_not_png_jpeg_or_webp_are_refused() { + for bytes in [ + b"".as_slice(), + b"GIF89a\x01\x00\x01\x00".as_slice(), + b"BM\x00\x00\x00\x00".as_slice(), + b"#!/bin/sh\necho hi\n".as_slice(), + b"".as_slice(), + ] { + assert_eq!( + prepare(bytes, "image/png"), + Err(ArtworkError::UnsupportedFormat), + "{bytes:?}" + ); + } +} + +#[test] +fn more_bytes_than_the_cap_are_refused_before_anything_else() { + let mut big = b"\x89PNG\r\n\x1a\n".to_vec(); + big.resize(MAX_INPUT_BYTES + 1, 0); + assert_eq!(prepare(&big, "image/png"), Err(ArtworkError::TooLarge)); + // Exactly the cap is not "too large" (it is merely damaged here). + big.truncate(MAX_INPUT_BYTES); + assert_eq!(prepare(&big, "image/png"), Err(ArtworkError::Malformed)); +} + +#[test] +fn a_picture_with_too_many_pixels_is_refused_without_decoding_it() { + // 4097 x 4097 gray pixels compress to a few KiB but would need 16 MiB of pixels. + let heavy = DynamicImage::ImageLuma8(image::GrayImage::new(4097, 4097)); + let bytes = png_of(&heavy); + assert!(bytes.len() < MAX_INPUT_BYTES); + assert_eq!( + prepare(&bytes, "image/png"), + Err(ArtworkError::TooManyPixels) + ); + + // A very long thin strip is under the pixel count but over the side limit. + let strip = png_of(&DynamicImage::ImageLuma8(image::GrayImage::new( + MAX_SOURCE_SIDE + 1, + 1, + ))); + assert_eq!( + prepare(&strip, "image/png"), + Err(ArtworkError::TooManyPixels) + ); + + // The limit itself is fine. + let edge = png_of(&DynamicImage::ImageLuma8(image::GrayImage::new(4096, 4096))); + assert!(prepare(&edge, "image/png").is_ok()); +} + +#[test] +fn damaged_pictures_are_refused() { + let png = png_of(&opaque(64, 64)); + assert_eq!( + prepare(&png[..png.len() / 2], "image/png"), + Err(ArtworkError::Malformed) + ); + let jpeg = jpeg_of(&RgbImage::new(64, 64)); + assert_eq!( + prepare(&jpeg[..jpeg.len() / 2], "image/jpeg"), + Err(ArtworkError::Malformed) + ); + assert_eq!( + prepare(b"\xFF\xD8\xFFnot really a jpeg", "image/jpeg"), + Err(ArtworkError::Malformed) + ); + assert_eq!( + prepare(b"RIFF\x04\x00\x00\x00WEBP", "image/webp"), + Err(ArtworkError::Malformed) + ); +} + +fn with_chunk_after_header(png: &[u8], kind: &[u8; 4], data: &[u8]) -> Vec { + // signature (8) + IHDR chunk (4 + 4 + 13 + 4) + let split = 8 + 25; + let mut out = png[..split].to_vec(); + out.extend((data.len() as u32).to_be_bytes()); + out.extend(kind); + out.extend(data); + out.extend([0, 0, 0, 0]); // the checksum is never reached: the image is refused first + out.extend(&png[split..]); + out +} + +#[test] +fn animated_pictures_are_refused() { + let apng = with_chunk_after_header(&png_of(&opaque(8, 8)), b"acTL", &[0, 0, 0, 2, 0, 0, 0, 0]); + assert_eq!(prepare(&apng, "image/png"), Err(ArtworkError::Animated)); + + // A still image with an unrelated ancillary chunk stays fine. + let tagged = with_chunk_after_header(&png_of(&opaque(8, 8)), b"tEXt", b"k\0v"); + assert!(!png_is_animated(&tagged)); + + let mut webp = b"RIFF\x1a\x00\x00\x00WEBPVP8X\x0a\x00\x00\x00".to_vec(); + webp.extend([0x02, 0, 0, 0, 7, 0, 0, 7, 0, 0]); + assert_eq!(prepare(&webp, "image/webp"), Err(ArtworkError::Animated)); + let mut frames = b"RIFF\x1a\x00\x00\x00WEBPANIM\x06\x00\x00\x00".to_vec(); + frames.extend([0; 6]); + assert_eq!(prepare(&frames, "image/webp"), Err(ArtworkError::Animated)); +} + +#[test] +fn hostile_chunk_lengths_do_not_loop_or_overflow() { + let mut png = b"\x89PNG\r\n\x1a\n".to_vec(); + png.extend(u32::MAX.to_be_bytes()); + png.extend(b"zzzz"); + assert!(!png_is_animated(&png)); + let mut webp = b"RIFF\x00\x00\x00\x00WEBPzzzz".to_vec(); + webp.extend(u32::MAX.to_le_bytes()); + assert!(!webp_is_animated(&webp)); +} + +#[test] +fn trailing_data_and_metadata_never_survive() { + let mut png = png_of(&opaque(32, 32)); + png.extend(b"-----SECRET TRAILER-----"); + let prepared = prepare(&png, "image/png").unwrap(); + assert!(!prepared.bytes.windows(6).any(|window| window == b"SECRET")); +} + +#[test] +fn a_cover_has_a_name_only_its_entry_and_content_decide() { + let a = prepare(&png_of(&opaque(32, 32)), "image/png").unwrap(); + let b = prepare(&png_of(&opaque(48, 32)), "image/png").unwrap(); + let name = file_name("steam:1", &a); + assert_eq!( + name, + file_name("steam:1", &a), + "the same picture, the same file" + ); + assert_ne!( + name, + file_name("steam:1", &b), + "another picture, another file" + ); + assert_ne!( + name, + file_name("steam:2", &a), + "another entry never shares a file" + ); + assert!( + name.starts_with("plugin-") && name.ends_with(".jpg"), + "{name}" + ); + assert!(is_plain_name(&name)); + assert_eq!(media_type_of(&name), "image/jpeg"); + assert_eq!(media_type_of("plugin-x-y.png"), "image/png"); +} + +#[test] +fn a_stored_cover_reads_back_within_the_bound() { + let dir = TempDir::new().unwrap(); + let covers = dir.path().join("covers"); + let prepared = prepare(&png_of(&opaque(32, 32)), "image/png").unwrap(); + let name = file_name("steam:1", &prepared); + + assert!(!store(&covers, &name, &prepared).unwrap(), "first write"); + assert!(store(&covers, &name, &prepared).unwrap(), "already there"); + let bytes = read(&covers, &name, 1 << 20).unwrap(); + assert_eq!(bytes, prepared.bytes); + assert_eq!( + read(&covers, &name, bytes.len() as u64 - 1), + Err(ReadError::TooLarge) + ); + assert_eq!(read(&covers, &name, bytes.len() as u64), Ok(bytes)); + + remove(&covers, &name); + assert_eq!(read(&covers, &name, 1 << 20), Err(ReadError::Unavailable)); +} + +#[test] +fn only_plain_names_are_read_or_removed() { + let dir = TempDir::new().unwrap(); + let covers = dir.path().join("covers"); + fs::create_dir_all(&covers).unwrap(); + let outside = dir.path().join("secret.txt"); + fs::write(&outside, b"secret").unwrap(); + for name in [ + "../secret.txt", + "/etc/passwd", + "a/b.jpg", + ".hidden", + "", + "..", + "x\\y.jpg", + ] { + assert_eq!( + read(&covers, name, 1 << 20), + Err(ReadError::Unavailable), + "{name}" + ); + remove(&covers, name); + } + assert!(outside.exists()); + // A folder is not a cover. + fs::create_dir(covers.join("folder.jpg")).unwrap(); + assert_eq!( + read(&covers, "folder.jpg", 1 << 20), + Err(ReadError::Unavailable) + ); +} + +/// `jpeg` with an EXIF block that says "rotate 90 degrees clockwise to display" (orientation 6). +fn rotated_jpeg(jpeg: &[u8]) -> Vec { + let mut exif = vec![0xFF, 0xE1, 0x00, 0x22]; + exif.extend(b"Exif\0\0"); + exif.extend([b'I', b'I', 0x2A, 0, 8, 0, 0, 0]); + exif.extend([1, 0]); + exif.extend([0x12, 0x01, 3, 0, 1, 0, 0, 0, 6, 0, 0, 0]); + exif.extend([0, 0, 0, 0]); + let mut out = jpeg[..2].to_vec(); + out.extend(exif); + out.extend(&jpeg[2..]); + out +} + +#[test] +fn the_orientation_a_camera_recorded_is_applied_before_the_metadata_is_dropped() { + let wide = rotated_jpeg(&jpeg_of(&RgbImage::new(80, 40))); + let prepared = prepare(&wide, "image/jpeg").unwrap(); + assert_eq!((prepared.width, prepared.height), (40, 80)); + assert!( + !prepared.bytes.windows(4).any(|w| w == b"Exif"), + "the stored cover carries no EXIF" + ); +} diff --git a/crates/platform/src/plugin_bundle_db.rs b/crates/platform/src/plugin_bundle_db.rs new file mode 100644 index 000000000..cc8f21f60 --- /dev/null +++ b/crates/platform/src/plugin_bundle_db.rs @@ -0,0 +1,911 @@ +//! SQLite mapping between installed plugin bundles and their component packages. +//! +//! A bundle only groups packages that keep their own identity, grants and lifecycle. Component +//! packages, activation and payloads stay in the package registry and their existing stores; this +//! module remembers which installed plugin ids came from which bundle. Every write is one +//! transaction, and all methods perform blocking SQLite work that belongs on a worker thread. + +use std::collections::BTreeSet; +use std::sync::{Arc, Mutex}; + +use gamenode_core::ports::StorageError; +use rusqlite::{Connection, OptionalExtension, params}; + +/// One component of an installed bundle. +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct BundleComponentRecord { + /// The component's own plugin id; it remains a normal installed package. + pub plugin_id: String, + /// `provider` or `extension`, exactly as declared by the component package. + pub kind: String, + /// Lowercase SHA-256 of the component archive declared by `bundle.json`. + pub component_sha256: String, + /// The component package version, independent of the bundle version. + pub package_version: String, +} + +/// An installed bundle and every component it maps to. +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct BundleRecord { + pub bundle_id: String, + pub name: String, + pub version: String, + pub publisher_fingerprint: String, + /// Lowercase SHA-256 of the exact signed `bundle.json` bytes. + pub manifest_sha256: String, + /// Unix seconds when the mapping was recorded. + pub installed_at: i64, + pub components: Vec, +} + +/// The bundle mapping on the shared application database connection. Cloning shares that one +/// connection, so every handle observes the same rows. +#[derive(Clone)] +pub struct SqlitePluginBundleStore { + conn: Arc>, +} + +fn failed(error: impl std::fmt::Display) -> StorageError { + StorageError::Failed(error.to_string()) +} + +fn invalid(message: &str) -> StorageError { + StorageError::Failed(message.to_owned()) +} + +fn validate_bundle(bundle: &BundleRecord) -> Result<(), StorageError> { + if [ + bundle.bundle_id.as_str(), + bundle.name.as_str(), + bundle.version.as_str(), + bundle.publisher_fingerprint.as_str(), + bundle.manifest_sha256.as_str(), + ] + .iter() + .any(|value| value.is_empty()) + { + return Err(invalid("a bundle record has an empty identity field")); + } + if bundle.installed_at < 0 { + return Err(invalid("a bundle record has a negative install time")); + } + if bundle.components.is_empty() { + return Err(invalid("a bundle record has no components")); + } + let mut plugin_ids = BTreeSet::new(); + for component in &bundle.components { + if component.plugin_id.is_empty() + || component.kind.is_empty() + || component.component_sha256.is_empty() + || component.package_version.is_empty() + { + return Err(invalid("a bundle component has an empty identity field")); + } + if !matches!(component.kind.as_str(), "provider" | "extension") { + return Err(invalid( + "a bundle component kind is not provider or extension", + )); + } + if !plugin_ids.insert(component.plugin_id.as_str()) { + return Err(invalid("a bundle record repeats a component plugin id")); + } + } + Ok(()) +} + +fn read(conn: &Connection, bundle_id: &str) -> Result, StorageError> { + let bundle = conn + .query_row( + "SELECT bundle_id, name, version, publisher_fingerprint, manifest_sha256, installed_at + FROM plugin_bundles WHERE bundle_id = ?1", + [bundle_id], + |row| { + Ok(BundleRecord { + bundle_id: row.get(0)?, + name: row.get(1)?, + version: row.get(2)?, + publisher_fingerprint: row.get(3)?, + manifest_sha256: row.get(4)?, + installed_at: row.get(5)?, + components: Vec::new(), + }) + }, + ) + .optional() + .map_err(failed)?; + let Some(mut bundle) = bundle else { + return Ok(None); + }; + let mut statement = conn + .prepare( + "SELECT plugin_id, kind, component_sha256, package_version + FROM plugin_bundle_components WHERE bundle_id = ?1 ORDER BY plugin_id", + ) + .map_err(failed)?; + let rows = statement + .query_map([bundle_id], |row| { + Ok(BundleComponentRecord { + plugin_id: row.get(0)?, + kind: row.get(1)?, + component_sha256: row.get(2)?, + package_version: row.get(3)?, + }) + }) + .map_err(failed)?; + bundle.components = rows.collect::, _>>().map_err(failed)?; + Ok(Some(bundle)) +} + +fn read_history( + conn: &Connection, + bundle_id: &str, + version: &str, +) -> Result, StorageError> { + let bundle = conn + .query_row( + "SELECT bundle_id, name, version, publisher_fingerprint, manifest_sha256, installed_at + FROM plugin_bundle_history WHERE bundle_id = ?1 AND version = ?2", + params![bundle_id, version], + |row| { + Ok(BundleRecord { + bundle_id: row.get(0)?, + name: row.get(1)?, + version: row.get(2)?, + publisher_fingerprint: row.get(3)?, + manifest_sha256: row.get(4)?, + installed_at: row.get(5)?, + components: Vec::new(), + }) + }, + ) + .optional() + .map_err(failed)?; + let Some(mut bundle) = bundle else { + return Ok(None); + }; + let mut statement = conn + .prepare( + "SELECT plugin_id, kind, component_sha256, package_version + FROM plugin_bundle_history_components + WHERE bundle_id = ?1 AND version = ?2 + ORDER BY plugin_id", + ) + .map_err(failed)?; + let rows = statement + .query_map(params![bundle_id, version], |row| { + Ok(BundleComponentRecord { + plugin_id: row.get(0)?, + kind: row.get(1)?, + component_sha256: row.get(2)?, + package_version: row.get(3)?, + }) + }) + .map_err(failed)?; + bundle.components = rows.collect::, _>>().map_err(failed)?; + Ok(Some(bundle)) +} + +/// Copies one mapping into history, replacing an older archived copy of the same version. The +/// current mapping is never modified here. +fn archive_bundle( + conn: &Connection, + bundle: &BundleRecord, + archived_at: i64, +) -> Result<(), StorageError> { + conn.execute( + "INSERT OR REPLACE INTO plugin_bundle_history + (bundle_id, version, name, publisher_fingerprint, manifest_sha256, installed_at, archived_at) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)", + params![ + bundle.bundle_id, + bundle.version, + bundle.name, + bundle.publisher_fingerprint, + bundle.manifest_sha256, + bundle.installed_at, + archived_at, + ], + ) + .map_err(failed)?; + conn.execute( + "DELETE FROM plugin_bundle_history_components WHERE bundle_id = ?1 AND version = ?2", + params![bundle.bundle_id, bundle.version], + ) + .map_err(failed)?; + let mut insert = conn + .prepare( + "INSERT INTO plugin_bundle_history_components + (bundle_id, version, plugin_id, kind, component_sha256, package_version) + VALUES (?1, ?2, ?3, ?4, ?5, ?6)", + ) + .map_err(failed)?; + for component in &bundle.components { + insert + .execute(params![ + bundle.bundle_id, + bundle.version, + component.plugin_id, + component.kind, + component.component_sha256, + component.package_version, + ]) + .map_err(failed)?; + } + Ok(()) +} + +/// Replaces the current component rows of an existing bundle row. The bundle row itself is +/// updated in place so its identity stays the primary key. +fn replace_components(conn: &Connection, bundle: &BundleRecord) -> Result<(), StorageError> { + conn.execute( + "DELETE FROM plugin_bundle_components WHERE bundle_id = ?1", + [&bundle.bundle_id], + ) + .map_err(failed)?; + let mut insert = conn + .prepare( + "INSERT INTO plugin_bundle_components + (bundle_id, plugin_id, kind, component_sha256, package_version) + VALUES (?1, ?2, ?3, ?4, ?5)", + ) + .map_err(failed)?; + for component in &bundle.components { + insert + .execute(params![ + bundle.bundle_id, + component.plugin_id, + component.kind, + component.component_sha256, + component.package_version, + ]) + .map_err(failed)?; + } + Ok(()) +} + +fn update_bundle_row(conn: &Connection, bundle: &BundleRecord) -> Result<(), StorageError> { + let changed = conn + .execute( + "UPDATE plugin_bundles + SET name = ?2, version = ?3, publisher_fingerprint = ?4, manifest_sha256 = ?5, + installed_at = ?6 + WHERE bundle_id = ?1", + params![ + bundle.bundle_id, + bundle.name, + bundle.version, + bundle.publisher_fingerprint, + bundle.manifest_sha256, + bundle.installed_at, + ], + ) + .map_err(failed)?; + if changed != 1 { + return Err(invalid("the bundle mapping no longer exists")); + } + Ok(()) +} + +impl SqlitePluginBundleStore { + pub(crate) fn new(conn: Arc>) -> Self { + Self { conn } + } + + fn conn(&self) -> std::sync::MutexGuard<'_, Connection> { + crate::db::lock(&self.conn) + } + + /// Records a bundle and all its components in one transaction. A duplicate bundle id, a + /// component already mapped to another bundle, or an invalid record changes nothing. + pub fn record_bundle(&self, bundle: &BundleRecord) -> Result<(), StorageError> { + validate_bundle(bundle)?; + let mut conn = self.conn(); + let tx = conn.transaction().map_err(failed)?; + tx.execute( + "INSERT INTO plugin_bundles + (bundle_id, name, version, publisher_fingerprint, manifest_sha256, installed_at) + VALUES (?1, ?2, ?3, ?4, ?5, ?6)", + params![ + bundle.bundle_id, + bundle.name, + bundle.version, + bundle.publisher_fingerprint, + bundle.manifest_sha256, + bundle.installed_at, + ], + ) + .map_err(failed)?; + { + let mut insert = tx + .prepare( + "INSERT INTO plugin_bundle_components + (bundle_id, plugin_id, kind, component_sha256, package_version) + VALUES (?1, ?2, ?3, ?4, ?5)", + ) + .map_err(failed)?; + for component in &bundle.components { + insert + .execute(params![ + bundle.bundle_id, + component.plugin_id, + component.kind, + component.component_sha256, + component.package_version, + ]) + .map_err(failed)?; + } + } + tx.commit().map_err(failed) + } + + /// Replaces an installed bundle's version, manifest hash, install time and component rows in + /// one transaction, archiving the previous mapping first. The previous record is returned so a + /// caller that has just activated new component versions can restore them if a later step + /// fails. A missing mapping and an unchanged version both change nothing. + pub fn update_bundle( + &self, + bundle: &BundleRecord, + archived_at: i64, + ) -> Result { + validate_bundle(bundle)?; + if archived_at < 0 { + return Err(invalid("a bundle archive time is negative")); + } + let mut conn = self.conn(); + let tx = conn.transaction().map_err(failed)?; + let previous = read(&tx, &bundle.bundle_id)? + .ok_or_else(|| invalid("the bundle mapping no longer exists"))?; + if previous.version == bundle.version + && previous.manifest_sha256 == bundle.manifest_sha256 + && previous.components == bundle.components + { + return Err(invalid("the bundle update does not change the mapping")); + } + archive_bundle(&tx, &previous, archived_at)?; + update_bundle_row(&tx, bundle)?; + replace_components(&tx, bundle)?; + tx.commit().map_err(failed)?; + Ok(previous) + } + + /// Versions of this bundle that are archived and can be restored, most recently archived + /// first. The current version is never included. + pub fn previous_versions(&self, bundle_id: &str) -> Result, StorageError> { + let conn = self.conn(); + let mut statement = conn + .prepare( + "SELECT version FROM plugin_bundle_history + WHERE bundle_id = ?1 ORDER BY archived_at DESC, version DESC", + ) + .map_err(failed)?; + statement + .query_map([bundle_id], |row| row.get::<_, String>(0)) + .map_err(failed)? + .collect::, _>>() + .map_err(failed) + } + + /// One archived mapping of this bundle, if it exists. + pub fn previous_bundle( + &self, + bundle_id: &str, + version: &str, + ) -> Result, StorageError> { + read_history(&self.conn(), bundle_id, version) + } + + /// Makes an archived version current again in one transaction: the current mapping is archived + /// and the selected history entry is removed. Returns the restored record, or `None` when that + /// version is not archived. Component packages, grants and activation are untouched here; the + /// caller re-activates the restored versions and revalidates grants. + pub fn restore_bundle_version( + &self, + bundle_id: &str, + version: &str, + archived_at: i64, + ) -> Result, StorageError> { + if archived_at < 0 { + return Err(invalid("a bundle archive time is negative")); + } + let mut conn = self.conn(); + let tx = conn.transaction().map_err(failed)?; + let current = + read(&tx, bundle_id)?.ok_or_else(|| invalid("the bundle mapping no longer exists"))?; + let Some(target) = read_history(&tx, bundle_id, version)? else { + return Ok(None); + }; + if target.version == current.version { + return Err(invalid("the bundle already uses the requested version")); + } + archive_bundle(&tx, ¤t, archived_at)?; + tx.execute( + "DELETE FROM plugin_bundle_history_components WHERE bundle_id = ?1 AND version = ?2", + params![bundle_id, version], + ) + .map_err(failed)?; + tx.execute( + "DELETE FROM plugin_bundle_history WHERE bundle_id = ?1 AND version = ?2", + params![bundle_id, version], + ) + .map_err(failed)?; + update_bundle_row(&tx, &target)?; + replace_components(&tx, &target)?; + tx.commit().map_err(failed)?; + Ok(Some(target)) + } + + /// The stored bundle and its components, with components ordered by plugin id. + pub fn bundle(&self, bundle_id: &str) -> Result, StorageError> { + read(&self.conn(), bundle_id) + } + + /// Every stored bundle and its components, ordered by bundle id. The inventory groups + /// installed components by this mapping; a package without a row stays standalone. + pub fn bundles(&self) -> Result, StorageError> { + let conn = self.conn(); + let mut statement = conn + .prepare("SELECT bundle_id FROM plugin_bundles ORDER BY bundle_id") + .map_err(failed)?; + let ids = statement + .query_map([], |row| row.get::<_, String>(0)) + .map_err(failed)? + .collect::, _>>() + .map_err(failed)?; + let mut bundles = Vec::with_capacity(ids.len()); + for bundle_id in ids { + if let Some(bundle) = read(&conn, &bundle_id)? { + bundles.push(bundle); + } + } + Ok(bundles) + } + + /// The bundle that contains `plugin_id`, or `None` for an ungrouped standalone package. + pub fn bundle_for_plugin(&self, plugin_id: &str) -> Result, StorageError> { + let conn = self.conn(); + let bundle_id: Option = conn + .query_row( + "SELECT bundle_id FROM plugin_bundle_components WHERE plugin_id = ?1", + [plugin_id], + |row| row.get(0), + ) + .optional() + .map_err(failed)?; + match bundle_id { + Some(bundle_id) => read(&conn, &bundle_id), + None => Ok(None), + } + } + + /// Removes only the bundle mapping and returns what was removed. Component packages, grants + /// and every other table are untouched, so callers own package removal and retention choices. + pub fn remove_bundle(&self, bundle_id: &str) -> Result, StorageError> { + let mut conn = self.conn(); + let tx = conn.transaction().map_err(failed)?; + let Some(bundle) = read(&tx, bundle_id)? else { + return Ok(None); + }; + // Delete the children explicitly: foreign-key enforcement is not enabled on every + // connection, and the mapping must not gain orphans from a caller that skips the cascade. + tx.execute( + "DELETE FROM plugin_bundle_components WHERE bundle_id = ?1", + [bundle_id], + ) + .map_err(failed)?; + tx.execute( + "DELETE FROM plugin_bundles WHERE bundle_id = ?1", + [bundle_id], + ) + .map_err(failed)?; + tx.commit().map_err(failed)?; + Ok(Some(bundle)) + } + + /// Removes the mapping rows of the named components and, when no component row remains, the + /// bundle row itself. One transaction, so a partially uninstalled bundle never leaves a row + /// naming a package that is no longer installed. Returns the mapping that still exists. + /// + /// Component packages, grants and every other table are untouched. + pub fn remove_bundle_components( + &self, + bundle_id: &str, + plugin_ids: &[String], + ) -> Result, StorageError> { + let mut conn = self.conn(); + let tx = conn.transaction().map_err(failed)?; + if read(&tx, bundle_id)?.is_none() { + return Ok(None); + } + { + let mut delete = tx + .prepare( + "DELETE FROM plugin_bundle_components WHERE bundle_id = ?1 AND plugin_id = ?2", + ) + .map_err(failed)?; + for plugin_id in plugin_ids { + delete + .execute(params![bundle_id, plugin_id]) + .map_err(failed)?; + } + } + let remaining: i64 = tx + .query_row( + "SELECT COUNT(*) FROM plugin_bundle_components WHERE bundle_id = ?1", + [bundle_id], + |row| row.get(0), + ) + .map_err(failed)?; + let remaining_bundle = if remaining == 0 { + tx.execute( + "DELETE FROM plugin_bundles WHERE bundle_id = ?1", + [bundle_id], + ) + .map_err(failed)?; + None + } else { + read(&tx, bundle_id)? + }; + tx.commit().map_err(failed)?; + Ok(remaining_bundle) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::db::SqliteSettingsStore; + use tempfile::TempDir; + + fn open(dir: &TempDir) -> SqliteSettingsStore { + SqliteSettingsStore::open(&dir.path().join("test.sqlite3")).unwrap() + } + + fn component( + plugin_id: &str, + kind: &str, + digest: char, + package_version: &str, + ) -> BundleComponentRecord { + BundleComponentRecord { + plugin_id: plugin_id.to_owned(), + kind: kind.to_owned(), + component_sha256: digest.to_string().repeat(64), + package_version: package_version.to_owned(), + } + } + + fn bundle(id: &str) -> BundleRecord { + BundleRecord { + bundle_id: id.to_owned(), + name: "Dolphin GameCube and Wii".to_owned(), + version: "0.1.0".to_owned(), + publisher_fingerprint: "sha256:publisher".to_owned(), + manifest_sha256: "a".repeat(64), + installed_at: 500, + components: vec![ + component("org.example.dolphin", "provider", 'a', "0.2.0"), + component("org.example.dolphin.launch", "extension", 'b', "0.1.0"), + ], + } + } + + #[test] + fn a_bundle_and_its_components_round_trip() { + let dir = TempDir::new().unwrap(); + let store = open(&dir).bundle_store(); + let expected = bundle("org.example.dolphin"); + let mut recorded = expected.clone(); + // Components are read in plugin-id order, independent of how they were recorded. + recorded.components.reverse(); + store.record_bundle(&recorded).unwrap(); + + assert_eq!( + store.bundle("org.example.dolphin").unwrap(), + Some(expected.clone()) + ); + assert_eq!(store.bundle("org.example.missing").unwrap(), None); + assert_eq!(store.bundles().unwrap(), vec![expected.clone()]); + assert_eq!(expected.components[0].package_version, "0.2.0"); + assert_eq!(expected.components[1].kind, "extension"); + } + + #[test] + fn recording_a_bundle_is_all_or_nothing() { + let dir = TempDir::new().unwrap(); + let store = open(&dir).bundle_store(); + let mut first = bundle("org.example.first"); + first.components = vec![component("org.example.shared", "provider", 'a', "1.0.0")]; + store.record_bundle(&first).unwrap(); + + // The second component collides with the bundle recorded above after its sibling and the + // bundle row were already inserted; the whole record must roll back. + let mut second = bundle("org.example.second"); + second.components = vec![ + component("org.example.second", "provider", 'b', "1.0.0"), + component("org.example.shared", "extension", 'c', "1.0.0"), + ]; + assert!(store.record_bundle(&second).is_err()); + assert_eq!(store.bundle("org.example.second").unwrap(), None); + assert_eq!(store.bundle_for_plugin("org.example.second").unwrap(), None); + assert_eq!( + store.bundle_for_plugin("org.example.shared").unwrap(), + Some(first) + ); + } + + #[test] + fn a_plugin_resolves_to_its_bundle_or_none() { + let dir = TempDir::new().unwrap(); + let store = open(&dir).bundle_store(); + let recorded = bundle("org.example.dolphin"); + store.record_bundle(&recorded).unwrap(); + + assert_eq!( + store + .bundle_for_plugin("org.example.dolphin.launch") + .unwrap(), + Some(recorded) + ); + assert_eq!( + store.bundle_for_plugin("org.example.standalone").unwrap(), + None + ); + } + + #[test] + fn an_update_archives_the_previous_mapping_and_rollback_restores_it() { + let dir = TempDir::new().unwrap(); + let store = open(&dir).bundle_store(); + let first = bundle("org.example.dolphin"); + store.record_bundle(&first).unwrap(); + + let mut second = first.clone(); + second.version = "0.2.0".to_owned(); + second.manifest_sha256 = "c".repeat(64); + second.installed_at = 900; + second.components = vec![ + component("org.example.dolphin", "provider", 'd', "0.3.0"), + component("org.example.dolphin.launch", "extension", 'e', "0.2.0"), + ]; + assert_eq!( + store.update_bundle(&second, 700).unwrap(), + first, + "the previous mapping is returned for rollback" + ); + assert_eq!( + store.bundle("org.example.dolphin").unwrap(), + Some(second.clone()) + ); + assert_eq!( + store.previous_versions("org.example.dolphin").unwrap(), + vec!["0.1.0".to_owned()] + ); + assert_eq!( + store + .previous_bundle("org.example.dolphin", "0.1.0") + .unwrap(), + Some(first.clone()) + ); + + // An unchanged update changes nothing. + assert!(store.update_bundle(&second, 800).is_err()); + + let restored = store + .restore_bundle_version("org.example.dolphin", "0.1.0", 1_000) + .unwrap() + .expect("the archived version is restored"); + assert_eq!(restored, first); + assert_eq!(store.bundle("org.example.dolphin").unwrap(), Some(first)); + assert_eq!( + store.previous_versions("org.example.dolphin").unwrap(), + vec!["0.2.0".to_owned()], + "the replaced version becomes the rollback target" + ); + // A version that is not archived restores nothing. + assert_eq!( + store + .restore_bundle_version("org.example.dolphin", "9.9.9", 1_000) + .unwrap(), + None + ); + } + + #[test] + fn a_duplicate_bundle_id_does_not_replace_the_first_mapping() { + let dir = TempDir::new().unwrap(); + let store = open(&dir).bundle_store(); + let recorded = bundle("org.example.dolphin"); + store.record_bundle(&recorded).unwrap(); + + let mut replacement = recorded.clone(); + replacement.version = "0.2.0".to_owned(); + assert!(store.record_bundle(&replacement).is_err()); + assert_eq!(store.bundle("org.example.dolphin").unwrap(), Some(recorded)); + } + + #[test] + fn invalid_bundle_records_are_rejected_before_writing() { + let dir = TempDir::new().unwrap(); + let store = open(&dir); + let bundles = store.bundle_store(); + let cases = [ + { + let mut value = bundle("org.example.invalid"); + value.bundle_id.clear(); + value + }, + { + let mut value = bundle("org.example.invalid"); + value.name.clear(); + value + }, + { + let mut value = bundle("org.example.invalid"); + value.version.clear(); + value + }, + { + let mut value = bundle("org.example.invalid"); + value.publisher_fingerprint.clear(); + value + }, + { + let mut value = bundle("org.example.invalid"); + value.manifest_sha256.clear(); + value + }, + { + let mut value = bundle("org.example.invalid"); + value.installed_at = -1; + value + }, + { + let mut value = bundle("org.example.invalid"); + value.components.clear(); + value + }, + { + let mut value = bundle("org.example.invalid"); + value.components[0].plugin_id.clear(); + value + }, + { + let mut value = bundle("org.example.invalid"); + value.components[0].kind = "store".to_owned(); + value + }, + { + let mut value = bundle("org.example.invalid"); + value.components[0].component_sha256.clear(); + value + }, + { + let mut value = bundle("org.example.invalid"); + value.components[0].package_version.clear(); + value + }, + { + let mut value = bundle("org.example.invalid"); + value.components[1].plugin_id = value.components[0].plugin_id.clone(); + value + }, + ]; + for value in cases { + assert!(bundles.record_bundle(&value).is_err(), "{value:?}"); + } + let rows: i64 = store + .conn() + .query_row("SELECT COUNT(*) FROM plugin_bundles", [], |row| row.get(0)) + .unwrap(); + assert_eq!(rows, 0, "a rejected record writes nothing"); + } + + #[test] + fn removing_component_rows_keeps_a_partial_mapping_and_drops_an_empty_one() { + let dir = TempDir::new().unwrap(); + let store = open(&dir).bundle_store(); + let recorded = bundle("org.example.dolphin"); + store.record_bundle(&recorded).unwrap(); + + // One component removed: its row and only its row disappears; the bundle keeps the rest. + let remaining = store + .remove_bundle_components("org.example.dolphin", &["org.example.dolphin".to_owned()]) + .unwrap() + .expect("the bundle still has a component"); + assert_eq!( + remaining.components, + vec![component( + "org.example.dolphin.launch", + "extension", + 'b', + "0.1.0" + )] + ); + assert_eq!( + store.bundle_for_plugin("org.example.dolphin").unwrap(), + None + ); + assert_eq!( + store + .bundle_for_plugin("org.example.dolphin.launch") + .unwrap(), + Some(remaining.clone()) + ); + + // Removing the last component deletes the bundle row as well. + let remaining = store + .remove_bundle_components( + "org.example.dolphin", + &["org.example.dolphin.launch".to_owned()], + ) + .unwrap(); + assert_eq!(remaining, None); + assert_eq!(store.bundle("org.example.dolphin").unwrap(), None); + + // An unknown bundle or an unknown component id writes nothing. + assert_eq!( + store + .remove_bundle_components("org.example.missing", &["x".to_owned()]) + .unwrap(), + None + ); + store.record_bundle(&recorded).unwrap(); + let unchanged = store + .remove_bundle_components("org.example.dolphin", &["org.example.other".to_owned()]) + .unwrap(); + assert_eq!(unchanged, Some(recorded)); + } + + #[test] + fn removing_the_mapping_leaves_other_persistence_untouched() { + let dir = TempDir::new().unwrap(); + let settings = open(&dir); + settings + .conn() + .execute( + "INSERT INTO plugin_runtime_resources + (owner_key, runtime_id, revision, runtime_json) + VALUES ('owner', 'runtime', 1, '{}')", + [], + ) + .unwrap(); + let bundles = settings.bundle_store(); + let recorded = bundle("org.example.dolphin"); + bundles.record_bundle(&recorded).unwrap(); + + assert_eq!( + bundles + .remove_bundle("org.example.dolphin") + .unwrap() + .as_ref(), + Some(&recorded) + ); + assert_eq!(bundles.bundle("org.example.dolphin").unwrap(), None); + assert_eq!( + bundles + .bundle_for_plugin("org.example.dolphin.launch") + .unwrap(), + None + ); + assert_eq!(bundles.remove_bundle("org.example.missing").unwrap(), None); + + let sentinel: i64 = settings + .conn() + .query_row( + "SELECT COUNT(*) FROM plugin_runtime_resources WHERE runtime_id = 'runtime'", + [], + |row| row.get(0), + ) + .unwrap(); + assert_eq!(sentinel, 1, "an unrelated row is preserved"); + + // The mapping is fully gone, so the id can be recorded again. + bundles.record_bundle(&recorded).unwrap(); + assert_eq!( + bundles.bundle("org.example.dolphin").unwrap(), + Some(recorded) + ); + } +} diff --git a/crates/platform/src/plugin_bundles.rs b/crates/platform/src/plugin_bundles.rs new file mode 100644 index 000000000..2df883047 --- /dev/null +++ b/crates/platform/src/plugin_bundles.rs @@ -0,0 +1,1071 @@ +//! Signed bundle manifests for multi-package plugin distribution. +//! +//! A bundle is a ZIP envelope: `bundle.json`, `components/*.gnplugin` and `signature.ed25519`. +//! This module owns the manifest contract and its signature domain. The archive extractor and +//! the per-component package verification live with the package/registry code; a bundle only +//! groups packages that are validated exactly as if imported alone. + +use base64::Engine as _; +use ring::signature::{ED25519, UnparsedPublicKey}; +use serde::Deserialize; +use sha2::{Digest, Sha256}; +use std::collections::{BTreeMap, BTreeSet}; +use std::io::{Cursor, Read, Seek}; +use std::path::Path; +use zip::ZipArchive; + +use crate::plugin_packages::{ + MAX_COMPRESSED_BYTES, MAX_ENTRIES, MAX_EXPANDED_BYTES, MAX_METADATA_BYTES, + parse_integrity_json, verify_integrity_signature, verify_payload_hashes, +}; + +/// ASCII domain label followed by one NUL byte; signed before the raw `bundle.json` bytes. +pub const BUNDLE_SIGNATURE_DOMAIN_PREFIX: &[u8] = b"GameNode/plugin-bundle/v1\0"; +/// The manifest name at the bundle root. +pub const BUNDLE_MANIFEST_NAME: &str = "bundle.json"; +/// Component archives live below this package-relative directory. +pub const COMPONENTS_DIRECTORY: &str = "components"; +/// Most components one bundle may carry. +pub const MAX_BUNDLE_COMPONENTS: usize = 8; +/// Largest `bundle.json` accepted, in bytes. +pub const MAX_BUNDLE_MANIFEST_BYTES: u64 = 256 * 1024; +/// Largest bundle archive accepted, in bytes. +pub const MAX_BUNDLE_ARCHIVE_BYTES: u64 = 512 * 1024 * 1024; +/// Largest expanded bundle accepted, in bytes. +pub const MAX_BUNDLE_EXPANDED_BYTES: u64 = 2 * 1024 * 1024 * 1024; + +#[derive(Debug, thiserror::Error, PartialEq, Eq)] +pub enum BundleError { + #[error("bundle manifest is malformed or exceeds the size limit")] + InvalidManifest, + #[error("bundle manifest has an unsupported schema version")] + UnsupportedSchema, + #[error("bundle publisher key or signature has an invalid length")] + InvalidKeyOrSignature, + #[error("bundle signature is invalid")] + InvalidSignature, + #[error("bundle component path is unsafe or not a component archive")] + InvalidComponentPath, + #[error("bundle repeats a component plugin id or archive path")] + DuplicateComponent, + #[error("bundle carries too many components")] + TooManyComponents, + #[error("bundle component kind must be \"provider\" or \"extension\"")] + UnsupportedComponentKind, + #[error("bundle archive is malformed or contains an unexpected entry")] + InvalidArchive, + #[error("bundle or component exceeds an archive size or entry limit")] + ArchiveLimit, + #[error("bundle component is not a valid signed package")] + InvalidComponent, + #[error("bundle component identity does not match the bundle manifest")] + ComponentMismatch, + #[error("verified bundle components could not be written to the private staging directory")] + Staging, +} + +/// A verified bundle: the signed manifest plus the identity of every component package. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct VerifiedBundle { + pub manifest: BundleManifest, + /// Lowercase SHA-256 of the exact signed `bundle.json` bytes stored in the archive. + pub manifest_sha256: String, + pub components: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct VerifiedBundleComponent { + pub path: String, + pub plugin_id: String, + pub kind: String, + pub version: String, + pub sha256: String, +} + +#[derive(Clone, Debug, PartialEq, Eq, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct BundleManifest { + pub schema: u32, + pub id: String, + pub name: String, + pub version: String, + pub publisher: BundlePublisher, + pub components: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct BundlePublisher { + pub key_id: String, + /// Base64-encoded 32-byte Ed25519 public key, matching the component publisher keys. + pub public_key: String, +} + +#[derive(Clone, Debug, PartialEq, Eq, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct BundleComponent { + /// Package-relative archive path below `components/`, ending in `.gnplugin`. + pub path: String, + /// Lowercase SHA-256 of the exact component archive bytes. + pub sha256: String, + pub plugin_id: String, + /// `provider` or `extension`. + pub kind: String, +} + +impl BundleManifest { + pub fn publisher_key(&self) -> Result<[u8; 32], BundleError> { + let decoded = base64::engine::general_purpose::STANDARD + .decode(self.publisher.public_key.as_bytes()) + .map_err(|_| BundleError::InvalidKeyOrSignature)?; + decoded + .try_into() + .map_err(|_| BundleError::InvalidKeyOrSignature) + } +} + +fn valid_text(value: &str, max: usize) -> bool { + !value.trim().is_empty() + && value.len() <= max + && value.trim() == value + && !value.chars().any(char::is_control) +} + +fn valid_identifier(value: &str) -> bool { + valid_text(value, 128) + && value + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'-' | b'_')) +} + +fn valid_component_path(path: &str) -> bool { + let Some(relative) = path.strip_prefix("components/") else { + return false; + }; + relative.len() > ".gnplugin".len() + && relative.ends_with(".gnplugin") + && !path.contains('\\') + && !path.chars().any(char::is_control) + && path.split('/').all(|segment| { + !segment.is_empty() && segment != "." && segment != ".." && !segment.contains(':') + }) +} + +fn valid_digest(value: &str) -> bool { + value.len() == 64 + && value + .bytes() + .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)) +} + +/// Parse and validate the bounded bundle manifest. The caller verifies the detached signature +/// before trusting any field. +pub fn parse_bundle_manifest(raw: &[u8]) -> Result { + if raw.is_empty() || raw.len() as u64 > MAX_BUNDLE_MANIFEST_BYTES { + return Err(BundleError::InvalidManifest); + } + let manifest: BundleManifest = + serde_json::from_slice(raw).map_err(|_| BundleError::InvalidManifest)?; + if manifest.schema != 1 { + return Err(BundleError::UnsupportedSchema); + } + if !valid_identifier(&manifest.id) || !valid_text(&manifest.name, 200) { + return Err(BundleError::InvalidManifest); + } + if semver::Version::parse(&manifest.version).is_err() { + return Err(BundleError::InvalidManifest); + } + if !valid_text(&manifest.publisher.key_id, 128) || manifest.publisher_key().is_err() { + return Err(BundleError::InvalidKeyOrSignature); + } + if manifest.components.is_empty() { + return Err(BundleError::InvalidManifest); + } + if manifest.components.len() > MAX_BUNDLE_COMPONENTS { + return Err(BundleError::TooManyComponents); + } + let mut plugin_ids = std::collections::BTreeSet::new(); + let mut paths = std::collections::BTreeSet::new(); + for component in &manifest.components { + if !valid_component_path(&component.path) { + return Err(BundleError::InvalidComponentPath); + } + if !valid_digest(&component.sha256) || !valid_identifier(&component.plugin_id) { + return Err(BundleError::InvalidManifest); + } + if !matches!(component.kind.as_str(), "provider" | "extension") { + return Err(BundleError::UnsupportedComponentKind); + } + if !plugin_ids.insert(component.plugin_id.as_str()) + || !paths.insert(component.path.to_ascii_lowercase()) + { + return Err(BundleError::DuplicateComponent); + } + } + Ok(manifest) +} + +/// Verify Ed25519 over the fixed domain prefix plus the exact raw `bundle.json` bytes. +pub fn verify_bundle_signature( + public_key: &[u8], + raw_manifest: &[u8], + signature: &[u8], +) -> Result<(), BundleError> { + if public_key.len() != 32 || signature.len() != 64 { + return Err(BundleError::InvalidKeyOrSignature); + } + let mut signed = Vec::with_capacity(BUNDLE_SIGNATURE_DOMAIN_PREFIX.len() + raw_manifest.len()); + signed.extend_from_slice(BUNDLE_SIGNATURE_DOMAIN_PREFIX); + signed.extend_from_slice(raw_manifest); + UnparsedPublicKey::new(&ED25519, public_key) + .verify(&signed, signature) + .map_err(|_| BundleError::InvalidSignature) +} + +/// The manifest's declared key must equal the key that actually verified it, so a bundle cannot +/// point trust at a key different from the one used to sign it. +pub fn verify_bundle_manifest( + raw_manifest: &[u8], + publisher_key: &[u8], + signature: &[u8], +) -> Result { + verify_bundle_signature(publisher_key, raw_manifest, signature)?; + let manifest = parse_bundle_manifest(raw_manifest)?; + if manifest.publisher_key()? != publisher_key { + return Err(BundleError::InvalidSignature); + } + Ok(manifest) +} + +/// The optional development-key marker at the bundle root. +pub const DEVELOPMENT_KEY: &str = "DEVELOPMENT-KEY.txt"; + +/// Verify a bundle archive from disk without extracting or executing it. +pub fn verify_bundle_archive(path: &Path) -> Result { + let metadata = std::fs::symlink_metadata(path).map_err(|_| BundleError::InvalidArchive)?; + if metadata.file_type().is_symlink() + || !metadata.is_file() + || metadata.len() > MAX_BUNDLE_ARCHIVE_BYTES + { + return Err(BundleError::ArchiveLimit); + } + let file = std::fs::File::open(path).map_err(|_| BundleError::InvalidArchive)?; + verify_bundle_reader(std::io::BufReader::new(file)).map(|verified| verified.0) +} + +/// Verify a bundle archive and stage every component archive it declares below `staging_dir`. +/// +/// `staging_dir` must already exist and be private to the import; this function only creates the +/// `components/` subdirectory and the exact files the verified manifest lists. Nothing is +/// extracted recursively and no package content is read as code. The verified identity is +/// returned so the caller can run the ordinary package validator on every staged component. +pub fn stage_bundle_archive( + archive_path: &Path, + staging_dir: &Path, +) -> Result { + let metadata = + std::fs::symlink_metadata(archive_path).map_err(|_| BundleError::InvalidArchive)?; + if metadata.file_type().is_symlink() + || !metadata.is_file() + || metadata.len() > MAX_BUNDLE_ARCHIVE_BYTES + { + return Err(BundleError::ArchiveLimit); + } + if !staging_dir.is_dir() { + return Err(BundleError::Staging); + } + let file = std::fs::File::open(archive_path).map_err(|_| BundleError::InvalidArchive)?; + let (bundle, components) = verify_bundle_reader(std::io::BufReader::new(file))?; + for (relative, bytes) in components { + let destination = staging_dir.join(&relative); + let parent = destination.parent().ok_or(BundleError::Staging)?; + std::fs::create_dir_all(parent).map_err(|_| BundleError::Staging)?; + std::fs::write(&destination, &bytes).map_err(|_| BundleError::Staging)?; + } + Ok(bundle) +} + +/// Verify a bundle held in memory; used by fixtures and import staging. +pub fn verify_bundle_bytes(bytes: &[u8]) -> Result { + if bytes.len() as u64 > MAX_BUNDLE_ARCHIVE_BYTES { + return Err(BundleError::ArchiveLimit); + } + verify_bundle_reader(Cursor::new(bytes)).map(|verified| verified.0) +} + +fn read_bounded(mut reader: R, limit: usize) -> Result, BundleError> { + let mut bytes = Vec::with_capacity(limit.min(64 * 1024)); + reader + .read_to_end(&mut bytes) + .map_err(|_| BundleError::InvalidArchive)?; + if bytes.len() > limit { + return Err(BundleError::ArchiveLimit); + } + Ok(bytes) +} + +fn safe_relative(name: &str) -> bool { + !name.is_empty() + && !name.contains('\\') + && !name.contains('\0') + && !name.starts_with('/') + && !name.chars().any(char::is_control) + && name + .split('/') + .all(|part| !part.is_empty() && part != "." && part != ".." && !part.contains(':')) +} + +fn valid_outer_name(name: &str) -> bool { + name == BUNDLE_MANIFEST_NAME + || name == "signature.ed25519" + || name == DEVELOPMENT_KEY + || valid_component_path(name) +} + +fn verify_bundle_reader( + reader: R, +) -> Result<(VerifiedBundle, BTreeMap>), BundleError> { + let mut archive = ZipArchive::new(reader).map_err(|_| BundleError::InvalidArchive)?; + if archive.len() > MAX_BUNDLE_COMPONENTS + 3 { + return Err(BundleError::ArchiveLimit); + } + let mut files = BTreeMap::new(); + let mut folded = BTreeSet::new(); + let mut expanded = 0u64; + for index in 0..archive.len() { + let entry = archive + .by_index(index) + .map_err(|_| BundleError::InvalidArchive)?; + if entry.is_dir() { + return Err(BundleError::InvalidArchive); + } + let name = entry.name().to_owned(); + if !valid_outer_name(&name) || !folded.insert(name.to_ascii_lowercase()) { + return Err(BundleError::InvalidArchive); + } + expanded = expanded + .checked_add(entry.size()) + .ok_or(BundleError::ArchiveLimit)?; + if expanded > MAX_BUNDLE_EXPANDED_BYTES { + return Err(BundleError::ArchiveLimit); + } + let limit = match name.as_str() { + BUNDLE_MANIFEST_NAME => MAX_BUNDLE_MANIFEST_BYTES as usize, + "signature.ed25519" => 64, + DEVELOPMENT_KEY => 64 * 1024, + _ => MAX_COMPRESSED_BYTES as usize, + }; + let data = read_bounded(entry.take(limit as u64 + 1), limit)?; + files.insert(name, data); + } + + let raw_manifest = files + .remove(BUNDLE_MANIFEST_NAME) + .ok_or(BundleError::InvalidManifest)?; + let signature = files + .remove("signature.ed25519") + .ok_or(BundleError::InvalidKeyOrSignature)?; + let manifest = parse_bundle_manifest(&raw_manifest)?; + let publisher_key = manifest.publisher_key()?; + verify_bundle_signature(&publisher_key, &raw_manifest, &signature)?; + let manifest_sha256 = format!("{:x}", Sha256::digest(&raw_manifest)); + + let mut components = Vec::with_capacity(manifest.components.len()); + let mut component_files = BTreeMap::new(); + for component in &manifest.components { + let bytes = files + .remove(&component.path) + .ok_or(BundleError::InvalidComponent)?; + if format!("{:x}", Sha256::digest(&bytes)) != component.sha256 { + return Err(BundleError::InvalidComponent); + } + let identity = verify_component(&bytes, &publisher_key)?; + if identity.id != component.plugin_id || identity.kind != component.kind { + return Err(BundleError::ComponentMismatch); + } + components.push(VerifiedBundleComponent { + path: component.path.clone(), + plugin_id: identity.id, + kind: identity.kind, + version: identity.version, + sha256: component.sha256.clone(), + }); + component_files.insert(component.path.clone(), bytes); + } + files.remove(DEVELOPMENT_KEY); + if !files.is_empty() { + return Err(BundleError::InvalidArchive); + } + Ok(( + VerifiedBundle { + manifest, + manifest_sha256, + components, + }, + component_files, + )) +} + +#[derive(Deserialize)] +struct ComponentManifest { + id: String, + kind: String, + version: String, + publisher: ComponentPublisher, +} + +#[derive(Deserialize)] +struct ComponentPublisher { + public_key: String, +} + +struct ComponentIdentity { + id: String, + kind: String, + version: String, +} + +fn verify_component( + bytes: &[u8], + publisher_key: &[u8; 32], +) -> Result { + let mut archive = + ZipArchive::new(Cursor::new(bytes)).map_err(|_| BundleError::InvalidComponent)?; + if archive.len() > MAX_ENTRIES { + return Err(BundleError::ArchiveLimit); + } + let mut payload = BTreeMap::new(); + let mut integrity = None; + let mut signature = None; + let mut folded = BTreeSet::new(); + let mut expanded = 0u64; + for index in 0..archive.len() { + let entry = archive + .by_index(index) + .map_err(|_| BundleError::InvalidComponent)?; + if entry.is_dir() { + return Err(BundleError::InvalidComponent); + } + let name = entry.name().to_owned(); + if !safe_relative(&name) || !folded.insert(name.to_ascii_lowercase()) { + return Err(BundleError::InvalidComponent); + } + expanded = expanded + .checked_add(entry.size()) + .ok_or(BundleError::ArchiveLimit)?; + if expanded > MAX_EXPANDED_BYTES { + return Err(BundleError::ArchiveLimit); + } + let limit = if name == "integrity.json" + || name == "signature.ed25519" + || name == "plugin.json" + || name.starts_with("licenses/") + { + MAX_METADATA_BYTES as usize + } else { + MAX_COMPRESSED_BYTES as usize + }; + let data = read_bounded(entry.take(limit as u64 + 1), limit)?; + match name.as_str() { + "integrity.json" => integrity = Some(data), + "signature.ed25519" => signature = Some(data), + _ => { + payload.insert(name, data); + } + } + } + let integrity = integrity.ok_or(BundleError::InvalidComponent)?; + let signature = signature.ok_or(BundleError::InvalidComponent)?; + verify_integrity_signature(publisher_key, &integrity, &signature) + .map_err(|_| BundleError::InvalidComponent)?; + let manifest = parse_integrity_json(&integrity).map_err(|_| BundleError::InvalidComponent)?; + verify_payload_hashes(&manifest.files.0, &payload) + .map_err(|_| BundleError::InvalidComponent)?; + let plugin = payload + .get("plugin.json") + .ok_or(BundleError::InvalidComponent)?; + let identity: ComponentManifest = + serde_json::from_slice(plugin).map_err(|_| BundleError::InvalidComponent)?; + let declared = base64::engine::general_purpose::STANDARD + .decode(identity.publisher.public_key.as_bytes()) + .map_err(|_| BundleError::InvalidComponent)?; + if declared.as_slice() != publisher_key { + return Err(BundleError::ComponentMismatch); + } + if !valid_identifier(&identity.id) || semver::Version::parse(&identity.version).is_err() { + return Err(BundleError::InvalidComponent); + } + if !matches!(identity.kind.as_str(), "provider" | "extension") { + return Err(BundleError::UnsupportedComponentKind); + } + Ok(ComponentIdentity { + id: identity.id, + kind: identity.kind, + version: identity.version, + }) +} + +#[cfg(test)] +mod tests { + use ring::signature::{Ed25519KeyPair, KeyPair}; + + use super::*; + + fn manifest(key: &[u8]) -> Vec { + let public = base64::engine::general_purpose::STANDARD.encode(key); + serde_json::to_vec(&serde_json::json!({ + "schema": 1, + "id": "org.example.dolphin", + "name": "Dolphin GameCube and Wii", + "version": "0.1.0", + "publisher": { "key_id": "dolphin-dev", "public_key": public }, + "components": [ + { + "path": "components/provider.gnplugin", + "sha256": "a".repeat(64), + "plugin_id": "org.example.dolphin", + "kind": "provider" + }, + { + "path": "components/launch.gnplugin", + "sha256": "b".repeat(64), + "plugin_id": "org.example.dolphin.launch", + "kind": "extension" + } + ] + })) + .unwrap() + } + + fn signed(key: &Ed25519KeyPair, raw: &[u8]) -> Vec { + let mut payload = BUNDLE_SIGNATURE_DOMAIN_PREFIX.to_vec(); + payload.extend_from_slice(raw); + key.sign(&payload).as_ref().to_vec() + } + + #[test] + fn a_bundle_manifest_parses_with_its_publisher_and_components() { + let key = Ed25519KeyPair::from_seed_unchecked(&[7; 32]).unwrap(); + let public = key.public_key().as_ref(); + let raw = manifest(public); + let parsed = parse_bundle_manifest(&raw).unwrap(); + assert_eq!(parsed.id, "org.example.dolphin"); + assert_eq!(parsed.version, "0.1.0"); + assert_eq!(parsed.publisher.key_id, "dolphin-dev"); + assert_eq!(parsed.publisher_key().unwrap(), public); + assert_eq!(parsed.components.len(), 2); + assert_eq!(parsed.components[0].kind, "provider"); + assert_eq!(parsed.components[1].kind, "extension"); + assert_eq!(parsed.components[0].sha256, "a".repeat(64)); + } + + #[test] + fn the_signature_covers_the_exact_manifest_bytes() { + let key = Ed25519KeyPair::from_seed_unchecked(&[8; 32]).unwrap(); + let public = key.public_key().as_ref(); + let raw = manifest(public); + let signature = signed(&key, &raw); + verify_bundle_signature(public, &raw, &signature).unwrap(); + let mut tampered = raw.clone(); + tampered.push(b' '); + assert_eq!( + verify_bundle_signature(public, &tampered, &signature), + Err(BundleError::InvalidSignature) + ); + let mut bad_signature = signature.clone(); + bad_signature[0] ^= 1; + assert_eq!( + verify_bundle_signature(public, &raw, &bad_signature), + Err(BundleError::InvalidSignature) + ); + } + + #[test] + fn a_manifest_pointing_at_another_key_is_rejected() { + let signer = Ed25519KeyPair::from_seed_unchecked(&[9; 32]).unwrap(); + let other = Ed25519KeyPair::from_seed_unchecked(&[10; 32]).unwrap(); + let raw = manifest(signer.public_key().as_ref()); + let signature = signed(&signer, &raw); + assert_eq!( + verify_bundle_manifest(&raw, other.public_key().as_ref(), &signature), + Err(BundleError::InvalidSignature) + ); + } + + #[test] + fn unsafe_or_duplicate_components_are_rejected() { + let key = Ed25519KeyPair::from_seed_unchecked(&[11; 32]).unwrap(); + let public = base64::engine::general_purpose::STANDARD.encode(key.public_key().as_ref()); + for path in [ + "components/../escape.gnplugin", + "components//empty.gnplugin", + "/components/absolute.gnplugin", + "components/not-a-package.zip", + ] { + let raw = serde_json::to_vec(&serde_json::json!({ + "schema": 1, + "id": "org.example.bundle", + "name": "Bundle", + "version": "1.0.0", + "publisher": { "key_id": "key", "public_key": public }, + "components": [{ "path": path, "sha256": "a".repeat(64), "plugin_id": "org.example.a", "kind": "provider" }] + })) + .unwrap(); + assert_eq!( + parse_bundle_manifest(&raw), + Err(BundleError::InvalidComponentPath), + "{path}" + ); + } + let raw = serde_json::to_vec(&serde_json::json!({ + "schema": 1, + "id": "org.example.bundle", + "name": "Bundle", + "version": "1.0.0", + "publisher": { "key_id": "key", "public_key": public }, + "components": [ + { "path": "components/a.gnplugin", "sha256": "a".repeat(64), "plugin_id": "org.example.a", "kind": "provider" }, + { "path": "components/b.gnplugin", "sha256": "b".repeat(64), "plugin_id": "org.example.a", "kind": "provider" } + ] + })) + .unwrap(); + assert_eq!( + parse_bundle_manifest(&raw), + Err(BundleError::DuplicateComponent) + ); + } + + #[test] + fn schema_version_kind_and_size_are_bounded() { + let key = Ed25519KeyPair::from_seed_unchecked(&[12; 32]).unwrap(); + let public = base64::engine::general_purpose::STANDARD.encode(key.public_key().as_ref()); + let make = |schema: u32, kind: &str, count: usize| { + let components: Vec<_> = (0..count) + .map(|index| { + serde_json::json!({ + "path": format!("components/{index}.gnplugin"), + "sha256": "a".repeat(64), + "plugin_id": format!("org.example.{index}"), + "kind": kind + }) + }) + .collect(); + serde_json::to_vec(&serde_json::json!({ + "schema": schema, + "id": "org.example.bundle", + "name": "Bundle", + "version": "1.0.0", + "publisher": { "key_id": "key", "public_key": public }, + "components": components + })) + .unwrap() + }; + assert_eq!( + parse_bundle_manifest(&make(2, "provider", 1)), + Err(BundleError::UnsupportedSchema) + ); + assert_eq!( + parse_bundle_manifest(&make(1, "store", 1)), + Err(BundleError::UnsupportedComponentKind) + ); + assert_eq!( + parse_bundle_manifest(&make(1, "provider", MAX_BUNDLE_COMPONENTS + 1)), + Err(BundleError::TooManyComponents) + ); + assert!( + parse_bundle_manifest(&vec![b' '; MAX_BUNDLE_MANIFEST_BYTES as usize + 1]).is_err() + ); + } + + use std::io::{Cursor, Read, Write}; + + use zip::{ZipWriter, write::SimpleFileOptions}; + + fn component_archive( + plugin_id: &str, + kind: &str, + version: &str, + key: &Ed25519KeyPair, + declared_key: Option<&[u8]>, + ) -> Vec { + let declared = declared_key.unwrap_or(key.public_key().as_ref()); + let public = base64::engine::general_purpose::STANDARD.encode(declared); + let manifest = serde_json::to_vec(&serde_json::json!({ + "schema": 1, + "id": plugin_id, + "kind": kind, + "name": "Component", + "version": version, + "api": { "min": "1.6.0", "max": "1.6.0" }, + "permissions": [], + "targets": [{ "os": "linux", "arch": "x86_64", "abi": "gnu", "entrypoint": "bin/plugin" }], + "publisher": { "key_id": "bundle-dev", "public_key": public }, + "license": { "expression": "MIT", "files": ["licenses/LICENSE"] } + })) + .unwrap(); + let files = BTreeMap::from([ + ("bin/plugin".to_owned(), b"fixture executable".to_vec()), + ("licenses/LICENSE".to_owned(), b"fixture license".to_vec()), + ("plugin.json".to_owned(), manifest), + ]); + let hashes = files + .iter() + .map(|(path, bytes)| (path.clone(), format!("{:x}", Sha256::digest(bytes)))) + .collect::>(); + let integrity = + serde_json::to_vec(&serde_json::json!({ "schema": 1, "files": hashes })).unwrap(); + let mut signed = crate::plugin_packages::SIGNATURE_DOMAIN_PREFIX.to_vec(); + signed.extend_from_slice(&integrity); + let signature = key.sign(&signed).as_ref().to_vec(); + let mut entries: Vec<(&str, &[u8])> = files + .iter() + .map(|(path, bytes)| (path.as_str(), bytes.as_slice())) + .collect(); + entries.push(("integrity.json", &integrity)); + entries.push(("signature.ed25519", &signature)); + let mut writer = ZipWriter::new(Cursor::new(Vec::new())); + for (name, data) in entries { + writer + .start_file(name, SimpleFileOptions::default()) + .unwrap(); + writer.write_all(data).unwrap(); + } + writer.finish().unwrap().into_inner() + } + + fn bundle_archive( + key: &Ed25519KeyPair, + components: &[(&str, &str, &str, Vec)], + development: bool, + ) -> Vec { + let public = base64::engine::general_purpose::STANDARD.encode(key.public_key().as_ref()); + let declared = components + .iter() + .map(|(file, plugin_id, kind, bytes)| { + serde_json::json!({ + "path": format!("components/{file}"), + "sha256": format!("{:x}", Sha256::digest(bytes)), + "plugin_id": plugin_id, + "kind": kind + }) + }) + .collect::>(); + let manifest = serde_json::to_vec(&serde_json::json!({ + "schema": 1, + "id": "org.example.bundle", + "name": "Bundle", + "version": "0.1.0", + "publisher": { "key_id": "bundle-dev", "public_key": public }, + "components": declared + })) + .unwrap(); + let mut payload = BUNDLE_SIGNATURE_DOMAIN_PREFIX.to_vec(); + payload.extend_from_slice(&manifest); + let signature = key.sign(&payload).as_ref().to_vec(); + let mut writer = ZipWriter::new(Cursor::new(Vec::new())); + writer + .start_file(BUNDLE_MANIFEST_NAME, SimpleFileOptions::default()) + .unwrap(); + writer.write_all(&manifest).unwrap(); + for (file, _, _, bytes) in components { + writer + .start_file(format!("components/{file}"), SimpleFileOptions::default()) + .unwrap(); + writer.write_all(bytes).unwrap(); + } + writer + .start_file("signature.ed25519", SimpleFileOptions::default()) + .unwrap(); + writer.write_all(&signature).unwrap(); + if development { + writer + .start_file(DEVELOPMENT_KEY, SimpleFileOptions::default()) + .unwrap(); + writer.write_all(b"DEVELOPMENT KEY ONLY").unwrap(); + } + writer.finish().unwrap().into_inner() + } + + fn sample_components( + key: &Ed25519KeyPair, + ) -> Vec<(&'static str, &'static str, &'static str, Vec)> { + vec![ + ( + "provider.gnplugin", + "org.example.provider", + "provider", + component_archive("org.example.provider", "provider", "0.1.0", key, None), + ), + ( + "launch.gnplugin", + "org.example.launch", + "extension", + component_archive("org.example.launch", "extension", "0.1.0", key, None), + ), + ] + } + + #[test] + fn a_valid_bundle_verifies_every_component() { + let key = Ed25519KeyPair::from_seed_unchecked(&[21; 32]).unwrap(); + let components = sample_components(&key); + let bytes = bundle_archive(&key, &components, true); + let verified = verify_bundle_bytes(&bytes).unwrap(); + assert_eq!(verified.manifest.id, "org.example.bundle"); + assert_eq!(verified.manifest.version, "0.1.0"); + assert_eq!(verified.components.len(), 2); + assert_eq!(verified.components[0].plugin_id, "org.example.provider"); + assert_eq!(verified.components[0].kind, "provider"); + assert_eq!(verified.components[1].plugin_id, "org.example.launch"); + assert_eq!(verified.components[1].kind, "extension"); + assert_eq!(verified.components[0].version, "0.1.0"); + } + + #[test] + fn staging_writes_only_the_declared_component_archives() { + let key = Ed25519KeyPair::from_seed_unchecked(&[28; 32]).unwrap(); + let components = sample_components(&key); + let bytes = bundle_archive(&key, &components, true); + let base = tempfile::tempdir().unwrap(); + let archive = base.path().join("fixture.gnbundle"); + std::fs::write(&archive, &bytes).unwrap(); + let staging = base.path().join("staging"); + std::fs::create_dir(&staging).unwrap(); + + let verified = stage_bundle_archive(&archive, &staging).unwrap(); + assert_eq!(verified, verify_bundle_bytes(&bytes).unwrap()); + let provider = std::fs::read(staging.join("components/provider.gnplugin")).unwrap(); + assert_eq!(provider, components[0].3); + let launch = std::fs::read(staging.join("components/launch.gnplugin")).unwrap(); + assert_eq!(launch, components[1].3); + assert!(!staging.join("bundle.json").exists()); + assert!(!staging.join("signature.ed25519").exists()); + + let missing = base.path().join("missing"); + assert_eq!( + stage_bundle_archive(&archive, &missing), + Err(BundleError::Staging) + ); + } + + #[test] + fn tampered_and_missing_components_are_rejected() { + let key = Ed25519KeyPair::from_seed_unchecked(&[22; 32]).unwrap(); + let components = sample_components(&key); + let valid = bundle_archive(&key, &components, false); + + let tampered = { + let mut source = ZipArchive::new(Cursor::new(valid.clone())).unwrap(); + let mut writer = ZipWriter::new(Cursor::new(Vec::new())); + for index in 0..source.len() { + let mut entry = source.by_index(index).unwrap(); + let name = entry.name().to_owned(); + let mut data = Vec::new(); + entry.read_to_end(&mut data).unwrap(); + if name == "components/provider.gnplugin" { + data.extend_from_slice(b"tampered"); + } + writer + .start_file(name, SimpleFileOptions::default()) + .unwrap(); + writer.write_all(&data).unwrap(); + } + writer.finish().unwrap().into_inner() + }; + assert_eq!( + verify_bundle_bytes(&tampered), + Err(BundleError::InvalidComponent) + ); + + let missing = { + let mut source = ZipArchive::new(Cursor::new(valid)).unwrap(); + let mut writer = ZipWriter::new(Cursor::new(Vec::new())); + for index in 0..source.len() { + let mut entry = source.by_index(index).unwrap(); + let name = entry.name().to_owned(); + if name == "components/launch.gnplugin" { + continue; + } + let mut data = Vec::new(); + entry.read_to_end(&mut data).unwrap(); + writer + .start_file(name, SimpleFileOptions::default()) + .unwrap(); + writer.write_all(&data).unwrap(); + } + writer.finish().unwrap().into_inner() + }; + assert_eq!( + verify_bundle_bytes(&missing), + Err(BundleError::InvalidComponent) + ); + } + + #[test] + fn mixed_publishers_duplicate_ids_and_identity_mismatches_are_rejected() { + let key = Ed25519KeyPair::from_seed_unchecked(&[23; 32]).unwrap(); + let other = Ed25519KeyPair::from_seed_unchecked(&[24; 32]).unwrap(); + let foreign = vec![( + "foreign.gnplugin", + "org.example.foreign", + "provider", + component_archive("org.example.foreign", "provider", "0.1.0", &other, None), + )]; + assert_eq!( + verify_bundle_bytes(&bundle_archive(&key, &foreign, false)), + Err(BundleError::InvalidComponent) + ); + + let mut duplicate = sample_components(&key); + duplicate[1].1 = "org.example.provider"; + assert_eq!( + verify_bundle_bytes(&bundle_archive(&key, &duplicate, false)), + Err(BundleError::DuplicateComponent) + ); + + let mut mismatch = sample_components(&key); + mismatch[0].1 = "org.example.other"; + assert_eq!( + verify_bundle_bytes(&bundle_archive(&key, &mismatch, false)), + Err(BundleError::ComponentMismatch) + ); + } + + #[test] + fn unexpected_entries_and_nested_bundles_are_rejected() { + let key = Ed25519KeyPair::from_seed_unchecked(&[25; 32]).unwrap(); + let valid = bundle_archive(&key, &sample_components(&key), false); + for extra in ["extra.txt", "components/nested.gnbundle"] { + let mut source = ZipArchive::new(Cursor::new(valid.clone())).unwrap(); + let mut writer = ZipWriter::new(Cursor::new(Vec::new())); + for index in 0..source.len() { + let mut entry = source.by_index(index).unwrap(); + let name = entry.name().to_owned(); + let mut data = Vec::new(); + entry.read_to_end(&mut data).unwrap(); + writer + .start_file(name, SimpleFileOptions::default()) + .unwrap(); + writer.write_all(&data).unwrap(); + } + writer + .start_file(extra, SimpleFileOptions::default()) + .unwrap(); + writer.write_all(b"not allowed").unwrap(); + let bytes = writer.finish().unwrap().into_inner(); + assert_eq!( + verify_bundle_bytes(&bytes), + Err(BundleError::InvalidArchive), + "{extra}" + ); + } + } + + #[test] + fn a_component_declaring_another_publisher_is_rejected() { + let key = Ed25519KeyPair::from_seed_unchecked(&[26; 32]).unwrap(); + let other = Ed25519KeyPair::from_seed_unchecked(&[27; 32]).unwrap(); + let component = component_archive( + "org.example.provider", + "provider", + "0.1.0", + &key, + Some(other.public_key().as_ref()), + ); + let components = vec![( + "provider.gnplugin", + "org.example.provider", + "provider", + component, + )]; + assert_eq!( + verify_bundle_bytes(&bundle_archive(&key, &components, false)), + Err(BundleError::ComponentMismatch) + ); + } + + #[test] + fn case_colliding_and_excess_entries_are_rejected() { + let key = Ed25519KeyPair::from_seed_unchecked(&[28; 32]).unwrap(); + let components = sample_components(&key); + + // Two component archives whose names differ only by case collide. + let colliding = vec![ + ( + "provider.gnplugin", + "org.example.provider", + "provider", + component_archive("org.example.provider", "provider", "0.1.0", &key, None), + ), + ( + "Provider.gnplugin", + "org.example.provider", + "provider", + component_archive("org.example.provider", "provider", "0.1.0", &key, None), + ), + ]; + let mut writer = ZipWriter::new(Cursor::new(Vec::new())); + { + let bytes = bundle_archive(&key, &colliding, false); + let mut source = ZipArchive::new(Cursor::new(&bytes)).unwrap(); + for index in 0..source.len() { + let mut entry = source.by_index(index).unwrap(); + let name = entry.name().to_owned(); + let mut data = Vec::new(); + entry.read_to_end(&mut data).unwrap(); + writer + .start_file(name, SimpleFileOptions::default()) + .unwrap(); + writer.write_all(&data).unwrap(); + } + } + writer + .start_file("components/Extra.gnplugin", SimpleFileOptions::default()) + .unwrap(); + writer.write_all(b"extra case-colliding entry").unwrap(); + let bytes = writer.finish().unwrap().into_inner(); + assert_eq!( + verify_bundle_bytes(&bytes), + Err(BundleError::InvalidArchive) + ); + + // More entries than components plus metadata exceeds the archive limit before any read. + let mut writer = ZipWriter::new(Cursor::new(Vec::new())); + { + let bytes = bundle_archive(&key, &components, true); + let mut source = ZipArchive::new(Cursor::new(&bytes)).unwrap(); + for index in 0..source.len() { + let mut entry = source.by_index(index).unwrap(); + let name = entry.name().to_owned(); + let mut data = Vec::new(); + entry.read_to_end(&mut data).unwrap(); + writer + .start_file(name, SimpleFileOptions::default()) + .unwrap(); + writer.write_all(&data).unwrap(); + } + } + for index in 0..=(MAX_BUNDLE_COMPONENTS + 1) { + let name = format!("components/pad-{index}.gnplugin"); + writer + .start_file(name, SimpleFileOptions::default()) + .unwrap(); + writer.write_all(b"padding entry").unwrap(); + } + let bytes = writer.finish().unwrap().into_inner(); + assert_eq!(verify_bundle_bytes(&bytes), Err(BundleError::ArchiveLimit)); + } + + #[test] + fn bounded_reads_reject_entries_over_their_limit() { + let data = vec![0u8; 128]; + assert_eq!( + read_bounded(Cursor::new(&data), 64), + Err(BundleError::ArchiveLimit) + ); + assert_eq!( + read_bounded(Cursor::new(&data), 128).unwrap(), + data.as_slice() + ); + } +} diff --git a/crates/platform/src/plugin_environment.rs b/crates/platform/src/plugin_environment.rs new file mode 100644 index 000000000..dafbc48cf --- /dev/null +++ b/crates/platform/src/plugin_environment.rs @@ -0,0 +1,537 @@ +//! Read-only detection of the environment in which plugin processes would execute. +//! +//! This module never starts or inspects a candidate plugin. Detection reads the current +//! process environment and OS metadata only. Call [`detect`] from async code; all OS calls +//! and filesystem reads run on Tokio's blocking pool. + +use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; + +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct PluginEnvironment { + /// Effective userspace identity (for example the container's os-release on Linux). + pub userspace: Option, + /// Kernel or host facts visible from this process; these can differ from userspace. + pub host: Option, + pub process_architecture: Option, + pub process_abi: Option, + pub libc: Option, + pub emulation: EmulationStatus, + /// Facts unavailable to this detector remain explicit instead of receiving guesses. + pub unknown_facts: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct UserspaceIdentity { + pub family: String, + pub id: Option, + pub version_id: Option, + pub name: Option, + pub product: Option, + pub major: Option, + pub minor: Option, + pub build: Option, + pub kind: Option, + /// Unrecognized os-release keys are retained for future evaluators. + pub extra: BTreeMap, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct HostIdentity { + pub family: String, + pub version: Option, + pub architecture: Option, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum OperatingSystemKind { + Client, + Server, + Unknown, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "family", content = "version", rename_all = "snake_case")] +pub enum LibcIdentity { + Gnu(Option), + Musl(Option), + Unknown, +} + +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum EmulationStatus { + Native, + Emulated, + #[default] + Unknown, +} + +/// Caller-selected behavior for environments whose execution mode is emulated or unknown. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum EmulationPolicy { + RequireNative, + AllowEmulated, + AllowUnknown, +} + +impl EmulationPolicy { + pub fn accepts(self, status: &EmulationStatus) -> bool { + matches!( + (self, status), + (_, EmulationStatus::Native) + | (Self::AllowEmulated, EmulationStatus::Emulated) + | (Self::AllowUnknown, EmulationStatus::Unknown) + ) + } +} + +/// Detects the current effective environment without blocking the async executor. +pub async fn detect() -> Result { + tokio::task::spawn_blocking(detect_blocking) + .await + .map_err(|error| format!("plugin environment worker failed: {error}")) + .and_then(|result| result) +} + +fn detect_blocking() -> Result { + #[cfg(target_os = "linux")] + { + detect_linux() + } + #[cfg(windows)] + { + detect_windows() + } + #[cfg(not(any(target_os = "linux", windows)))] + { + Ok(PluginEnvironment { + unknown_facts: vec!["unsupported_host_platform".into()], + ..Default::default() + }) + } +} + +#[cfg(target_os = "linux")] +fn detect_linux() -> Result { + let mut unknown_facts = Vec::new(); + let os_release = std::fs::read_to_string("/etc/os-release") + .or_else(|_| std::fs::read_to_string("/usr/lib/os-release")); + let userspace = match os_release { + Ok(text) => { + let identity = parse_os_release(&text); + if identity.id.is_none() { + unknown_facts.push("linux_distribution_id".into()); + } + if identity.version_id.is_none() { + unknown_facts.push("linux_distribution_version".into()); + } + Some(identity) + } + Err(_) => { + unknown_facts.push("linux_os_release".into()); + None + } + }; + let uts = rustix::system::uname(); + let kernel = uts.sysname().to_string_lossy().into_owned(); + let kernel_version = uts.release().to_string_lossy().into_owned(); + let kernel_arch = normalize_arch(&uts.machine().to_string_lossy()); + let process_arch = normalize_arch(std::env::consts::ARCH); + let emulation = match (&process_arch, &kernel_arch) { + (Some(process), Some(host)) if process == host => EmulationStatus::Native, + (Some(_), Some(_)) => EmulationStatus::Emulated, + _ => EmulationStatus::Unknown, + }; + let (libc, abi) = detect_libc(); + if libc.is_none() { + unknown_facts.push("libc_identity".into()); + } else if matches!( + libc.as_ref(), + Some(LibcIdentity::Gnu(None) | LibcIdentity::Musl(None)) + ) { + unknown_facts.push("libc_version".into()); + } + if abi.is_none() { + unknown_facts.push("process_abi".into()); + } + Ok(PluginEnvironment { + userspace, + host: Some(HostIdentity { + family: kernel, + version: Some(kernel_version), + architecture: kernel_arch.clone(), + }), + process_architecture: process_arch, + process_abi: abi, + libc, + emulation, + unknown_facts, + }) +} + +#[cfg(target_os = "linux")] +fn parse_os_release(input: &str) -> UserspaceIdentity { + let mut fields = BTreeMap::new(); + for line in input.lines() { + let Some((key, value)) = line.split_once('=') else { + continue; + }; + if key.is_empty() + || !key + .bytes() + .all(|b| b.is_ascii_uppercase() || b.is_ascii_digit() || b == b'_') + { + continue; + } + let value = value.trim(); + let value = if value.len() >= 2 + && ((value.starts_with('"') && value.ends_with('"')) + || (value.starts_with('\'') && value.ends_with('\''))) + { + &value[1..value.len() - 1] + } else { + value + }; + fields.insert( + key.to_owned(), + value.replace("\\\"", "\"").replace("\\\\", "\\"), + ); + } + let id = fields.remove("ID"); + let version_id = fields.remove("VERSION_ID"); + let name = fields.remove("NAME"); + let version = version_id.as_deref().unwrap_or_default(); + let mut parts = version.split(['.', '-']); + let major = parts.next().and_then(|part| part.parse().ok()); + let minor = parts.next().and_then(|part| part.parse().ok()); + // ID_LIKE is retained as diagnostic ancestry only; it does not imply compatibility. + let family = id.clone().unwrap_or_else(|| "unknown".into()); + UserspaceIdentity { + family, + id, + version_id, + name, + product: None, + major, + minor, + build: None, + kind: None, + extra: fields, + } +} + +#[cfg(target_os = "linux")] +fn detect_libc() -> (Option, Option) { + let Ok(maps) = std::fs::read_to_string("/proc/self/maps") else { + return (None, None); + }; + let path = maps + .lines() + .filter_map(|line| line.split_whitespace().last()) + .find(|path| path.contains("libc.so") || path.contains("ld-musl")); + let Some(path) = path else { + return (None, None); + }; + let name = path.rsplit('/').next().unwrap_or(path); + let Ok(bytes) = std::fs::read(path) else { + return ( + Some(if name.contains("musl") { + LibcIdentity::Musl(None) + } else { + LibcIdentity::Unknown + }), + None, + ); + }; + let version = find_version( + &bytes, + if name.contains("musl") { + b"Version " + } else { + b"release version " + }, + ); + let identity = if name.contains("musl") { + LibcIdentity::Musl(version.clone()) + } else if name.contains("libc.so") { + LibcIdentity::Gnu(version.clone()) + } else { + LibcIdentity::Unknown + }; + let abi = match &identity { + LibcIdentity::Gnu(_) => Some("gnu".into()), + LibcIdentity::Musl(_) => Some("musl".into()), + LibcIdentity::Unknown => None, + }; + (Some(identity), abi) +} + +#[cfg(any(target_os = "linux", test))] +fn find_version(bytes: &[u8], marker: &[u8]) -> Option { + let start = bytes + .windows(marker.len()) + .position(|window| window == marker)? + + marker.len(); + let mut end = start; + while end < bytes.len() && bytes[end].is_ascii_digit() { + end += 1; + } + while end + 1 < bytes.len() && bytes[end] == b'.' && bytes[end + 1].is_ascii_digit() { + end += 1; + while end < bytes.len() && bytes[end].is_ascii_digit() { + end += 1; + } + } + let digits = bytes[start..end].to_vec(); + (!digits.is_empty()).then(|| String::from_utf8_lossy(&digits).into_owned()) +} + +#[cfg(any(target_os = "linux", test))] +fn normalize_arch(arch: &str) -> Option { + let lowercase = arch.to_ascii_lowercase(); + let normalized = match lowercase.as_str() { + "x86_64" | "amd64" => "x86_64", + "i386" | "i486" | "i586" | "i686" | "x86" => "x86", + "aarch64" | "arm64" => "aarch64", + "armv7l" | "armv7" => "armv7", + "riscv64" => "riscv64", + "s390x" => "s390x", + other if !other.is_empty() => other, + _ => return None, + }; + Some(normalized.into()) +} + +#[cfg(windows)] +fn detect_windows() -> Result { + use windows_sys::Win32::System::SystemInformation::OSVERSIONINFOEXW; + #[link(name = "ntdll")] + unsafe extern "system" { + fn RtlGetVersion(info: *mut OSVERSIONINFOEXW) -> i32; + } + let mut version = OSVERSIONINFOEXW { + dwOSVersionInfoSize: std::mem::size_of::() as u32, + ..Default::default() + }; + // SAFETY: the struct is correctly sized and writable for the duration of the OS call. + if unsafe { RtlGetVersion(&mut version) } < 0 { + return Err("Windows version query failed".into()); + } + let arch = windows_process_architecture(); + let process_architecture = arch.as_ref().map(|(process, _)| process.clone()); + let host_architecture = arch.as_ref().map(|(_, host)| host.clone()); + let emulation = match (&process_architecture, &host_architecture) { + (Some(process), Some(host)) if process == host => EmulationStatus::Native, + (Some(_), Some(_)) => EmulationStatus::Emulated, + _ => EmulationStatus::Unknown, + }; + let mut unknown_facts = Vec::new(); + if process_architecture.is_none() { + unknown_facts.push("windows_process_architecture".into()); + } + if host_architecture.is_none() { + unknown_facts.push("windows_native_architecture".into()); + } + if version.wProductType == 0 { + unknown_facts.push("windows_product_kind".into()); + } + let mut product_sku = 0u32; + // SAFETY: scalar version inputs and writable output match the Win32 contract. + let product = if unsafe { + windows_sys::Win32::System::SystemInformation::GetProductInfo( + version.dwMajorVersion, + version.dwMinorVersion, + version.wServicePackMajor as u32, + version.wServicePackMinor as u32, + &mut product_sku, + ) + } != 0 + { + Some(format!("Windows product SKU 0x{product_sku:04x}")) + } else { + unknown_facts.push("windows_product_sku".into()); + None + }; + let userspace = windows_userspace( + version.dwMajorVersion, + version.dwMinorVersion, + version.dwBuildNumber, + version.wProductType, + product, + ); + let abi = if cfg!(target_env = "msvc") { + Some("msvc".into()) + } else if cfg!(target_env = "gnu") { + Some("gnu".into()) + } else { + unknown_facts.push("windows_abi".into()); + None + }; + Ok(PluginEnvironment { + userspace: Some(userspace), + host: Some(HostIdentity { + family: "windows_nt_kernel".into(), + version: Some(format!( + "{}.{}", + version.dwMajorVersion, version.dwMinorVersion + )), + architecture: host_architecture, + }), + process_architecture, + process_abi: abi, + libc: None, + emulation, + unknown_facts, + }) +} + +#[cfg(any(windows, test))] +fn windows_userspace( + major: u32, + minor: u32, + build: u32, + product_type: u8, + product: Option, +) -> UserspaceIdentity { + let kind = match product_type { + 1 => OperatingSystemKind::Client, + 2 | 3 => OperatingSystemKind::Server, + _ => OperatingSystemKind::Unknown, + }; + UserspaceIdentity { + family: "windows".into(), + id: None, + version_id: Some(format!("{major}.{minor}.{build}")), + name: Some( + if kind == OperatingSystemKind::Server { + "Windows Server" + } else { + "Windows" + } + .into(), + ), + product, + major: Some(major), + minor: Some(minor), + build: Some(build), + kind: Some(kind), + extra: BTreeMap::new(), + } +} + +#[cfg(windows)] +fn windows_process_architecture() -> Option<(String, String)> { + use windows_sys::Win32::System::Threading::{GetCurrentProcess, IsWow64Process2}; + let mut process_machine = 0u16; + let mut native_machine = 0u16; + // SAFETY: valid pseudo-handle and writable outputs supplied to the OS API. + let ok = unsafe { + IsWow64Process2( + GetCurrentProcess(), + &mut process_machine, + &mut native_machine, + ) + }; + if ok == 0 { + return None; + } + let native = machine_name(native_machine)?; + let process = if process_machine == 0 { + native.clone() + } else { + machine_name(process_machine)? + }; + Some((process, native)) +} + +#[cfg(windows)] +fn machine_name(machine: u16) -> Option { + match machine { + 0x014c => Some("x86".into()), + 0x8664 => Some("x86_64".into()), + 0xaa64 => Some("aarch64".into()), + _ => None, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[cfg(target_os = "linux")] + #[test] + fn parses_linux_release_identity_and_preserves_unknown_fields() { + let identity = parse_os_release( + "ID=debian\nNAME=\"Debian GNU/Linux\"\nVERSION_ID=\"12.4\"\nBUILD_ID=custom\n", + ); + assert_eq!(identity.id.as_deref(), Some("debian")); + assert_eq!(identity.name.as_deref(), Some("Debian GNU/Linux")); + assert_eq!(identity.major, Some(12)); + assert_eq!(identity.minor, Some(4)); + assert_eq!( + identity.extra.get("BUILD_ID").map(String::as_str), + Some("custom") + ); + } + + #[cfg(target_os = "linux")] + #[test] + fn missing_os_release_values_remain_unknown() { + let identity = parse_os_release("PRETTY_NAME=\"Future Linux\"\n"); + assert_eq!(identity.family, "unknown"); + assert_eq!(identity.id, None); + assert_eq!(identity.version_id, None); + assert_eq!( + identity.extra.get("PRETTY_NAME").map(String::as_str), + Some("Future Linux") + ); + } + + #[test] + fn emulation_must_follow_the_explicit_callers_policy() { + assert!(!EmulationPolicy::RequireNative.accepts(&EmulationStatus::Emulated)); + assert!(EmulationPolicy::AllowEmulated.accepts(&EmulationStatus::Emulated)); + assert!(!EmulationPolicy::RequireNative.accepts(&EmulationStatus::Unknown)); + assert!(EmulationPolicy::AllowUnknown.accepts(&EmulationStatus::Unknown)); + } + + #[test] + fn normalizes_architecture_aliases_without_guessing_empty_values() { + assert_eq!(normalize_arch("AMD64").as_deref(), Some("x86_64")); + assert_eq!(normalize_arch("aarch64").as_deref(), Some("aarch64")); + assert_eq!(normalize_arch("").as_deref(), None); + } + + #[test] + fn windows_client_and_server_fixture_preserves_build_and_product() { + let client = windows_userspace(10, 0, 22631, 1, Some("Windows product SKU 0x0030".into())); + assert_eq!(client.kind, Some(OperatingSystemKind::Client)); + assert_eq!(client.build, Some(22631)); + assert_eq!( + client.product.as_deref(), + Some("Windows product SKU 0x0030") + ); + let server = windows_userspace(10, 0, 20348, 3, None); + assert_eq!(server.kind, Some(OperatingSystemKind::Server)); + assert_eq!(server.name.as_deref(), Some("Windows Server")); + assert_eq!(server.build, Some(20348)); + } + + #[test] + fn recognizes_libc_versions_from_mapped_binary_metadata() { + assert_eq!( + find_version(b"...release version 2.37 GNU...", b"release version ").as_deref(), + Some("2.37") + ); + assert_eq!( + find_version(b"...Version 1.2.4...", b"Version ").as_deref(), + Some("1.2.4") + ); + assert_eq!( + find_version(b"no version metadata", b"release version "), + None + ); + } +} diff --git a/crates/platform/src/plugin_files.rs b/crates/platform/src/plugin_files.rs new file mode 100644 index 000000000..0965165f6 --- /dev/null +++ b/crates/platform/src/plugin_files.rs @@ -0,0 +1,511 @@ +//! File access of third-party plugins, confined beneath one user-approved root. +//! +//! The root is a directory the user chose for one plugin and one game. Everything a plugin names +//! afterwards is a *relative path* of plain components below it, and every operation re-walks +//! that path from the root and refuses anything that would leave it: +//! +//! * a component that is `..`, empty, absolute, holds a separator, a control character or a +//! drive/stream marker is rejected before the disk is touched; +//! * a symbolic link, junction or other reparse point is never followed, at any depth, so a +//! directory replaced by a link after a listing is refused when it is used; +//! * a directory on another volume (a mount inside the root) is refused; +//! * the host's own data folders ([`Reserved`]) are never entered, listed or reached, even when +//! they sit under an otherwise approved parent; +//! * only regular files and directories exist for the plugin: devices, pipes and sockets are not +//! listed and cannot be opened. +//! +//! On Linux the walk uses `openat` with `O_NOFOLLOW` from a directory handle, so there is no +//! window between checking a component and using it. On Windows each component is checked as a +//! reparse point and the opened handle's final path is verified to lie under the root. +//! +//! Nothing here returns an absolute path. The work is blocking; callers run it on a worker. + +use std::io; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::Instant; + +#[cfg(unix)] +mod unix; +#[cfg(unix)] +use unix as sys; +#[cfg(windows)] +mod windows; +#[cfg(windows)] +use windows as sys; + +/// The most entries read from one directory; a larger directory is refused rather than listed +/// in part. +pub const MAX_DIR_ENTRIES: usize = 20_000; +/// The largest file a plugin may grow through the API. +pub const MAX_FILE_BYTES: u64 = 512 * 1024 * 1024; +/// The deepest relative path. +pub const MAX_DEPTH: usize = 64; +/// The longest single name, in bytes. +pub const MAX_NAME_BYTES: usize = 255; + +/// Why an operation was refused. +#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)] +pub enum FileError { + /// The path leaves the approved area: traversal, a link, another volume, a reserved host + /// folder or a name that is not allowed. + #[error("the path is outside the approved access")] + Denied, + /// The operating system refused access to something inside the approved area. + #[error("the operating system refused access")] + Access, + #[error("not found")] + NotFound, + #[error("not a regular file")] + NotAFile, + #[error("not a directory")] + NotADirectory, + /// A directory with too many entries, or a file that would grow too large. + #[error("too large")] + TooLarge, + /// A write starting beyond the end of the file. + #[error("the offset is beyond the end of the file")] + OutOfRange, + /// The approved root is gone or is no longer the folder the user approved. + #[error("the approved folder changed")] + RootChanged, + #[error("the file operation failed")] + Io, +} + +impl From for FileError { + fn from(error: io::Error) -> Self { + match error.kind() { + io::ErrorKind::NotFound => Self::NotFound, + io::ErrorKind::PermissionDenied => Self::Access, + _ => { + tracing::debug!(%error, "plugin file operation failed"); + Self::Io + } + } + } +} + +/// Identifies a directory on disk independently of its path: the volume and the node on it. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct Identity { + pub volume: u64, + pub node: u64, +} + +/// Identifies a path independently of its name: the volume and the node on it. The path is +/// followed as the system resolves it, so callers that approve a link-free file should inspect it +/// first. +pub fn identity_of(path: &Path) -> Result { + sys::identity_of(path).map_err(FileError::from) +} + +/// Host folders no plugin may reach. Built once from the host's data folders. +#[derive(Clone, Debug, Default)] +pub struct Reserved { + paths: Vec, + ids: Vec, +} + +impl Reserved { + /// Reserves each folder that exists (by identity) and by canonical path. + pub fn new(folders: &[PathBuf]) -> Self { + let mut reserved = Self::default(); + for folder in folders { + let canonical = std::fs::canonicalize(folder).unwrap_or_else(|_| folder.clone()); + if let Ok(id) = sys::identity_of(&canonical) { + reserved.ids.push(id); + } + reserved.paths.push(canonical); + } + reserved + } + + /// Whether `path` is a reserved folder or lies inside one. A path that does not exist is + /// judged by its text. + pub fn is_reserved(&self, path: &Path) -> bool { + let canonical = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf()); + self.covers(&canonical) || sys::identity_of(&canonical).is_ok_and(|id| self.holds_id(id)) + } + + fn holds_id(&self, id: Identity) -> bool { + self.ids.contains(&id) + } + + /// Whether `canonical` is a reserved folder or lies inside one. + fn covers(&self, canonical: &Path) -> bool { + self.paths + .iter() + .any(|reserved| canonical.starts_with(reserved)) + } +} + +/// A root the user approved: its canonical location and what it was when approved. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ApprovedRoot { + pub path: PathBuf, + pub identity: Identity, +} + +/// Validates a folder the user chose as a root. The path may pass through links the user +/// chose; what is stored is its canonical location. Refused: not a directory, a filesystem +/// root, a path that is not valid Unicode, or one inside a reserved host folder. +pub fn approve_root(chosen: &Path, reserved: &Reserved) -> Result { + let canonical = std::fs::canonicalize(chosen)?; + if !canonical.is_dir() { + return Err(FileError::NotADirectory); + } + if canonical.parent().is_none() || canonical.to_str().is_none() { + return Err(FileError::Denied); + } + if reserved.covers(&canonical) { + return Err(FileError::Denied); + } + let identity = sys::identity_of(&canonical)?; + if reserved.holds_id(identity) { + return Err(FileError::Denied); + } + Ok(ApprovedRoot { + path: canonical, + identity, + }) +} + +/// One entry of a directory. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Entry { + pub name: String, + pub directory: bool, + pub size: u64, + /// Unix seconds. + pub modified: i64, + /// The sub-second part of the modification time, in nanoseconds, as the system reported it. + /// Zero when the system reported whole seconds (or nothing finer). + pub modified_nanos: u32, + /// Whether the entry carries the read-only attribute (Windows) or has no write bit in its + /// mode (Linux). This is metadata, not what the current user may do: see [`AccessInfo`]. + pub read_only: bool, +} + +/// An answer that may be unknown: the system did not say, or the question does not apply. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Tri { + Allowed, + Denied, + Unknown, +} + +/// How [`Confined::access`] finds out, named in the answers so a plugin knows what an `unknown` +/// or an `allowed` rests on. +#[cfg(unix)] +pub const ACCESS_METHOD: &str = "kernel_access_check"; +/// How [`Confined::access`] finds out, named in the answers so a plugin knows what an `unknown` +/// or an `allowed` rests on. +#[cfg(windows)] +pub const ACCESS_METHOD: &str = "open_probe"; + +/// What the current operating-system user may do with an entry, found without changing the +/// entry, its permissions or anything else. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct AccessInfo { + pub directory: bool, + /// The read-only attribute or mode, as metadata. + pub read_only: bool, + /// Read the file, or list the directory. + pub read: Tri, + /// Write the file, or add entries to the directory. + pub write: Tri, + /// Create entries in the directory; unknown for a file, where it does not apply. + pub create: Tri, + /// Delete the entry, which depends on its parent folder. + pub delete: Tri, +} + +/// How much a walk may do before it stops. +pub struct Budget<'a> { + pub max_entries: usize, + pub deadline: Instant, + /// Set by the caller to stop the walk at the next entry. + pub cancel: &'a AtomicBool, +} + +/// The content digest of one file. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct FileDigest { + pub sha256: [u8; 32], + /// The bytes that were read and hashed. + pub bytes: u64, +} + +/// Bytes read at a time when hashing. +pub const HASH_CHUNK_BYTES: usize = 1024 * 1024; + +/// How a walk ended. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Walk { + /// Whether every entry below the start was visited. False after a cut, a cancellation, a + /// folder that could not be read, or a tree deeper than [`MAX_DEPTH`]. + pub complete: bool, + /// Folders below the start that the operating system would not let us read. + pub unreadable: u64, + pub visited: u64, + /// The budget or a cancellation stopped it, as opposed to an unreadable folder. + pub stopped: bool, +} + +/// What a write targets. +#[derive(Clone, Copy, Debug)] +pub enum Target<'a> { + /// An existing regular file. + Existing(&'a [String]), + /// The file `name` inside a directory, created if it does not exist. + Create { + directory: &'a [String], + name: &'a str, + }, +} + +/// File access below one approved root. +pub struct Confined { + root: ApprovedRoot, + reserved: Reserved, +} + +/// Whether `name` is one plain path component. +pub fn valid_component(name: &str) -> bool { + !name.is_empty() + && name.len() <= MAX_NAME_BYTES + && name != "." + && name != ".." + && !name + .chars() + .any(|c| c.is_control() || matches!(c, '/' | '\\')) +} + +/// Whether `name` is allowed for a file the plugin creates: a plain component that is also +/// valid on every platform, so a file made on Linux can be backed up on Windows. +pub fn valid_new_name(name: &str) -> bool { + if !valid_component(name) || name.ends_with([' ', '.']) { + return false; + } + if name.contains(['<', '>', ':', '"', '|', '?', '*']) { + return false; + } + let stem = name.split('.').next().unwrap_or("").to_ascii_uppercase(); + let reserved = matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL") + || ["COM", "LPT"].iter().any(|prefix| { + stem.strip_prefix(prefix).is_some_and(|digit| { + matches!(digit, "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9") + }) + }); + !reserved +} + +fn check_path(path: &[String]) -> Result<(), FileError> { + if path.len() > MAX_DEPTH || !path.iter().all(|part| valid_component(part)) { + return Err(FileError::Denied); + } + Ok(()) +} + +impl Confined { + /// Opens the approved root again. Fails with [`FileError::RootChanged`] when the folder is + /// gone or is no longer the one that was approved (replaced, or another volume mounted + /// there). + pub fn open(root: &ApprovedRoot, reserved: &Reserved) -> Result { + let current = sys::identity_of(&root.path).map_err(|_| FileError::RootChanged)?; + if current != root.identity { + return Err(FileError::RootChanged); + } + let canonical = std::fs::canonicalize(&root.path).map_err(|_| FileError::RootChanged)?; + if canonical != root.path || reserved.covers(&canonical) { + return Err(FileError::RootChanged); + } + Ok(Self { + root: root.clone(), + reserved: reserved.clone(), + }) + } + + /// The entries of the directory `directory` (relative to the root, empty for the root) + /// whose names sort after `after`, at most `limit`, and whether more follow. + pub fn list( + &self, + directory: &[String], + after: Option<&str>, + limit: usize, + ) -> Result<(Vec, bool), FileError> { + check_path(directory)?; + let mut entries = sys::list(self, directory)?; + entries.sort_by(|a, b| a.name.cmp(&b.name)); + let mut rest = entries + .into_iter() + .filter(|entry| after.is_none_or(|after| entry.name.as_str() > after)); + let page: Vec = rest.by_ref().take(limit).collect(); + let more = rest.next().is_some(); + Ok((page, more)) + } + + /// Up to `max` bytes of the file from `offset`, and whether the end of the file was reached. + pub fn read( + &self, + file: &[String], + offset: u64, + max: usize, + ) -> Result<(Vec, bool), FileError> { + check_path(file)?; + if file.is_empty() { + return Err(FileError::NotAFile); + } + sys::read(self, file, offset, max) + } + + /// Writes `contents` at `offset`; with `truncate` the file ends where the write does. The + /// offset may not pass the end of the file, and the file may not grow past + /// [`MAX_FILE_BYTES`]. Returns the new size. + pub fn write( + &self, + target: Target<'_>, + offset: u64, + contents: &[u8], + truncate: bool, + ) -> Result { + match target { + Target::Existing(file) => { + check_path(file)?; + if file.is_empty() { + return Err(FileError::NotAFile); + } + } + Target::Create { directory, name } => { + check_path(directory)?; + if !valid_new_name(name) { + return Err(FileError::Denied); + } + } + } + let end = offset + .checked_add(contents.len() as u64) + .ok_or(FileError::TooLarge)?; + if end > MAX_FILE_BYTES { + return Err(FileError::TooLarge); + } + sys::write(self, target, offset, contents, truncate) + } + + /// The entry at `path` (empty for the root itself, whose name is empty), as the system + /// describes it, without following links. + pub fn stat(&self, path: &[String]) -> Result { + check_path(path)?; + sys::stat(self, path) + } + + /// What the current user may do with the entry at `path` (empty for the root). Nothing is + /// changed to find out. + pub fn access(&self, path: &[String]) -> Result { + check_path(path)?; + sys::access(self, path) + } + + /// Visits every file and directory below `start` (depth first, in name order) until the tree + /// is done or `budget` runs out. An error reading `start` itself is returned; a folder deeper + /// down that cannot be read is counted and skipped, and the walk is then not complete. + pub fn walk_tree( + &self, + start: &[String], + budget: &Budget<'_>, + visit: &mut dyn FnMut(&[String], &Entry), + ) -> Result { + check_path(start)?; + let mut walk = Walk { + complete: true, + ..Walk::default() + }; + self.descend(start, budget, visit, &mut walk)?; + Ok(walk) + } + + fn descend( + &self, + directory: &[String], + budget: &Budget<'_>, + visit: &mut dyn FnMut(&[String], &Entry), + walk: &mut Walk, + ) -> Result<(), FileError> { + let mut entries = sys::list(self, directory)?; + entries.sort_by(|a, b| a.name.cmp(&b.name)); + for entry in entries { + if budget.cancel.load(Ordering::Relaxed) + || Instant::now() >= budget.deadline + || walk.visited >= budget.max_entries as u64 + { + walk.complete = false; + walk.stopped = true; + return Ok(()); + } + walk.visited += 1; + let mut path = directory.to_vec(); + path.push(entry.name.clone()); + visit(&path, &entry); + if !entry.directory { + continue; + } + if path.len() >= MAX_DEPTH { + walk.complete = false; + continue; + } + if self.descend(&path, budget, visit, walk).is_err() { + walk.complete = false; + walk.unreadable += 1; + } + if walk.stopped { + return Ok(()); + } + } + Ok(()) + } + + /// The SHA-256 of the file's content, read in chunks from the start so a large file is never + /// held in memory. Every chunk re-walks the path from the root, like any read. `None` when + /// `cancel` was set or `deadline` passed first; nothing is written or changed. + pub fn hash_file( + &self, + file: &[String], + cancel: &AtomicBool, + deadline: Instant, + ) -> Result, FileError> { + use sha2::{Digest, Sha256}; + check_path(file)?; + if file.is_empty() { + return Err(FileError::NotAFile); + } + let mut hash = Sha256::new(); + let mut offset = 0_u64; + loop { + if cancel.load(Ordering::Relaxed) || Instant::now() >= deadline { + return Ok(None); + } + let (chunk, eof) = sys::read(self, file, offset, HASH_CHUNK_BYTES)?; + hash.update(&chunk); + offset += chunk.len() as u64; + if eof || chunk.is_empty() { + return Ok(Some(FileDigest { + sha256: hash.finalize().into(), + bytes: offset, + })); + } + } + } + + /// Deletes one regular file. Directories are never deleted. + pub fn delete(&self, file: &[String]) -> Result<(), FileError> { + check_path(file)?; + if file.is_empty() { + return Err(FileError::NotAFile); + } + sys::delete(self, file) + } +} + +#[cfg(all(test, unix))] +mod tests; diff --git a/crates/platform/src/plugin_files/tests.rs b/crates/platform/src/plugin_files/tests.rs new file mode 100644 index 000000000..441bae20c --- /dev/null +++ b/crates/platform/src/plugin_files/tests.rs @@ -0,0 +1,970 @@ +use std::fs; +use std::os::unix::fs::symlink; + +use super::*; + +fn path(parts: &[&str]) -> Vec { + parts.iter().map(|part| (*part).to_owned()).collect() +} + +struct Area { + temp: tempfile::TempDir, + root: PathBuf, +} + +impl Area { + /// `/outside` holds a secret; `/root` is the approved root. + fn new() -> Self { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path().join("root"); + fs::create_dir_all(root.join("saves")).unwrap(); + fs::create_dir_all(temp.path().join("outside")).unwrap(); + fs::write(temp.path().join("outside/secret.txt"), b"secret").unwrap(); + fs::write(root.join("a.txt"), b"hello world").unwrap(); + fs::write(root.join("saves/slot1.sav"), b"save-1").unwrap(); + Self { temp, root } + } + + fn outside(&self) -> PathBuf { + self.temp.path().join("outside") + } + + fn confined(&self) -> Confined { + self.confined_with(&Reserved::default()) + } + + fn confined_with(&self, reserved: &Reserved) -> Confined { + let root = approve_root(&self.root, reserved).unwrap(); + Confined::open(&root, reserved).unwrap() + } +} + +fn names(entries: &[Entry]) -> Vec<&str> { + entries.iter().map(|entry| entry.name.as_str()).collect() +} + +#[test] +fn a_root_lists_reads_writes_and_deletes() { + let area = Area::new(); + let files = area.confined(); + + let (entries, more) = files.list(&[], None, 100).unwrap(); + assert!(!more); + assert_eq!(names(&entries), ["a.txt", "saves"]); + assert_eq!((entries[0].directory, entries[0].size), (false, 11)); + assert!(entries[1].directory); + assert!(entries[0].modified > 1_000_000_000); + + let (bytes, eof) = files.read(&path(&["a.txt"]), 6, 100).unwrap(); + assert_eq!((bytes.as_slice(), eof), (&b"world"[..], true)); + let (bytes, eof) = files.read(&path(&["a.txt"]), 0, 5).unwrap(); + assert_eq!((bytes.as_slice(), eof), (&b"hello"[..], false)); + let (bytes, eof) = files.read(&path(&["saves", "slot1.sav"]), 100, 5).unwrap(); + assert_eq!((bytes.len(), eof), (0, true)); + + let target = Target::Create { + directory: &path(&["saves"]), + name: "slot2.sav", + }; + assert_eq!(files.write(target, 0, b"new save", false).unwrap(), 8); + assert_eq!( + fs::read(area.root.join("saves/slot2.sav")).unwrap(), + b"new save" + ); + // Overwrite in place, then truncate where the write ends. + let existing = path(&["saves", "slot2.sav"]); + assert_eq!( + files + .write(Target::Existing(&existing), 4, b"SAVE!!", false) + .unwrap(), + 10 + ); + assert_eq!( + fs::read(area.root.join("saves/slot2.sav")).unwrap(), + b"new SAVE!!" + ); + assert_eq!( + files + .write(Target::Existing(&existing), 0, b"x", true) + .unwrap(), + 1 + ); + assert_eq!(fs::read(area.root.join("saves/slot2.sav")).unwrap(), b"x"); + + files.delete(&existing).unwrap(); + assert!(!area.root.join("saves/slot2.sav").exists()); + assert_eq!(files.delete(&existing), Err(FileError::NotFound)); +} + +#[test] +fn listing_pages_by_name() { + let area = Area::new(); + for index in 0..5 { + fs::write(area.root.join(format!("f{index}")), b"x").unwrap(); + } + let files = area.confined(); + let (first, more) = files.list(&[], None, 3).unwrap(); + assert_eq!(names(&first), ["a.txt", "f0", "f1"]); + assert!(more); + let (second, more) = files.list(&[], Some("f1"), 3).unwrap(); + assert_eq!(names(&second), ["f2", "f3", "f4"]); + assert!(more, "saves still follows"); + let (last, more) = files.list(&[], Some("f4"), 3).unwrap(); + assert_eq!((names(&last), more), (vec!["saves"], false)); +} + +#[test] +fn traversal_and_malformed_paths_are_refused_before_the_disk_is_touched() { + let area = Area::new(); + let files = area.confined(); + for bad in [ + path(&[".."]), + path(&["..", "outside", "secret.txt"]), + path(&["saves", "..", "..", "outside", "secret.txt"]), + path(&["/etc/passwd"]), + path(&["a/b"]), + path(&["saves\\..\\a.txt"]), + path(&["."]), + path(&[""]), + path(&["bad\0name"]), + path(&["a.txt\n"]), + ] { + assert_eq!(files.read(&bad, 0, 10), Err(FileError::Denied), "{bad:?}"); + assert_eq!(files.delete(&bad), Err(FileError::Denied), "{bad:?}"); + assert_eq!( + files.list(&bad, None, 10).unwrap_err(), + FileError::Denied, + "{bad:?}" + ); + assert_eq!( + files.write(Target::Existing(&bad), 0, b"x", false), + Err(FileError::Denied), + "{bad:?}" + ); + } + let too_deep: Vec = (0..=MAX_DEPTH).map(|_| "d".to_owned()).collect(); + assert_eq!( + files.list(&too_deep, None, 1).unwrap_err(), + FileError::Denied + ); + assert!(area.outside().join("secret.txt").exists()); +} + +#[test] +fn names_for_new_files_must_be_plain_and_portable() { + let area = Area::new(); + let files = area.confined(); + for bad in [ + "", + ".", + "..", + "a/b", + "a\\b", + "..\\x", + "con", + "NUL.txt", + "com1", + "LPT9.sav", + "a:b", + "a?b", + "trailing.", + "trailing ", + "q\"q", + &"n".repeat(256), + ] { + let target = Target::Create { + directory: &[], + name: bad, + }; + assert_eq!( + files.write(target, 0, b"x", false), + Err(FileError::Denied), + "{bad:?}" + ); + } + assert_eq!( + fs::read_dir(&area.root).unwrap().count(), + 2, + "nothing was created by the refused names" + ); + for good in [ + "slot.sav", + "archive.tar.gz", + ".hidden", + "ação.sav", + "COM10", + "a b", + ] { + let target = Target::Create { + directory: &[], + name: good, + }; + files.write(target, 0, b"x", false).unwrap(); + } +} + +#[test] +fn links_are_never_followed_at_any_depth() { + let area = Area::new(); + symlink( + area.outside().join("secret.txt"), + area.root.join("link.txt"), + ) + .unwrap(); + symlink(area.outside(), area.root.join("saves/out")).unwrap(); + symlink(area.root.join("a.txt"), area.root.join("inside-link")).unwrap(); + let files = area.confined(); + + // They do not exist for the plugin: not listed. + assert_eq!( + names(&files.list(&[], None, 100).unwrap().0), + ["a.txt", "saves"] + ); + assert_eq!( + names(&files.list(&path(&["saves"]), None, 100).unwrap().0), + ["slot1.sav"] + ); + + // Naming one anyway does not follow it, even when it points inside the root. + for link in [path(&["link.txt"]), path(&["inside-link"])] { + assert_eq!(files.read(&link, 0, 10), Err(FileError::Denied), "{link:?}"); + assert_eq!(files.delete(&link), Err(FileError::Denied), "{link:?}"); + assert_eq!( + files.write(Target::Existing(&link), 0, b"x", false), + Err(FileError::Denied) + ); + } + let through = path(&["saves", "out", "secret.txt"]); + assert_eq!(files.read(&through, 0, 10), Err(FileError::Denied)); + assert_eq!( + files.list(&path(&["saves", "out"]), None, 10).unwrap_err(), + FileError::Denied + ); + let create = Target::Create { + directory: &path(&["saves", "out"]), + name: "dropped.txt", + }; + assert_eq!(files.write(create, 0, b"x", false), Err(FileError::Denied)); + assert!(!area.outside().join("dropped.txt").exists()); + // Creating a file where a link to outside sits is refused and writes nothing through it. + let create = Target::Create { + directory: &[], + name: "link.txt", + }; + assert!(files.write(create, 0, b"overwritten", false).is_err()); + assert_eq!( + fs::read(area.outside().join("secret.txt")).unwrap(), + b"secret" + ); +} + +#[test] +fn a_directory_replaced_by_a_link_after_listing_is_refused_when_used() { + let area = Area::new(); + let files = area.confined(); + // The plugin listed `saves` and holds its path. + let slot = path(&["saves", "slot1.sav"]); + assert_eq!(files.read(&slot, 0, 10).unwrap().0, b"save-1"); + + // Then the directory is swapped for a link to a folder holding a same-named file. + fs::write(area.outside().join("slot1.sav"), b"stolen").unwrap(); + fs::remove_dir_all(area.root.join("saves")).unwrap(); + symlink(area.outside(), area.root.join("saves")).unwrap(); + + assert_eq!(files.read(&slot, 0, 10), Err(FileError::Denied)); + assert_eq!(files.delete(&slot), Err(FileError::Denied)); + assert_eq!( + files.write(Target::Existing(&slot), 0, b"x", false), + Err(FileError::Denied) + ); + assert_eq!( + files.list(&path(&["saves"]), None, 10).unwrap_err(), + FileError::Denied + ); + assert_eq!( + fs::read(area.outside().join("slot1.sav")).unwrap(), + b"stolen" + ); +} + +#[test] +fn a_file_replaced_by_a_link_is_not_followed_on_write_or_delete() { + let area = Area::new(); + let files = area.confined(); + let file = path(&["a.txt"]); + fs::remove_file(area.root.join("a.txt")).unwrap(); + symlink(area.outside().join("secret.txt"), area.root.join("a.txt")).unwrap(); + assert_eq!( + files.write(Target::Existing(&file), 0, b"pwned", true), + Err(FileError::Denied) + ); + assert_eq!(files.read(&file, 0, 10), Err(FileError::Denied)); + assert_eq!( + fs::read(area.outside().join("secret.txt")).unwrap(), + b"secret" + ); + // Deleting a path that is a link never removes anything it points to. + assert_eq!(files.delete(&file), Err(FileError::Denied)); + assert!(area.outside().join("secret.txt").exists()); +} + +#[test] +fn reserved_host_folders_are_neither_listed_nor_reachable_under_an_approved_parent() { + let area = Area::new(); + let reserved_dir = area.root.join("saves/gamenode-data"); + fs::create_dir_all(reserved_dir.join("plugin-data")).unwrap(); + fs::write(reserved_dir.join("plugin-data/storage.sqlite3"), b"private").unwrap(); + let reserved = Reserved::new(std::slice::from_ref(&reserved_dir)); + let files = area.confined_with(&reserved); + + // The reserved folder does not appear, and nothing beneath it can be named. + assert_eq!( + names(&files.list(&path(&["saves"]), None, 100).unwrap().0), + ["slot1.sav"] + ); + for target in [ + path(&["saves", "gamenode-data"]), + path(&["saves", "gamenode-data", "plugin-data"]), + ] { + assert_eq!( + files.list(&target, None, 10).unwrap_err(), + FileError::Denied, + "{target:?}" + ); + } + let secret = path(&["saves", "gamenode-data", "plugin-data", "storage.sqlite3"]); + assert_eq!(files.read(&secret, 0, 10), Err(FileError::Denied)); + assert_eq!(files.delete(&secret), Err(FileError::Denied)); + assert_eq!( + files.write(Target::Existing(&secret), 0, b"x", true), + Err(FileError::Denied) + ); + let create = Target::Create { + directory: &path(&["saves", "gamenode-data"]), + name: "x", + }; + assert_eq!(files.write(create, 0, b"x", false), Err(FileError::Denied)); + assert_eq!( + fs::read(reserved_dir.join("plugin-data/storage.sqlite3")).unwrap(), + b"private" + ); +} + +#[test] +fn a_root_inside_or_equal_to_a_reserved_folder_cannot_be_approved() { + let area = Area::new(); + let reserved = Reserved::new(&[area.root.join("saves")]); + assert_eq!( + approve_root(&area.root.join("saves"), &reserved).unwrap_err(), + FileError::Denied + ); + fs::create_dir_all(area.root.join("saves/deeper")).unwrap(); + assert_eq!( + approve_root(&area.root.join("saves/deeper"), &reserved).unwrap_err(), + FileError::Denied + ); + // Even through a link the user picked: the canonical location decides. + symlink(area.root.join("saves"), area.temp.path().join("shortcut")).unwrap(); + assert_eq!( + approve_root(&area.temp.path().join("shortcut"), &reserved).unwrap_err(), + FileError::Denied + ); + // A parent that merely contains the reserved folder is fine, with the folder excluded. + assert!(approve_root(&area.root, &reserved).is_ok()); +} + +#[test] +fn roots_must_be_real_directories_and_never_the_filesystem_root() { + let area = Area::new(); + let none = Reserved::default(); + assert_eq!( + approve_root(Path::new("/"), &none).unwrap_err(), + FileError::Denied + ); + assert_eq!( + approve_root(&area.root.join("a.txt"), &none).unwrap_err(), + FileError::NotADirectory + ); + assert_eq!( + approve_root(&area.root.join("missing"), &none).unwrap_err(), + FileError::NotFound + ); + let approved = approve_root(&area.root, &none).unwrap(); + assert_eq!(approved.path, fs::canonicalize(&area.root).unwrap()); +} + +#[test] +fn a_root_that_was_replaced_is_no_longer_the_approved_folder() { + let area = Area::new(); + let none = Reserved::default(); + let approved = approve_root(&area.root, &none).unwrap(); + assert!(Confined::open(&approved, &none).is_ok()); + + fs::rename(&area.root, area.temp.path().join("moved")).unwrap(); + assert_eq!( + Confined::open(&approved, &none).err(), + Some(FileError::RootChanged) + ); + // A different folder created at the same path is not the approved one either. + fs::create_dir_all(&area.root).unwrap(); + fs::write(area.root.join("a.txt"), b"impostor").unwrap(); + assert_eq!( + Confined::open(&approved, &none).err(), + Some(FileError::RootChanged) + ); +} + +#[test] +fn special_files_and_other_non_regular_entries_do_not_exist_for_a_plugin() { + let area = Area::new(); + let fifo = area.root.join("pipe"); + rustix::fs::mknodat( + rustix::fs::CWD, + &fifo, + rustix::fs::FileType::Fifo, + rustix::fs::Mode::from_bits_truncate(0o600), + 0, + ) + .unwrap(); + let files = area.confined(); + assert_eq!( + names(&files.list(&[], None, 100).unwrap().0), + ["a.txt", "saves"] + ); + // Opening one must neither hang nor succeed. + assert!(files.read(&path(&["pipe"]), 0, 10).is_err()); + assert!( + files + .write(Target::Existing(&path(&["pipe"])), 0, b"x", false) + .is_err() + ); + assert_eq!(files.delete(&path(&["pipe"])), Err(FileError::NotAFile)); +} + +#[test] +fn directories_are_never_deleted_or_read_as_files() { + let area = Area::new(); + let files = area.confined(); + let dir = path(&["saves"]); + assert_eq!(files.delete(&dir), Err(FileError::NotAFile)); + assert_eq!(files.read(&dir, 0, 10), Err(FileError::NotAFile)); + assert_eq!( + files.write(Target::Existing(&dir), 0, b"x", false), + Err(FileError::NotAFile) + ); + assert!(area.root.join("saves/slot1.sav").exists()); + // And files are not directories. + assert_eq!( + files.list(&path(&["a.txt"]), None, 10).unwrap_err(), + FileError::NotADirectory + ); + assert_eq!(files.read(&[], 0, 10), Err(FileError::NotAFile)); + assert_eq!(files.delete(&[]), Err(FileError::NotAFile)); +} + +#[test] +fn writes_cannot_leave_holes_or_grow_without_bound() { + let area = Area::new(); + let files = area.confined(); + let file = path(&["a.txt"]); + assert_eq!( + files.write(Target::Existing(&file), 12, b"x", false), + Err(FileError::OutOfRange) + ); + assert_eq!( + files + .write(Target::Existing(&file), 11, b"!", false) + .unwrap(), + 12 + ); + assert_eq!( + files.write(Target::Existing(&file), MAX_FILE_BYTES, b"x", false), + Err(FileError::TooLarge) + ); + assert_eq!( + files.write(Target::Existing(&file), u64::MAX, b"x", false), + Err(FileError::TooLarge) + ); + assert_eq!(fs::read(area.root.join("a.txt")).unwrap(), b"hello world!"); + // A new file may not start past its own end either. + let create = Target::Create { + directory: &[], + name: "new", + }; + assert_eq!( + files.write(create, 1, b"x", false), + Err(FileError::OutOfRange) + ); + assert!( + !area.root.join("new").exists(), + "a refused write creates nothing" + ); +} + +#[test] +fn a_directory_with_too_many_entries_is_refused_not_cut_short() { + let area = Area::new(); + let big = area.root.join("big"); + fs::create_dir_all(&big).unwrap(); + for index in 0..(MAX_DIR_ENTRIES + 1) { + fs::File::create(big.join(format!("{index}"))).unwrap(); + } + let files = area.confined(); + assert_eq!( + files.list(&path(&["big"]), None, 10).unwrap_err(), + FileError::TooLarge + ); + assert!(files.list(&[], None, 10).is_ok()); +} + +#[test] +fn errors_never_contain_a_path() { + let area = Area::new(); + let files = area.confined(); + let root = area.root.to_string_lossy().into_owned(); + for error in [ + files.read(&path(&["missing"]), 0, 1).unwrap_err(), + files.read(&path(&[".."]), 0, 1).unwrap_err(), + files.delete(&path(&["saves"])).unwrap_err(), + ] { + let text = format!("{error} {error:?}"); + assert!(!text.contains(&root) && !text.contains('/'), "{text}"); + } +} + +// ---- Inspection (task 13.3): nothing is read, nothing is changed ---- + +use std::os::unix::fs::PermissionsExt; +use std::sync::atomic::AtomicBool; +use std::time::Duration; + +fn running_as_root() -> bool { + rustix::process::geteuid().is_root() +} + +fn budget<'a>(cancel: &'a AtomicBool, max_entries: usize) -> Budget<'a> { + Budget { + max_entries, + deadline: Instant::now() + Duration::from_secs(30), + cancel, + } +} + +fn tree(files: &Confined, start: &[String], max_entries: usize) -> (Vec, Walk) { + let cancel = AtomicBool::new(false); + let mut seen = Vec::new(); + let walk = files + .walk_tree(start, &budget(&cancel, max_entries), &mut |path, entry| { + seen.push(format!( + "{}{}", + path.join("/"), + if entry.directory { "/" } else { "" } + )); + }) + .unwrap(); + (seen, walk) +} + +#[test] +fn a_walk_visits_every_entry_in_name_order_and_says_it_is_complete() { + let area = Area::new(); + fs::create_dir_all(area.root.join("saves/states/deep")).unwrap(); + fs::write(area.root.join("saves/states/deep/s9.sav"), b"x").unwrap(); + fs::write(area.root.join("saves/states/s1.sav"), b"y").unwrap(); + let files = area.confined(); + + let (seen, walk) = tree(&files, &[], 1000); + assert_eq!( + seen, + [ + "a.txt", + "saves/", + "saves/slot1.sav", + "saves/states/", + "saves/states/deep/", + "saves/states/deep/s9.sav", + "saves/states/s1.sav", + ] + ); + assert_eq!( + walk, + Walk { + complete: true, + unreadable: 0, + visited: 7, + stopped: false + } + ); + // A walk may start below the root. + let (below, walk) = tree(&files, &path(&["saves", "states"]), 1000); + assert_eq!( + below, + [ + "saves/states/deep/", + "saves/states/deep/s9.sav", + "saves/states/s1.sav" + ] + ); + assert!(walk.complete); +} + +#[test] +fn a_walk_stops_at_its_budget_and_is_then_not_complete() { + let area = Area::new(); + let files = area.confined(); + let (seen, walk) = tree(&files, &[], 2); + assert_eq!(seen.len(), 2); + assert!(!walk.complete && walk.stopped); + + // Cancelled before it starts: nothing is visited. + let cancel = AtomicBool::new(true); + let mut count = 0; + let walk = files + .walk_tree(&[], &budget(&cancel, 1000), &mut |_, _| count += 1) + .unwrap(); + assert_eq!(count, 0); + assert!(!walk.complete && walk.stopped); + + // A deadline that already passed does the same. + let cancel = AtomicBool::new(false); + let expired = Budget { + max_entries: 1000, + deadline: Instant::now(), + cancel: &cancel, + }; + let walk = files.walk_tree(&[], &expired, &mut |_, _| {}).unwrap(); + assert!(!walk.complete && walk.stopped); +} + +#[test] +fn a_walk_never_follows_links_or_leaves_the_root_and_skips_what_is_not_a_file() { + let area = Area::new(); + symlink(area.outside(), area.root.join("escape")).unwrap(); + symlink( + area.outside().join("secret.txt"), + area.root.join("saves/link.sav"), + ) + .unwrap(); + let files = area.confined(); + let (seen, walk) = tree(&files, &[], 1000); + assert_eq!(seen, ["a.txt", "saves/", "saves/slot1.sav"]); + assert!( + walk.complete, + "a link does not exist for the plugin, so nothing is missing" + ); + // The start must be inside the root. + assert_eq!( + files + .walk_tree( + &path(&["escape"]), + &budget(&AtomicBool::new(false), 10), + &mut |_, _| {} + ) + .unwrap_err(), + FileError::Denied + ); + assert_eq!( + files + .walk_tree( + &path(&["missing"]), + &budget(&AtomicBool::new(false), 10), + &mut |_, _| {} + ) + .unwrap_err(), + FileError::NotFound + ); +} + +#[test] +fn a_folder_that_cannot_be_read_is_counted_and_the_walk_goes_on() { + if running_as_root() { + return; // root reads everything + } + let area = Area::new(); + fs::create_dir_all(area.root.join("locked")).unwrap(); + fs::write(area.root.join("locked/hidden.sav"), b"h").unwrap(); + fs::set_permissions(area.root.join("locked"), fs::Permissions::from_mode(0o000)).unwrap(); + let files = area.confined(); + let (seen, walk) = tree(&files, &[], 1000); + fs::set_permissions(area.root.join("locked"), fs::Permissions::from_mode(0o755)).unwrap(); + assert_eq!(seen, ["a.txt", "locked/", "saves/", "saves/slot1.sav"]); + assert_eq!( + (walk.complete, walk.unreadable, walk.stopped), + (false, 1, false) + ); +} + +#[test] +fn a_tree_deeper_than_the_limit_is_cut_and_not_complete() { + let area = Area::new(); + let mut deep = area.root.clone(); + for n in 0..MAX_DEPTH + 2 { + deep = deep.join(format!("d{n}")); + } + fs::create_dir_all(&deep).unwrap(); + let files = area.confined(); + let (seen, walk) = tree(&files, &[], 10_000); + assert!(seen.len() < MAX_DEPTH + 10); + assert!(!walk.complete && !walk.stopped); +} + +#[test] +fn stat_describes_the_root_a_file_and_a_folder_without_following_links() { + let area = Area::new(); + symlink(area.outside(), area.root.join("escape")).unwrap(); + let files = area.confined(); + + let root = files.stat(&[]).unwrap(); + assert_eq!( + (root.name.as_str(), root.directory, root.size), + ("", true, 0) + ); + let file = files.stat(&path(&["a.txt"])).unwrap(); + assert_eq!( + (file.name.as_str(), file.directory, file.size), + ("a.txt", false, 11) + ); + assert!(!file.read_only); + assert!(file.modified > 1_000_000_000); + let folder = files.stat(&path(&["saves"])).unwrap(); + assert!(folder.directory); + assert_eq!( + files.stat(&path(&["escape"])).unwrap_err(), + FileError::Denied + ); + assert_eq!( + files.stat(&path(&["nothing"])).unwrap_err(), + FileError::NotFound + ); + assert_eq!( + files.stat(&path(&["..", "outside"])).unwrap_err(), + FileError::Denied + ); +} + +#[test] +fn stat_reports_the_sub_second_part_of_a_modification_time_as_the_system_gave_it() { + let area = Area::new(); + let file = fs::File::options() + .write(true) + .open(area.root.join("a.txt")) + .unwrap(); + let stamp = std::time::UNIX_EPOCH + Duration::new(1_700_000_000, 123_456_789); + file.set_modified(stamp).unwrap(); + let entry = area.confined().stat(&path(&["a.txt"])).unwrap(); + assert_eq!( + (entry.modified, entry.modified_nanos), + (1_700_000_000, 123_456_789) + ); + // A whole-second time is reported as zero nanoseconds, not as unknown. + file.set_modified(std::time::UNIX_EPOCH + Duration::new(1_700_000_001, 0)) + .unwrap(); + let entry = area.confined().stat(&path(&["a.txt"])).unwrap(); + assert_eq!((entry.modified, entry.modified_nanos), (1_700_000_001, 0)); +} + +#[test] +fn access_tells_the_read_only_metadata_apart_from_what_the_user_may_do() { + let area = Area::new(); + let files = area.confined(); + let file = area.root.join("a.txt"); + + let open = files.access(&path(&["a.txt"])).unwrap(); + assert_eq!( + ( + open.directory, + open.read_only, + open.read, + open.write, + open.create, + open.delete + ), + ( + false, + false, + Tri::Allowed, + Tri::Allowed, + Tri::Unknown, + Tri::Allowed + ) + ); + + // The mode says read-only, and the user really cannot write (a different thing from the mode, + // which root ignores). + fs::set_permissions(&file, fs::Permissions::from_mode(0o444)).unwrap(); + let locked = files.access(&path(&["a.txt"])).unwrap(); + assert!(locked.read_only); + assert_eq!(locked.read, Tri::Allowed); + if !running_as_root() { + assert_eq!(locked.write, Tri::Denied); + // Deleting a file depends on its folder, not on the file's own mode. + assert_eq!(locked.delete, Tri::Allowed); + } + + // The mode allows writing, yet the folder does not let the user delete or create. + fs::set_permissions(area.root.join("saves"), fs::Permissions::from_mode(0o555)).unwrap(); + let folder = files.access(&path(&["saves"])).unwrap(); + let inside = files.access(&path(&["saves", "slot1.sav"])).unwrap(); + fs::set_permissions(area.root.join("saves"), fs::Permissions::from_mode(0o755)).unwrap(); + assert!(folder.directory); + assert_eq!(folder.read, Tri::Allowed); + if !running_as_root() { + assert_eq!((folder.write, folder.create), (Tri::Denied, Tri::Denied)); + assert_eq!((inside.write, inside.delete), (Tri::Allowed, Tri::Denied)); + } +} + +#[test] +fn access_to_the_root_cannot_say_whether_it_can_be_deleted_and_a_link_is_not_followed() { + let area = Area::new(); + symlink(area.outside(), area.root.join("escape")).unwrap(); + let files = area.confined(); + let root = files.access(&[]).unwrap(); + assert!(root.directory); + assert_eq!( + root.delete, + Tri::Unknown, + "the root's own folder is outside the approval" + ); + assert_eq!( + files.access(&path(&["escape"])).unwrap_err(), + FileError::Denied + ); +} + +#[test] +fn inspecting_changes_nothing_not_even_a_modification_time() { + let area = Area::new(); + let files = area.confined(); + let file = area.root.join("a.txt"); + let stamp = std::time::UNIX_EPOCH + Duration::new(1_600_000_000, 5); + fs::File::options() + .write(true) + .open(&file) + .unwrap() + .set_modified(stamp) + .unwrap(); + let before = fs::metadata(&file).unwrap(); + let mode_before = fs::metadata(area.root.join("saves")) + .unwrap() + .permissions() + .mode(); + + let _ = tree(&files, &[], 1000); + files.stat(&path(&["a.txt"])).unwrap(); + files.access(&path(&["a.txt"])).unwrap(); + files.access(&path(&["saves"])).unwrap(); + + let after = fs::metadata(&file).unwrap(); + assert_eq!(after.modified().unwrap(), before.modified().unwrap()); + assert_eq!(after.len(), before.len()); + assert_eq!(fs::read(&file).unwrap(), b"hello world"); + assert_eq!( + fs::metadata(area.root.join("saves")) + .unwrap() + .permissions() + .mode(), + mode_before + ); + assert_eq!( + fs::read_dir(&area.root).unwrap().count(), + 2, + "no file was created" + ); +} + +// ---- Hashing (task 13.4) ---- + +fn sha(bytes: &[u8]) -> [u8; 32] { + use sha2::{Digest, Sha256}; + Sha256::digest(bytes).into() +} + +fn hash(files: &Confined, file: &[&str]) -> Result, FileError> { + files.hash_file( + &path(file), + &AtomicBool::new(false), + Instant::now() + Duration::from_secs(30), + ) +} + +#[test] +fn a_file_is_hashed_from_its_content_in_chunks_without_changing_it() { + let area = Area::new(); + let files = area.confined(); + let known = hash(&files, &["a.txt"]).unwrap().unwrap(); + assert_eq!(known.sha256, sha(b"hello world")); + assert_eq!(known.bytes, 11); + // An empty file has the digest of nothing. + fs::write(area.root.join("empty"), b"").unwrap(); + assert_eq!(hash(&files, &["empty"]).unwrap().unwrap().sha256, sha(b"")); + // A file larger than a chunk is hashed whole. + let big: Vec = (0..HASH_CHUNK_BYTES * 2 + 17) + .map(|n| (n % 251) as u8) + .collect(); + fs::write(area.root.join("big.bin"), &big).unwrap(); + let digest = hash(&files, &["big.bin"]).unwrap().unwrap(); + assert_eq!((digest.sha256, digest.bytes), (sha(&big), big.len() as u64)); + assert_eq!(fs::read(area.root.join("a.txt")).unwrap(), b"hello world"); +} + +#[test] +fn hashing_sees_a_change_that_keeps_the_size_and_the_modification_time() { + let area = Area::new(); + let files = area.confined(); + let file = area.root.join("a.txt"); + let stamp = std::time::UNIX_EPOCH + Duration::new(1_600_000_000, 0); + fs::File::options() + .write(true) + .open(&file) + .unwrap() + .set_modified(stamp) + .unwrap(); + let before = hash(&files, &["a.txt"]).unwrap().unwrap(); + fs::write(&file, b"HELLO WORLD").unwrap(); + fs::File::options() + .write(true) + .open(&file) + .unwrap() + .set_modified(stamp) + .unwrap(); + let after = hash(&files, &["a.txt"]).unwrap().unwrap(); + assert_eq!(files.stat(&path(&["a.txt"])).unwrap().size, 11); + assert_ne!(before.sha256, after.sha256); +} + +#[test] +fn hashing_stops_when_cancelled_or_late_and_refuses_what_is_not_a_plain_file() { + let area = Area::new(); + symlink(area.outside().join("secret.txt"), area.root.join("link")).unwrap(); + let files = area.confined(); + assert_eq!( + files + .hash_file( + &path(&["a.txt"]), + &AtomicBool::new(true), + Instant::now() + Duration::from_secs(30) + ) + .unwrap(), + None + ); + assert_eq!( + files + .hash_file(&path(&["a.txt"]), &AtomicBool::new(false), Instant::now()) + .unwrap(), + None + ); + assert_eq!(hash(&files, &["saves"]).unwrap_err(), FileError::NotAFile); + assert_eq!(hash(&files, &["link"]).unwrap_err(), FileError::Denied); + assert_eq!(hash(&files, &["missing"]).unwrap_err(), FileError::NotFound); + assert_eq!( + files + .hash_file( + &[], + &AtomicBool::new(false), + Instant::now() + Duration::from_secs(1) + ) + .unwrap_err(), + FileError::NotAFile + ); +} diff --git a/crates/platform/src/plugin_files/unix.rs b/crates/platform/src/plugin_files/unix.rs new file mode 100644 index 000000000..ac928b8a7 --- /dev/null +++ b/crates/platform/src/plugin_files/unix.rs @@ -0,0 +1,367 @@ +//! Linux: every step is `openat` from a directory handle with `O_NOFOLLOW`, so a path is never +//! resolved by the kernel behind our back and a component swapped for a link is refused when it +//! is opened, not merely when it was last looked at. + +// `st_dev`, `st_ino` and the like are `u64` here but not on every Unix target; the casts keep this +// portable. +#![allow(clippy::unnecessary_cast)] + +use std::fs::File; +use std::io; +use std::os::fd::OwnedFd; +use std::os::unix::fs::{FileExt, MetadataExt}; +use std::path::Path; + +use rustix::fs::{ + Access, AtFlags, Dir, FileType, Mode, OFlags, accessat, fstat, openat, statat, unlinkat, +}; +use rustix::io::Errno; + +use super::{ + AccessInfo, Confined, Entry, FileError, Identity, MAX_DIR_ENTRIES, Target, Tri, valid_component, +}; + +pub(super) fn identity_of(path: &Path) -> io::Result { + let metadata = std::fs::metadata(path)?; + Ok(Identity { + volume: metadata.dev(), + node: metadata.ino(), + }) +} + +fn errno(error: Errno) -> FileError { + match error { + Errno::NOENT => FileError::NotFound, + Errno::LOOP | Errno::XDEV => FileError::Denied, + Errno::NOTDIR => FileError::NotADirectory, + Errno::ISDIR | Errno::NXIO => FileError::NotAFile, + Errno::ACCESS | Errno::PERM | Errno::ROFS => FileError::Access, + other => FileError::from(io::Error::from(other)), + } +} + +fn id_of(fd: &OwnedFd) -> Result { + let stat = fstat(fd).map_err(errno)?; + Ok(Identity { + volume: stat.st_dev as u64, + node: stat.st_ino as u64, + }) +} + +const DIRECTORY: OFlags = OFlags::RDONLY + .union(OFlags::DIRECTORY) + .union(OFlags::NOFOLLOW) + .union(OFlags::CLOEXEC); + +/// The directory `components` below the root, opened one component at a time. +fn walk(c: &Confined, components: &[String]) -> Result { + let mut dir = + rustix::fs::open(&c.root.path, DIRECTORY, Mode::empty()).map_err(|error| match error { + // The folder is there but the user may not open it: not the same as gone or replaced. + Errno::ACCESS | Errno::PERM => FileError::Access, + _ => FileError::RootChanged, + })?; + if id_of(&dir)? != c.root.identity { + return Err(FileError::RootChanged); + } + for name in components { + if !valid_component(name) { + return Err(FileError::Denied); + } + let next = match openat(&dir, name.as_str(), DIRECTORY, Mode::empty()) { + Ok(next) => next, + // A link, or something that is not a directory: say which without following it. + Err(Errno::LOOP | Errno::NOTDIR) => { + return Err( + match statat(&dir, name.as_str(), AtFlags::SYMLINK_NOFOLLOW) { + Ok(stat) if FileType::from_raw_mode(stat.st_mode) == FileType::Symlink => { + FileError::Denied + } + Ok(_) => FileError::NotADirectory, + Err(error) => errno(error), + }, + ); + } + Err(error) => return Err(errno(error)), + }; + let id = id_of(&next)?; + if id.volume != c.root.identity.volume || c.reserved.holds_id(id) { + return Err(FileError::Denied); + } + dir = next; + } + Ok(dir) +} + +fn split(path: &[String]) -> (&[String], &str) { + let (name, parent) = path.split_last().expect("callers pass a non-empty path"); + (parent, name.as_str()) +} + +/// Opens an existing regular file below `dir` without following a link. +fn open_file(c: &Confined, dir: &OwnedFd, name: &str, access: OFlags) -> Result { + let fd = openat( + dir, + name, + access | OFlags::NOFOLLOW | OFlags::CLOEXEC | OFlags::NONBLOCK, + Mode::empty(), + ) + .map_err(errno)?; + checked(c, fd) +} + +fn checked(c: &Confined, fd: OwnedFd) -> Result { + let stat = fstat(&fd).map_err(errno)?; + if FileType::from_raw_mode(stat.st_mode) != FileType::RegularFile { + return Err(FileError::NotAFile); + } + if stat.st_dev as u64 != c.root.identity.volume { + return Err(FileError::Denied); + } + Ok(File::from(fd)) +} + +pub(super) fn list(c: &Confined, directory: &[String]) -> Result, FileError> { + let dir = walk(c, directory)?; + let reader = Dir::read_from(&dir).map_err(errno)?; + let mut entries = Vec::new(); + let mut seen = 0; + for item in reader { + let item = item.map_err(errno)?; + let raw = item.file_name().to_bytes(); + if raw == b"." || raw == b".." { + continue; + } + seen += 1; + if seen > MAX_DIR_ENTRIES { + return Err(FileError::TooLarge); + } + let Ok(name) = std::str::from_utf8(raw) else { + continue; + }; + if !valid_component(name) { + continue; + } + let Ok(stat) = statat(&dir, name, AtFlags::SYMLINK_NOFOLLOW) else { + continue; + }; + let id = Identity { + volume: stat.st_dev as u64, + node: stat.st_ino as u64, + }; + // Links, devices, pipes and sockets do not exist for a plugin; a mount point or a + // reserved host folder is not part of the approved area. + let directory = match FileType::from_raw_mode(stat.st_mode) { + FileType::Directory => true, + FileType::RegularFile => false, + _ => continue, + }; + if id.volume != c.root.identity.volume || (directory && c.reserved.holds_id(id)) { + continue; + } + entries.push(entry_of(name, directory, &stat)); + } + Ok(entries) +} + +fn entry_of(name: &str, directory: bool, stat: &rustix::fs::Stat) -> Entry { + Entry { + name: name.to_owned(), + directory, + size: if directory { 0 } else { stat.st_size as u64 }, + modified: stat.st_mtime as i64, + modified_nanos: stat.st_mtime_nsec as u32, + read_only: stat.st_mode & 0o222 == 0, + } +} + +/// The entry at `path`, or the root itself (named "") for an empty path. +pub(super) fn stat(c: &Confined, path: &[String]) -> Result { + if path.is_empty() { + let root = walk(c, &[])?; + let stat = fstat(&root).map_err(errno)?; + return Ok(entry_of("", true, &stat)); + } + let (parent, name) = split(path); + let dir = walk(c, parent)?; + let stat = statat(&dir, name, AtFlags::SYMLINK_NOFOLLOW).map_err(errno)?; + let directory = match FileType::from_raw_mode(stat.st_mode) { + FileType::Directory => true, + FileType::RegularFile => false, + FileType::Symlink => return Err(FileError::Denied), + _ => return Err(FileError::NotAFile), + }; + let id = Identity { + volume: stat.st_dev as u64, + node: stat.st_ino as u64, + }; + if id.volume != c.root.identity.volume || (directory && c.reserved.holds_id(id)) { + return Err(FileError::Denied); + } + Ok(entry_of(name, directory, &stat)) +} + +/// Asks the kernel what the effective user may do (`faccessat` with `AT_EACCESS`), which weighs +/// the mode bits, the owner and group, ACLs and a read-only mount without opening or changing +/// anything. +fn can(dir: &OwnedFd, name: &str, wanted: Access) -> Tri { + match accessat(dir, name, wanted, AtFlags::EACCESS) { + Ok(()) => Tri::Allowed, + Err(Errno::ACCESS | Errno::PERM | Errno::ROFS) => Tri::Denied, + Err(_) => Tri::Unknown, + } +} + +pub(super) fn access(c: &Confined, path: &[String]) -> Result { + let entry = stat(c, path)?; + let directory = entry.directory; + // The entry's own directory entry is checked from its parent, the root from itself. + let (holder, name, parent_path): (OwnedFd, String, Option<&[String]>) = if path.is_empty() { + (walk(c, &[])?, ".".to_owned(), None) + } else { + let (parent, name) = split(path); + (walk(c, parent)?, name.to_owned(), Some(parent)) + }; + let (read, write, create) = if directory { + let entered = can(&holder, &name, Access::EXEC_OK); + let all = |wanted: Access| match (entered, can(&holder, &name, wanted)) { + (Tri::Allowed, Tri::Allowed) => Tri::Allowed, + (Tri::Denied, _) | (_, Tri::Denied) => Tri::Denied, + _ => Tri::Unknown, + }; + let write = all(Access::WRITE_OK); + (all(Access::READ_OK), write, write) + } else { + ( + can(&holder, &name, Access::READ_OK), + can(&holder, &name, Access::WRITE_OK), + Tri::Unknown, + ) + }; + // Removing an entry needs write and search permission on its folder. The root's folder is + // outside the approval, and a sticky folder also looks at who owns what: neither is guessed. + let delete = match parent_path { + None => Tri::Unknown, + Some(parent) => { + let folder = walk(c, parent)?; + let sticky = fstat(&folder).map_err(errno)?.st_mode & 0o1000 != 0; + if sticky { + Tri::Unknown + } else { + match ( + can(&folder, ".", Access::EXEC_OK), + can(&folder, ".", Access::WRITE_OK), + ) { + (Tri::Allowed, Tri::Allowed) => Tri::Allowed, + (Tri::Denied, _) | (_, Tri::Denied) => Tri::Denied, + _ => Tri::Unknown, + } + } + } + }; + Ok(AccessInfo { + directory, + read_only: entry.read_only, + read, + write, + create, + delete, + }) +} + +pub(super) fn read( + c: &Confined, + file: &[String], + offset: u64, + max: usize, +) -> Result<(Vec, bool), FileError> { + let (parent, name) = split(file); + let dir = walk(c, parent)?; + let file = open_file(c, &dir, name, OFlags::RDONLY)?; + let len = file.metadata().map_err(FileError::from)?.len(); + let want = max.min(len.saturating_sub(offset) as usize); + let mut buffer = vec![0; want]; + let mut done = 0; + while done < want { + let read = file + .read_at(&mut buffer[done..], offset + done as u64) + .map_err(FileError::from)?; + if read == 0 { + break; + } + done += read; + } + buffer.truncate(done); + let eof = offset.saturating_add(done as u64) >= len; + Ok((buffer, eof)) +} + +pub(super) fn write( + c: &Confined, + target: Target<'_>, + offset: u64, + contents: &[u8], + truncate: bool, +) -> Result { + let file = match target { + Target::Existing(path) => { + let (parent, name) = split(path); + let dir = walk(c, parent)?; + open_file(c, &dir, name, OFlags::WRONLY)? + } + Target::Create { directory, name } => { + let dir = walk(c, directory)?; + match open_file(c, &dir, name, OFlags::WRONLY) { + Err(FileError::NotFound) => { + // A new file starts empty, so a write may only begin at its start; refuse + // before creating anything. + if offset != 0 { + return Err(FileError::OutOfRange); + } + let fd = openat( + &dir, + name, + OFlags::WRONLY + | OFlags::CREATE + | OFlags::EXCL + | OFlags::NOFOLLOW + | OFlags::CLOEXEC + | OFlags::NONBLOCK, + Mode::from_bits_truncate(0o666), + ) + .map_err(errno)?; + checked(c, fd)? + } + other => other?, + } + } + }; + let len = file.metadata().map_err(FileError::from)?.len(); + if offset > len { + return Err(FileError::OutOfRange); + } + file.write_all_at(contents, offset) + .map_err(FileError::from)?; + let end = offset + contents.len() as u64; + if truncate { + file.set_len(end).map_err(FileError::from)?; + Ok(end) + } else { + Ok(len.max(end)) + } +} + +pub(super) fn delete(c: &Confined, file: &[String]) -> Result<(), FileError> { + let (parent, name) = split(file); + let dir = walk(c, parent)?; + let stat = statat(&dir, name, AtFlags::SYMLINK_NOFOLLOW).map_err(errno)?; + match FileType::from_raw_mode(stat.st_mode) { + FileType::RegularFile => {} + FileType::Symlink => return Err(FileError::Denied), + _ => return Err(FileError::NotAFile), + } + if stat.st_dev as u64 != c.root.identity.volume { + return Err(FileError::Denied); + } + unlinkat(&dir, name, AtFlags::empty()).map_err(errno) +} diff --git a/crates/platform/src/plugin_files/windows.rs b/crates/platform/src/plugin_files/windows.rs new file mode 100644 index 000000000..1d326000c --- /dev/null +++ b/crates/platform/src/plugin_files/windows.rs @@ -0,0 +1,417 @@ +//! Windows: there is no `openat` in the standard library, so each component is checked as a +//! reparse point (symbolic link, junction, mount point) and the handle that was actually opened +//! is then asked for its final path, which must be exactly the approved root plus the requested +//! components. A component swapped for a junction between the check and the open therefore ends +//! the operation before any byte is read, written or deleted. + +use std::fs::{self, File, OpenOptions}; +use std::io; +use std::os::windows::fs::{FileExt, MetadataExt, OpenOptionsExt}; +use std::os::windows::io::AsRawHandle; +use std::path::{Path, PathBuf}; + +use windows_sys::Win32::Foundation::HANDLE; +use windows_sys::Win32::Storage::FileSystem::{ + BY_HANDLE_FILE_INFORMATION, DELETE, FILE_ADD_FILE, FILE_ATTRIBUTE_READONLY, + FILE_ATTRIBUTE_REPARSE_POINT, FILE_DELETE_CHILD, FILE_DISPOSITION_INFO, + FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OPEN_REPARSE_POINT, FILE_LIST_DIRECTORY, + FILE_NAME_NORMALIZED, FILE_READ_ATTRIBUTES, FILE_READ_DATA, FILE_SHARE_DELETE, FILE_SHARE_READ, + FILE_SHARE_WRITE, FILE_WRITE_DATA, FileDispositionInfo, GetFileInformationByHandle, + GetFinalPathNameByHandleW, SetFileInformationByHandle, VOLUME_NAME_DOS, +}; + +use super::{ + AccessInfo, Confined, Entry, FileError, Identity, MAX_DIR_ENTRIES, Target, Tri, valid_component, +}; + +const SHARE_ALL: u32 = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE; +/// Seconds between 1601-01-01 (FILETIME) and the Unix epoch. +const FILETIME_UNIX_OFFSET: u64 = 11_644_473_600; + +fn handle_of(file: &File) -> HANDLE { + file.as_raw_handle() as HANDLE +} + +fn information(file: &File) -> io::Result { + // SAFETY: `info` is plain data the call fills in, and the handle is open for the call. + unsafe { + let mut info = std::mem::zeroed::(); + if GetFileInformationByHandle(handle_of(file), &mut info) == 0 { + return Err(io::Error::last_os_error()); + } + Ok(info) + } +} + +/// Opens `path` itself (a directory or a file), never following a link at the end. +fn open_for_identity(path: &Path) -> io::Result { + OpenOptions::new() + .access_mode(FILE_READ_ATTRIBUTES) + .share_mode(SHARE_ALL) + .custom_flags(FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT) + .open(path) +} + +pub(super) fn identity_of(path: &Path) -> io::Result { + let info = information(&open_for_identity(path)?)?; + Ok(Identity { + volume: u64::from(info.dwVolumeSerialNumber), + node: (u64::from(info.nFileIndexHigh) << 32) | u64::from(info.nFileIndexLow), + }) +} + +/// The path the system reports for an open handle, with every link resolved. +fn final_path(file: &File) -> io::Result { + let mut buffer = vec![0u16; 1024]; + loop { + // SAFETY: the buffer is valid for `buffer.len()` UTF-16 units for the call. + let length = unsafe { + GetFinalPathNameByHandleW( + handle_of(file), + buffer.as_mut_ptr(), + buffer.len() as u32, + FILE_NAME_NORMALIZED | VOLUME_NAME_DOS, + ) + } as usize; + if length == 0 { + return Err(io::Error::last_os_error()); + } + if length < buffer.len() { + buffer.truncate(length); + return Ok(PathBuf::from(String::from_utf16_lossy(&buffer))); + } + buffer.resize(length + 1, 0); + } +} + +fn same_path(a: &Path, b: &Path) -> bool { + match (a.to_str(), b.to_str()) { + (Some(a), Some(b)) => a.to_lowercase() == b.to_lowercase(), + _ => false, + } +} + +fn is_reparse(metadata: &fs::Metadata) -> bool { + metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0 +} + +/// `root` plus `components`, checking that no component is a link or other reparse point and +/// that the result is not a reserved host folder. +fn walk(c: &Confined, components: &[String]) -> Result { + let mut path = c.root.path.clone(); + for name in components { + if !valid_component(name) { + return Err(FileError::Denied); + } + path.push(name); + let metadata = fs::symlink_metadata(&path).map_err(FileError::from)?; + if is_reparse(&metadata) { + return Err(FileError::Denied); + } + } + if c.reserved.covers(&path) { + return Err(FileError::Denied); + } + Ok(path) +} + +/// The opened handle must be exactly where the walk said it was, and not reserved. +fn verify(c: &Confined, file: &File, expected: &Path) -> Result<(), FileError> { + let actual = final_path(file).map_err(FileError::from)?; + // `canonicalize` and the handle both give verbatim (`\\?\`) paths, so they compare directly. + let expected = if actual + .to_str() + .is_some_and(|text| text.starts_with(r"\\?\")) + && !expected + .to_str() + .is_some_and(|text| text.starts_with(r"\\?\")) + { + PathBuf::from(format!(r"\\?\{}", expected.display())) + } else { + expected.to_path_buf() + }; + if !same_path(&actual, &expected) || c.reserved.covers(&actual) { + return Err(FileError::Denied); + } + Ok(()) +} + +fn open_directory(c: &Confined, components: &[String]) -> Result { + let path = walk(c, components)?; + let handle = open_for_identity(&path).map_err(FileError::from)?; + let metadata = handle.metadata().map_err(FileError::from)?; + if !metadata.is_dir() { + return Err(FileError::NotADirectory); + } + verify(c, &handle, &path)?; + Ok(path) +} + +fn unix_seconds(metadata: &fs::Metadata) -> i64 { + (metadata.last_write_time() / 10_000_000).saturating_sub(FILETIME_UNIX_OFFSET) as i64 +} + +/// The sub-second part of the write time: FILETIME counts 100-nanosecond ticks. +fn unix_nanos(metadata: &fs::Metadata) -> u32 { + ((metadata.last_write_time() % 10_000_000) * 100) as u32 +} + +fn entry_of(name: String, directory: bool, metadata: &fs::Metadata) -> Entry { + Entry { + name, + directory, + size: if directory { 0 } else { metadata.file_size() }, + modified: unix_seconds(metadata), + modified_nanos: unix_nanos(metadata), + read_only: metadata.file_attributes() & FILE_ATTRIBUTE_READONLY != 0, + } +} + +pub(super) fn list(c: &Confined, directory: &[String]) -> Result, FileError> { + let path = open_directory(c, directory)?; + let mut entries = Vec::new(); + let mut seen = 0; + for item in fs::read_dir(&path).map_err(FileError::from)? { + let item = item.map_err(FileError::from)?; + seen += 1; + if seen > MAX_DIR_ENTRIES { + return Err(FileError::TooLarge); + } + let Ok(name) = item.file_name().into_string() else { + continue; + }; + if !valid_component(&name) { + continue; + } + // Not following links: `DirEntry::metadata` describes the entry itself. + let Ok(metadata) = item.metadata() else { + continue; + }; + if is_reparse(&metadata) || c.reserved.covers(&path.join(&name)) { + continue; + } + let directory = metadata.is_dir(); + if !directory && !metadata.is_file() { + continue; + } + entries.push(entry_of(name, directory, &metadata)); + } + Ok(entries) +} + +/// The entry at `path`, or the root itself (named "") for an empty path. +pub(super) fn stat(c: &Confined, path: &[String]) -> Result { + let target = if path.is_empty() { + open_directory(c, &[])? + } else { + walk(c, path)? + }; + let metadata = fs::symlink_metadata(&target).map_err(FileError::from)?; + if is_reparse(&metadata) { + return Err(FileError::Denied); + } + let directory = metadata.is_dir(); + if !directory && !metadata.is_file() { + return Err(FileError::NotAFile); + } + let name = path.last().cloned().unwrap_or_default(); + Ok(entry_of(name, directory, &metadata)) +} + +/// Whether the current user can open `path` itself with `mask`, which is how the system weighs +/// the ACLs against the user's token. Nothing is written: the handle is closed at once and a +/// share mode of everything keeps it from getting in anyone's way. A sharing violation or any +/// other error is not an answer. +fn probe(path: &Path, mask: u32) -> Tri { + const ACCESS_DENIED: i32 = 5; + match OpenOptions::new() + .access_mode(mask) + .share_mode(SHARE_ALL) + .custom_flags(FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT) + .open(path) + { + Ok(_) => Tri::Allowed, + Err(error) if error.raw_os_error() == Some(ACCESS_DENIED) => Tri::Denied, + Err(_) => Tri::Unknown, + } +} + +pub(super) fn access(c: &Confined, path: &[String]) -> Result { + let entry = stat(c, path)?; + let directory = entry.directory; + let target = if path.is_empty() { + c.root.path.clone() + } else { + walk(c, path)? + }; + let (read, write, create) = if directory { + let write = probe(&target, FILE_ADD_FILE); + (probe(&target, FILE_LIST_DIRECTORY), write, write) + } else { + ( + probe(&target, FILE_READ_DATA), + probe(&target, FILE_WRITE_DATA), + Tri::Unknown, + ) + }; + // The right to delete comes from the entry itself or from its folder. + let delete = match probe(&target, DELETE) { + Tri::Allowed => Tri::Allowed, + own => match target + .parent() + .filter(|_| !path.is_empty()) + .map(|parent| probe(parent, FILE_DELETE_CHILD)) + { + Some(Tri::Allowed) => Tri::Allowed, + Some(Tri::Denied) if own == Tri::Denied => Tri::Denied, + _ => Tri::Unknown, + }, + }; + Ok(AccessInfo { + directory, + read_only: entry.read_only, + read, + write, + create, + delete, + }) +} + +fn open_regular(c: &Confined, path: &Path, options: &mut OpenOptions) -> Result { + let file = options + .share_mode(SHARE_ALL) + .custom_flags(FILE_FLAG_OPEN_REPARSE_POINT) + .open(path) + .map_err(FileError::from)?; + let metadata = file.metadata().map_err(FileError::from)?; + if is_reparse(&metadata) { + return Err(FileError::Denied); + } + if !metadata.is_file() { + return Err(FileError::NotAFile); + } + verify(c, &file, path)?; + Ok(file) +} + +pub(super) fn read( + c: &Confined, + file: &[String], + offset: u64, + max: usize, +) -> Result<(Vec, bool), FileError> { + let path = walk(c, file)?; + let file = open_regular(c, &path, OpenOptions::new().read(true))?; + let len = file.metadata().map_err(FileError::from)?.len(); + let want = max.min(len.saturating_sub(offset) as usize); + let mut buffer = vec![0; want]; + let mut done = 0; + while done < want { + let read = file + .seek_read(&mut buffer[done..], offset + done as u64) + .map_err(FileError::from)?; + if read == 0 { + break; + } + done += read; + } + buffer.truncate(done); + let eof = offset.saturating_add(done as u64) >= len; + Ok((buffer, eof)) +} + +pub(super) fn write( + c: &Confined, + target: Target<'_>, + offset: u64, + contents: &[u8], + truncate: bool, +) -> Result { + let file = match target { + Target::Existing(path) => { + let path = walk(c, path)?; + open_regular(c, &path, OpenOptions::new().write(true))? + } + Target::Create { directory, name } => { + let parent = open_directory(c, directory)?; + let path = parent.join(name); + match open_regular(c, &path, OpenOptions::new().write(true)) { + Err(FileError::NotFound) => { + // A new file starts empty, so a write may only begin at its start; refuse + // before creating anything. + if offset != 0 { + return Err(FileError::OutOfRange); + } + let created = OpenOptions::new() + .write(true) + .create_new(true) + .share_mode(SHARE_ALL) + .custom_flags(FILE_FLAG_OPEN_REPARSE_POINT) + .open(&path) + .map_err(FileError::from)?; + if let Err(error) = verify(c, &created, &path) { + drop(created); + let _ = fs::remove_file(&path); + return Err(error); + } + created + } + other => other?, + } + } + }; + let len = file.metadata().map_err(FileError::from)?.len(); + if offset > len { + return Err(FileError::OutOfRange); + } + let mut written = 0; + while written < contents.len() { + let wrote = file + .seek_write(&contents[written..], offset + written as u64) + .map_err(FileError::from)?; + if wrote == 0 { + return Err(FileError::Io); + } + written += wrote; + } + let end = offset + contents.len() as u64; + if truncate { + file.set_len(end).map_err(FileError::from)?; + Ok(end) + } else { + Ok(len.max(end)) + } +} + +pub(super) fn delete(c: &Confined, file: &[String]) -> Result<(), FileError> { + let path = walk(c, file)?; + let handle = OpenOptions::new() + .access_mode(DELETE | FILE_READ_ATTRIBUTES) + .share_mode(SHARE_ALL) + .custom_flags(FILE_FLAG_OPEN_REPARSE_POINT) + .open(&path) + .map_err(FileError::from)?; + let metadata = handle.metadata().map_err(FileError::from)?; + if is_reparse(&metadata) { + return Err(FileError::Denied); + } + if !metadata.is_file() { + return Err(FileError::NotAFile); + } + verify(c, &handle, &path)?; + // Mark exactly the file that was verified; no path is resolved again. + let info = FILE_DISPOSITION_INFO { DeleteFile: true }; + // SAFETY: `info` outlives the call and its size is passed; the handle is open with DELETE. + let done = unsafe { + SetFileInformationByHandle( + handle_of(&handle), + FileDispositionInfo, + std::ptr::addr_of!(info).cast(), + std::mem::size_of::() as u32, + ) + }; + if done == 0 { + return Err(io::Error::last_os_error().into()); + } + Ok(()) +} diff --git a/crates/platform/src/plugin_locations.rs b/crates/platform/src/plugin_locations.rs new file mode 100644 index 000000000..0615f2608 --- /dev/null +++ b/crates/platform/src/plugin_locations.rs @@ -0,0 +1,250 @@ +//! Folder suggestions declared by third-party plugins. +//! +//! A plugin may say where the folder for a game's saves or prefix usually is +//! (`FilesRequestAccess.declared_locations`). The text is untrusted: it is only ever a +//! *suggestion* shown to the user, who confirms or chooses another folder, so everything here is +//! pure parsing and expansion. Nothing is read, listed or opened; the caller checks existence. +//! +//! A location is either an absolute path or starts with one of a closed set of placeholders that +//! the host expands from the system's own folders: +//! +//! | Placeholder | Where | Meaning | +//! | --- | --- | --- | +//! | `{home}` | both | the user's home folder | +//! | `{documents}` | both | the user's Documents folder (Linux: only if XDG defines one) | +//! | `{appdata}` | Windows | the roaming application data folder | +//! | `{localappdata}` | Windows | the local application data folder | +//! | `{xdg_data}` | Linux | `XDG_DATA_HOME` | +//! | `{xdg_config}` | Linux | `XDG_CONFIG_HOME` | +//! +//! A suggestion that cannot apply on this system (a placeholder of the other system, a drive +//! path on Linux, a system folder that does not exist) expands to nothing and is dropped without +//! an error, so one list serves every platform. A location that is not well formed (an unknown +//! placeholder, a relative path, `..`, controls, too long) is an error the plugin is told about. + +use std::path::PathBuf; + +/// The longest location text, in bytes. +pub const MAX_LOCATION_BYTES: usize = 1024; +/// The most suggestions a plugin may declare for one kind. +pub const MAX_PER_KIND: usize = 8; + +/// The system a location is expanded for. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Os { + Linux, + Windows, +} + +impl Os { + pub const fn current() -> Self { + if cfg!(windows) { + Self::Windows + } else { + Self::Linux + } + } +} + +/// Why a location is refused. The messages are safe to show the plugin. +#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)] +pub enum LocationError { + #[error("a location is empty")] + Empty, + #[error("a location is longer than {MAX_LOCATION_BYTES} bytes")] + TooLong, + #[error("a location contains a control character")] + Control, + #[error("a location uses a placeholder that does not exist")] + UnknownPlaceholder, + #[error("a location must be an absolute path or start with a placeholder")] + Relative, + #[error( + "a location may not contain `..`, a lone `{{`/`}}` or other than plain names after a placeholder" + )] + Malformed, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Placeholder { + Home, + Documents, + AppData, + LocalAppData, + XdgData, + XdgConfig, +} + +impl Placeholder { + fn parse(name: &str) -> Option { + Some(match name { + "home" => Self::Home, + "documents" => Self::Documents, + "appdata" => Self::AppData, + "localappdata" => Self::LocalAppData, + "xdg_data" => Self::XdgData, + "xdg_config" => Self::XdgConfig, + _ => return None, + }) + } + + fn exists_on(self, os: Os) -> bool { + match self { + Self::Home | Self::Documents => true, + Self::AppData | Self::LocalAppData => os == Os::Windows, + Self::XdgData | Self::XdgConfig => os == Os::Linux, + } + } +} + +/// The system folders placeholders expand to. `None` means the system has no such folder. +pub trait Folders { + fn home(&self) -> Option; + fn documents(&self) -> Option; + /// Windows: the roaming application data folder. Linux: `XDG_DATA_HOME`. + fn data(&self) -> Option; + /// Windows: the local application data folder. + fn local_data(&self) -> Option; + /// Linux: `XDG_CONFIG_HOME`. + fn config(&self) -> Option; +} + +/// The folders of the running system. +pub struct SystemFolders; + +impl Folders for SystemFolders { + fn home(&self) -> Option { + dirs::home_dir() + } + fn documents(&self) -> Option { + dirs::document_dir() + } + fn data(&self) -> Option { + dirs::data_dir() + } + fn local_data(&self) -> Option { + dirs::data_local_dir() + } + fn config(&self) -> Option { + dirs::config_dir() + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +enum Root { + Placeholder(Placeholder), + /// An absolute path written the way Unix writes it. + Unix, + /// An absolute path written the way Windows writes it (a drive or a UNC share). + Windows(String), +} + +/// A location that is well formed. Expanding it is a separate, pure step. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Location { + root: Root, + /// Plain names below the root, separators collapsed, no `.` and no `..`. + parts: Vec, +} + +fn plain_parts(rest: &str) -> Result, LocationError> { + let mut parts = Vec::new(); + for part in rest.split(['/', '\\']) { + match part { + "" | "." => {} + ".." => return Err(LocationError::Malformed), + name if name.contains(['{', '}']) => return Err(LocationError::Malformed), + name => parts.push(name.to_owned()), + } + } + Ok(parts) +} + +/// Checks a location's text. Both `/` and `\` separate names. +pub fn parse(location: &str) -> Result { + if location.is_empty() { + return Err(LocationError::Empty); + } + if location.len() > MAX_LOCATION_BYTES { + return Err(LocationError::TooLong); + } + if location.chars().any(char::is_control) { + return Err(LocationError::Control); + } + if let Some(after) = location.strip_prefix('{') { + let (name, rest) = after.split_once('}').ok_or(LocationError::Malformed)?; + let placeholder = Placeholder::parse(name).ok_or(LocationError::UnknownPlaceholder)?; + if !(rest.is_empty() || rest.starts_with(['/', '\\'])) { + return Err(LocationError::Malformed); + } + return Ok(Location { + root: Root::Placeholder(placeholder), + parts: plain_parts(rest)?, + }); + } + let bytes = location.as_bytes(); + let drive = bytes.len() >= 3 + && bytes[0].is_ascii_alphabetic() + && bytes[1] == b':' + && matches!(bytes[2], b'/' | b'\\'); + let (root, rest) = if drive { + ( + Root::Windows(location[..2].to_ascii_uppercase()), + &location[3..], + ) + } else if let Some(share) = location.strip_prefix("\\\\") { + // `\\server\share\...`: the server and share are the first two names. + (Root::Windows("\\\\".to_owned()), share) + } else if let Some(rest) = location.strip_prefix('/') { + (Root::Unix, rest) + } else { + return Err(LocationError::Relative); + }; + if location.contains('{') || location.contains('}') { + return Err(LocationError::Malformed); + } + Ok(Location { + root, + parts: plain_parts(rest)?, + }) +} + +impl Location { + /// The absolute path this location means on `os`, or `None` when it does not apply there: a + /// placeholder or a path of the other system, or a system folder that does not exist. The + /// result is valid Unicode and is not checked against the disk. + pub fn expand(&self, os: Os, folders: &dyn Folders) -> Option { + let mut path = match &self.root { + Root::Placeholder(placeholder) => { + if !placeholder.exists_on(os) { + return None; + } + match placeholder { + Placeholder::Home => folders.home(), + Placeholder::Documents => folders.documents(), + Placeholder::AppData | Placeholder::XdgData => folders.data(), + Placeholder::LocalAppData => folders.local_data(), + Placeholder::XdgConfig => folders.config(), + }? + } + Root::Unix if os == Os::Linux => PathBuf::from("/"), + Root::Windows(root) if os == Os::Windows => { + if root == "\\\\" { + // The first two names are the server and the share. + let mut names = self.parts.iter(); + let (server, share) = (names.next()?, names.next()?); + let mut path = PathBuf::from(format!("\\\\{server}\\{share}\\")); + path.extend(names); + return path.to_str().is_some().then_some(path); + } + PathBuf::from(format!("{root}\\")) + } + _ => return None, + }; + path.extend(&self.parts); + path.to_str().is_some().then_some(path) + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/platform/src/plugin_locations/tests.rs b/crates/platform/src/plugin_locations/tests.rs new file mode 100644 index 000000000..9e5ac31d6 --- /dev/null +++ b/crates/platform/src/plugin_locations/tests.rs @@ -0,0 +1,140 @@ +use super::*; + +struct Fake { + documents: bool, +} + +impl Folders for Fake { + fn home(&self) -> Option { + Some("/home/ana".into()) + } + fn documents(&self) -> Option { + self.documents.then(|| "/home/ana/Documents".into()) + } + fn data(&self) -> Option { + Some("/home/ana/.local/share".into()) + } + fn local_data(&self) -> Option { + Some("/home/ana/AppData/Local".into()) + } + fn config(&self) -> Option { + Some("/home/ana/.config".into()) + } +} + +fn expand(location: &str, os: Os) -> Option { + parse(location) + .unwrap() + .expand(os, &Fake { documents: true }) +} + +#[test] +fn placeholders_expand_to_the_systems_folders_below_plain_names() { + assert_eq!( + expand("{home}/Games/Saves", Os::Linux), + Some("/home/ana/Games/Saves".into()) + ); + assert_eq!( + expand("{documents}", Os::Linux), + Some("/home/ana/Documents".into()) + ); + assert_eq!( + expand("{xdg_data}/portal", Os::Linux), + Some("/home/ana/.local/share/portal".into()) + ); + assert_eq!( + expand("{xdg_config}/portal/", Os::Linux), + Some("/home/ana/.config/portal".into()) + ); + assert_eq!( + expand("{appdata}/Portal", Os::Windows), + Some("/home/ana/.local/share/Portal".into()) + ); + assert_eq!( + expand("{localappdata}/Portal", Os::Windows), + Some("/home/ana/AppData/Local/Portal".into()) + ); + // Both separators separate names, and repeated ones and `.` collapse. + assert_eq!( + expand("{home}\\My Games\\.\\\\Portal", Os::Linux), + Some("/home/ana/My Games/Portal".into()) + ); +} + +#[test] +fn what_cannot_apply_on_this_system_expands_to_nothing_not_to_an_error() { + // The placeholders of the other system. + assert_eq!(expand("{appdata}/X", Os::Linux), None); + assert_eq!(expand("{localappdata}/X", Os::Linux), None); + assert_eq!(expand("{xdg_data}/X", Os::Windows), None); + assert_eq!(expand("{xdg_config}/X", Os::Windows), None); + // A system folder that does not exist. + assert_eq!( + parse("{documents}/X") + .unwrap() + .expand(Os::Linux, &Fake { documents: false }), + None + ); + // Absolute paths of the other system. + assert_eq!( + expand("C:\\Program Files (x86)\\Steam\\steamapps", Os::Linux), + None + ); + assert_eq!(expand("\\\\server\\share\\saves", Os::Linux), None); + assert_eq!(expand("/opt/games", Os::Windows), None); +} + +#[test] +fn absolute_paths_of_this_system_are_kept_as_written() { + assert_eq!( + expand("/opt/games/portal", Os::Linux), + Some("/opt/games/portal".into()) + ); + assert_eq!(expand("/", Os::Linux), Some("/".into())); + // Windows paths are only meaningful on Windows; the drive letter is normalised. + #[cfg(windows)] + { + assert_eq!( + expand("c:/Program Files (x86)/Steam", Os::Windows), + Some("C:\\Program Files (x86)\\Steam".into()) + ); + assert_eq!( + expand("\\\\nas\\games\\saves", Os::Windows), + Some("\\\\nas\\games\\saves".into()) + ); + } +} + +#[test] +fn a_location_that_is_not_well_formed_is_an_error_the_plugin_is_told_about() { + for (text, error) in [ + ("", LocationError::Empty), + ("{nope}/x", LocationError::UnknownPlaceholder), + ("{Home}/x", LocationError::UnknownPlaceholder), + ("{home", LocationError::Malformed), + ("{home}x", LocationError::Malformed), + ("{home}/../etc", LocationError::Malformed), + ("{home}/a/{documents}", LocationError::Malformed), + ("/opt/../etc", LocationError::Malformed), + ("/opt/{home}", LocationError::Malformed), + ("C:\\games\\..\\x", LocationError::Malformed), + ("saves/slot1", LocationError::Relative), + ("./saves", LocationError::Relative), + ("~/saves", LocationError::Relative), + ("C:saves", LocationError::Relative), + ("\\saves", LocationError::Relative), + ("{home}/a\u{7}b", LocationError::Control), + ("{home}/a\nb", LocationError::Control), + ] { + assert_eq!(parse(text), Err(error), "{text:?}"); + } + let long = format!("/{}", "a".repeat(MAX_LOCATION_BYTES)); + assert_eq!(parse(&long), Err(LocationError::TooLong)); + // Exactly at the limit is fine. + assert!(parse(&format!("/{}", "a".repeat(MAX_LOCATION_BYTES - 1))).is_ok()); +} + +#[test] +fn the_system_folders_are_the_real_ones() { + assert_eq!(SystemFolders.home(), dirs::home_dir()); +} diff --git a/crates/platform/src/plugin_network.rs b/crates/platform/src/plugin_network.rs new file mode 100644 index 000000000..f46450883 --- /dev/null +++ b/crates/platform/src/plugin_network.rs @@ -0,0 +1,696 @@ +//! HTTPS fetches made on behalf of third-party plugins. +//! +//! A plugin may ask the host to fetch a URL from an origin the user approved. The host is the one +//! on the network, so everything that keeps that safe lives here, in one place: +//! +//! * the URL must be `https`, name a host, carry no user name or password, and its exact origin +//! (scheme, host and port) must be approved *now*; the caller's `allow` check runs for the +//! first URL and again for every redirect target, before anything is sent; +//! * the host name is resolved by the client's own resolver, which refuses the connection when +//! **any** address is loopback, private, link-local, unique-local, shared (CGNAT), +//! multicast, unspecified, documentation, reserved or an IPv6 form that embeds such an IPv4 +//! address. The client connects to exactly the addresses that passed, so a name cannot pass +//! the check and then resolve elsewhere; IP-literal hosts get the same test before connecting; +//! * redirects are followed by hand, never by the HTTP library, within [`MAX_REDIRECTS`] hops, +//! and credentials do not cross origins; +//! * nothing is reused between fetches: no connection pool, no cookies, no proxy (a proxy would +//! resolve names itself and bypass the address check), no default or GameNode credentials; +//! * the response is bounded by the caller's byte budget (never above [`MAX_RESPONSE_BYTES`]) and +//! the whole fetch, redirects and body included, by one deadline (never above +//! [`MAX_TIMEOUT`]). +//! +//! None of this confines a plugin that runs as the user: it is what the *API* does for it. + +use std::error::Error as StdError; +use std::fmt; +use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; +use std::sync::Arc; +use std::time::Duration; + +use reqwest::StatusCode; +use reqwest::dns::{Addrs, Name, Resolve, Resolving}; +use reqwest::header::{ + AUTHORIZATION, COOKIE, HeaderMap, HeaderName, HeaderValue, LOCATION, PROXY_AUTHORIZATION, +}; +use url::{Host, Url}; + +/// The most bytes a response may hold, whatever the caller asks for. +pub const MAX_RESPONSE_BYTES: usize = 8 * 1024 * 1024; +/// Package updates have a separate bounded ceiling because ZIP packages are much larger than +/// plugin API responses. This does not widen the ordinary Network.Fetch request budget. +pub const MAX_PACKAGE_RESPONSE_BYTES: usize = 256 * 1024 * 1024; +/// The response budget when the caller names none. +pub const DEFAULT_RESPONSE_BYTES: usize = 1024 * 1024; +/// The longest a whole fetch may take, redirects and body included. +pub const MAX_TIMEOUT: Duration = Duration::from_secs(30); +/// The largest request body. +pub const MAX_REQUEST_BODY_BYTES: usize = 1024 * 1024; +/// Redirects followed before giving up. +pub const MAX_REDIRECTS: usize = 5; +/// The longest URL accepted, in bytes. +pub const MAX_URL_BYTES: usize = 2048; +/// Response headers handed back, and their total size. +pub const MAX_RESPONSE_HEADERS: usize = 64; +pub const MAX_RESPONSE_HEADER_BYTES: usize = 32 * 1024; + +/// Why a fetch did not produce a response. None of them says where the host is or what it +/// resolved to. +#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)] +pub enum FetchError { + /// Not https, not an approved origin, a forbidden address, or credentials in the URL. + #[error("the destination is not allowed")] + Denied, + #[error("the response is larger than the budget")] + TooLarge, + #[error("the fetch took too long")] + Timeout, + #[error("too many redirects")] + TooManyRedirects, + /// The host could not be reached or its certificate was not accepted. + #[error("the destination could not be reached")] + Unreachable, + /// A redirect without a usable target. + #[error("the response is not valid")] + BadResponse, +} + +/// The methods a plugin may use. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Method { + Get, + Head, + Post, + Put, + Patch, + Delete, +} + +impl Method { + fn parse(text: &str) -> Option { + Some(match text { + "" | "GET" => Self::Get, + "HEAD" => Self::Head, + "POST" => Self::Post, + "PUT" => Self::Put, + "PATCH" => Self::Patch, + "DELETE" => Self::Delete, + _ => return None, + }) + } + + fn http(self) -> reqwest::Method { + match self { + Self::Get => reqwest::Method::GET, + Self::Head => reqwest::Method::HEAD, + Self::Post => reqwest::Method::POST, + Self::Put => reqwest::Method::PUT, + Self::Patch => reqwest::Method::PATCH, + Self::Delete => reqwest::Method::DELETE, + } + } + + fn may_have_body(self) -> bool { + !matches!(self, Self::Get | Self::Head) + } +} + +/// The most request headers, and the longest value. +pub const MAX_REQUEST_HEADERS: usize = 32; +pub const MAX_REQUEST_HEADER_VALUE_BYTES: usize = 4096; + +/// Headers the host sets itself or that would change how the request is framed or routed. A +/// plugin cannot send them. +const FORBIDDEN_HEADERS: &[&str] = &[ + "host", + "content-length", + "transfer-encoding", + "connection", + "keep-alive", + "upgrade", + "te", + "trailer", + "expect", + "proxy-authorization", + "proxy-connection", + "via", + "forwarded", + "x-forwarded-for", + "x-forwarded-host", + "x-forwarded-proto", +]; + +/// Why a request was refused for its shape. Messages are safe to show the plugin. +#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)] +pub enum RequestError { + #[error("url must be an https URL of at most {MAX_URL_BYTES} bytes, without credentials")] + Url, + #[error("method must be GET, HEAD, POST, PUT, PATCH or DELETE")] + Method, + #[error("{0}")] + Header(String), + #[error("{0}")] + Body(String), +} + +/// A request that passed the shape checks. The origin it names is still subject to approval. +#[derive(Clone, Debug)] +pub struct Request { + url: Url, + method: Method, + /// Lowercase names, validated. + headers: Vec<(String, String)>, + body: Vec, + max_response_bytes: usize, + timeout: Duration, +} + +impl Request { + /// Validates the parts of a plugin's request. `max_response_bytes` 0 means + /// [`DEFAULT_RESPONSE_BYTES`] and a larger value is capped at [`MAX_RESPONSE_BYTES`]; + /// `timeout_ms` 0 or above [`MAX_TIMEOUT`] means [`MAX_TIMEOUT`]. + pub fn build<'a>( + url: &str, + method: &str, + headers: impl IntoIterator, + body: Vec, + max_response_bytes: u64, + timeout_ms: u32, + ) -> Result { + let mut url = if url.len() > MAX_URL_BYTES { + return Err(RequestError::Url); + } else { + Url::parse(url).map_err(|_| RequestError::Url)? + }; + if url.scheme() != "https" + || url.host().is_none() + || !url.username().is_empty() + || url.password().is_some() + { + return Err(RequestError::Url); + } + url.set_fragment(None); + if origin_of(&url).is_none() { + return Err(RequestError::Url); + } + let method = Method::parse(method).ok_or(RequestError::Method)?; + + let mut list: Vec<(String, String)> = Vec::new(); + for (name, value) in headers { + let lowered = name.to_ascii_lowercase(); + if HeaderName::from_bytes(lowered.as_bytes()).is_err() { + return Err(RequestError::Header(format!( + "`{name}` is not a valid header name" + ))); + } + if FORBIDDEN_HEADERS.contains(&lowered.as_str()) || lowered.starts_with("proxy-") { + return Err(RequestError::Header(format!( + "the header `{name}` is set by the host and cannot be sent" + ))); + } + if value.len() > MAX_REQUEST_HEADER_VALUE_BYTES || HeaderValue::from_str(value).is_err() + { + return Err(RequestError::Header(format!( + "the value of `{name}` is not valid" + ))); + } + if list.iter().any(|(known, _)| *known == lowered) { + return Err(RequestError::Header(format!( + "the header `{name}` is repeated" + ))); + } + list.push((lowered, value.to_owned())); + } + if list.len() > MAX_REQUEST_HEADERS { + return Err(RequestError::Header(format!( + "at most {MAX_REQUEST_HEADERS} headers may be sent" + ))); + } + if body.len() > MAX_REQUEST_BODY_BYTES { + return Err(RequestError::Body(format!( + "the body is larger than {MAX_REQUEST_BODY_BYTES} bytes" + ))); + } + if !body.is_empty() && !method.may_have_body() { + return Err(RequestError::Body( + "GET and HEAD requests carry no body".into(), + )); + } + Ok(Self { + url, + method, + headers: list, + body, + max_response_bytes: match max_response_bytes { + 0 => DEFAULT_RESPONSE_BYTES, + bytes => usize::try_from(bytes) + .unwrap_or(usize::MAX) + .min(MAX_RESPONSE_BYTES), + }, + timeout: match timeout_ms { + 0 => MAX_TIMEOUT, + ms => Duration::from_millis(u64::from(ms)).min(MAX_TIMEOUT), + }, + }) + } + + /// Builds the host-only request used to fetch a signed plugin package archive. It shares the + /// HTTPS URL checks and fetch client's redirect/DNS/deadline validation while using the + /// package archive size ceiling instead of the smaller plugin RPC response ceiling. + pub fn build_package_download( + url: &str, + max_response_bytes: u64, + ) -> Result { + let mut url = if url.len() > MAX_URL_BYTES { + return Err(RequestError::Url); + } else { + Url::parse(url).map_err(|_| RequestError::Url)? + }; + if url.scheme() != "https" + || url.host().is_none() + || !url.username().is_empty() + || url.password().is_some() + || origin_of(&url).is_none() + { + return Err(RequestError::Url); + } + url.set_fragment(None); + let budget = usize::try_from(max_response_bytes).unwrap_or(usize::MAX); + if budget == 0 || budget > MAX_PACKAGE_RESPONSE_BYTES { + return Err(RequestError::Body( + "package response exceeds the host limit".into(), + )); + } + Ok(Self { + url, + method: Method::Get, + headers: Vec::new(), + body: Vec::new(), + max_response_bytes: budget, + timeout: MAX_TIMEOUT, + }) + } + + /// The origin this request is first sent to. + pub fn origin(&self) -> Option { + origin_of(&self.url) + } + + pub fn url(&self) -> &Url { + &self.url + } + + pub fn method(&self) -> &'static str { + match self.method { + Method::Get => "GET", + Method::Head => "HEAD", + Method::Post => "POST", + Method::Put => "PUT", + Method::Patch => "PATCH", + Method::Delete => "DELETE", + } + } + + pub fn headers(&self) -> &[(String, String)] { + &self.headers + } + + pub fn body(&self) -> &[u8] { + &self.body + } + + pub fn max_response_bytes(&self) -> usize { + self.max_response_bytes + } + + pub fn timeout(&self) -> Duration { + self.timeout + } +} + +/// What came back. +#[derive(Clone, Debug)] +pub struct Response { + pub status: u16, + /// Lowercase names; repeated headers are joined with `, `. Bounded. + pub headers: Vec<(String, String)>, + pub body: Vec, + /// The origin the final response came from. + pub final_origin: String, +} + +/// What a client may do. The real one never relaxes either; tests do, to reach a local server. +#[derive(Clone, Copy, Debug)] +struct Policy { + require_https: bool, + allow_local: bool, +} + +/// An HTTPS client for plugin fetches. +pub struct FetchClient { + client: reqwest::Client, + policy: Policy, +} + +#[derive(Debug)] +struct Blocked; + +impl fmt::Display for Blocked { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("address not allowed") + } +} + +impl StdError for Blocked {} + +/// Resolves with the system resolver and refuses any answer that holds a forbidden address. +struct PublicOnly { + allow_local: bool, +} + +impl Resolve for PublicOnly { + fn resolve(&self, name: Name) -> Resolving { + let allow_local = self.allow_local; + Box::pin(async move { + let found: Vec = tokio::net::lookup_host((name.as_str(), 0)) + .await + .map_err(|error| Box::new(error) as Box)? + .collect(); + // One forbidden address spoils the answer: a name that also points inside is not + // one to talk to. + if found.is_empty() || (!allow_local && found.iter().any(|a| !is_public(a.ip()))) { + return Err(Box::new(Blocked) as Box); + } + Ok(Box::new(found.into_iter()) as Addrs) + }) + } +} + +/// Whether `ip` is an address a plugin may be sent to: a public, routable one. +pub fn is_public(ip: IpAddr) -> bool { + match ip { + IpAddr::V4(v4) => public_v4(v4), + IpAddr::V6(v6) => public_v6(v6), + } +} + +fn public_v4(ip: Ipv4Addr) -> bool { + let [a, b, c, _] = ip.octets(); + !(ip.is_unspecified() + || ip.is_loopback() + || ip.is_private() + || ip.is_link_local() + || ip.is_broadcast() + || ip.is_multicast() + || a == 0 // "this network" + || (a == 100 && (64..=127).contains(&b)) // shared address space (CGNAT) + || (a == 192 && b == 0 && c == 0) // IETF protocol assignments + || (a == 192 && b == 0 && c == 2) // documentation + || (a == 198 && (b == 18 || b == 19)) // benchmarking + || (a == 198 && b == 51 && c == 100) // documentation + || (a == 203 && b == 0 && c == 113) // documentation + || a >= 240) // reserved +} + +fn public_v6(ip: Ipv6Addr) -> bool { + let segments = ip.segments(); + // IPv4 carried inside IPv6 is judged as the IPv4 address it is. + if let Some(v4) = ip.to_ipv4_mapped() { + return public_v4(v4); + } + let embedded = |high: u16, low: u16| { + Ipv4Addr::new((high >> 8) as u8, high as u8, (low >> 8) as u8, low as u8) + }; + // 64:ff9b::/96 (NAT64) and 2002::/16 (6to4) embed an IPv4 address. + if segments[..6] == [0x64, 0xff9b, 0, 0, 0, 0] { + return public_v4(embedded(segments[6], segments[7])); + } + if segments[0] == 0x2002 { + return public_v4(embedded(segments[1], segments[2])); + } + !(ip.is_unspecified() + || ip.is_loopback() + || ip.is_multicast() + || (segments[0] & 0xfe00) == 0xfc00 // unique local fc00::/7 + || (segments[0] & 0xffc0) == 0xfe80 // link-local fe80::/10 + || (segments[0] & 0xffc0) == 0xfec0 // deprecated site-local + || segments[..6] == [0, 0, 0, 0, 0, 0] // IPv4-compatible (deprecated) + || (segments[0] == 0x2001 && segments[1] == 0) // Teredo + || (segments[0] == 0x2001 && segments[1] == 0x0db8) // documentation + || (segments[0] == 0x0100 && segments[1..4] == [0, 0, 0])) // discard-only +} + +/// The exact origin of `url` as text (`https://host` or `https://host:port`), or `None` when it +/// is not an https URL with a host. +pub fn origin_of(url: &Url) -> Option { + // A name is letters, digits, hyphens and dots (after punycode); `*` and the like are not part + // of a host, so no origin can stand for several. + let named = match url.host() { + Some(Host::Domain(name)) => name + .chars() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '.' | '_')), + Some(_) => true, + None => false, + }; + (url.scheme() == "https" && named).then(|| url.origin().ascii_serialization()) +} + +/// Why a redirect or request target is refused, before any connection. +fn check_target(url: &Url, policy: Policy) -> Result { + if url.as_str().len() > MAX_URL_BYTES + || !url.username().is_empty() + || url.password().is_some() + || url.host().is_none() + { + return Err(FetchError::Denied); + } + let secure = url.scheme() == "https"; + if !secure && (policy.require_https || url.scheme() != "http") { + return Err(FetchError::Denied); + } + // An address in the URL never reaches the resolver, so it is judged here. + let literal = match url.host() { + Some(Host::Ipv4(ip)) => Some(IpAddr::V4(ip)), + Some(Host::Ipv6(ip)) => Some(IpAddr::V6(ip)), + _ => None, + }; + if literal.is_some_and(|ip| !policy.allow_local && !is_public(ip)) { + return Err(FetchError::Denied); + } + Ok(url.origin().ascii_serialization()) +} + +fn is_redirect(status: StatusCode) -> bool { + matches!(status.as_u16(), 301 | 302 | 303 | 307 | 308) +} + +/// Finds the cause of a failed send: a refused address, a timeout, or anything else. +fn classify(error: &reqwest::Error) -> FetchError { + let mut source: Option<&(dyn StdError + 'static)> = Some(error); + while let Some(current) = source { + if current.is::() { + return FetchError::Denied; + } + source = current.source(); + } + if error.is_timeout() { + FetchError::Timeout + } else if error.is_builder() { + // The client refuses a scheme it was told not to use. + FetchError::Denied + } else { + FetchError::Unreachable + } +} + +impl FetchClient { + /// The client plugins use: https only, public addresses only. + pub fn new() -> Result { + Self::build(Policy { + require_https: true, + allow_local: false, + }) + } + + fn build(policy: Policy) -> Result { + let client = reqwest::Client::builder() + .redirect(reqwest::redirect::Policy::none()) + .no_proxy() + .pool_max_idle_per_host(0) + .https_only(policy.require_https) + .dns_resolver(Arc::new(PublicOnly { + allow_local: policy.allow_local, + })) + .user_agent(concat!( + "GameNode-Desktop/", + env!("CARGO_PKG_VERSION"), + " plugin-fetch" + )) + .build()?; + Ok(Self { client, policy }) + } + + /// A client that may talk plain HTTP to local servers, for tests only. + #[cfg(test)] + fn for_tests(allow_local: bool) -> Self { + Self::build(Policy { + require_https: false, + allow_local, + }) + .unwrap() + } + + /// Fetches `request`. `allow` is asked, with the exact origin, before the first request and + /// before every redirect is followed; returning false ends the fetch with + /// [`FetchError::Denied`] and nothing is sent to that origin. + pub async fn fetch( + &self, + request: Request, + allow: impl Fn(&str) -> bool + Send + Sync, + ) -> Result { + self.fetch_with_origin_check(request, |origin| std::future::ready(allow(&origin))) + .await + } + + /// Like `fetch`, with an asynchronous authorization check before each request. + pub async fn fetch_with_origin_check( + &self, + request: Request, + allow: impl Fn(String) -> F + Send + Sync, + ) -> Result + where + F: std::future::Future + Send, + { + let deadline = request.timeout; + tokio::time::timeout(deadline, self.run(request, allow)) + .await + .map_err(|_| FetchError::Timeout)? + } + + async fn run( + &self, + request: Request, + allow: impl Fn(String) -> F + Send + Sync, + ) -> Result + where + F: std::future::Future + Send, + { + let budget = request.max_response_bytes; + let Request { + mut url, + mut method, + headers, + mut body, + .. + } = request; + let mut headers: HeaderMap = headers + .iter() + .map(|(name, value)| { + Some(( + HeaderName::from_bytes(name.as_bytes()).ok()?, + HeaderValue::from_str(value).ok()?, + )) + }) + .collect::>() + .ok_or(FetchError::Denied)?; + for hop in 0..=MAX_REDIRECTS { + let origin = check_target(&url, self.policy)?; + if !allow(origin.clone()).await { + return Err(FetchError::Denied); + } + let mut sending = self + .client + .request(method.http(), url.clone()) + .headers(headers.clone()); + if !body.is_empty() { + sending = sending.body(body.clone()); + } + let mut response = sending.send().await.map_err(|error| classify(&error))?; + let status = response.status(); + + let target = if is_redirect(status) { + response + .headers() + .get(LOCATION) + .and_then(|value| value.to_str().ok()) + .map(|location| url.join(location).map_err(|_| FetchError::BadResponse)) + } else { + None + }; + if let Some(target) = target { + let next = target?; + if hop == MAX_REDIRECTS { + return Err(FetchError::TooManyRedirects); + } + // A redirect response's body is never read. + drop(response); + // Credentials stay with the origin they were meant for. + if next.origin() != url.origin() { + headers.remove(AUTHORIZATION); + headers.remove(COOKIE); + headers.remove(PROXY_AUTHORIZATION); + } + // As browsers do: 303, and POST after 301/302, continue as a body-less GET. + let switch = status.as_u16() == 303 && method != Method::Head + || matches!(status.as_u16(), 301 | 302) && method == Method::Post; + if switch { + method = Method::Get; + body = Vec::new(); + headers.remove(reqwest::header::CONTENT_TYPE); + } + url = next; + continue; + } + + if response + .content_length() + .is_some_and(|length| length > budget as u64) + { + return Err(FetchError::TooLarge); + } + let mut collected = Vec::new(); + while let Some(chunk) = response.chunk().await.map_err(|error| classify(&error))? { + if collected.len() + chunk.len() > budget { + return Err(FetchError::TooLarge); + } + collected.extend_from_slice(&chunk); + } + return Ok(Response { + status: status.as_u16(), + headers: header_list(response.headers()), + body: collected, + final_origin: origin, + }); + } + Err(FetchError::TooManyRedirects) + } +} + +/// The response headers a plugin gets: lowercase names, repeated ones joined, bounded in count +/// and size (the rest are dropped). +fn header_list(headers: &HeaderMap) -> Vec<(String, String)> { + let mut list: Vec<(String, String)> = Vec::new(); + let mut bytes = 0; + for (name, value) in headers { + let value = String::from_utf8_lossy(value.as_bytes()).into_owned(); + if let Some((_, joined)) = list.iter_mut().find(|(known, _)| known == name.as_str()) { + if bytes + value.len() + 2 > MAX_RESPONSE_HEADER_BYTES { + continue; + } + bytes += value.len() + 2; + joined.push_str(", "); + joined.push_str(&value); + continue; + } + if list.len() >= MAX_RESPONSE_HEADERS + || bytes + name.as_str().len() + value.len() > MAX_RESPONSE_HEADER_BYTES + { + continue; + } + bytes += name.as_str().len() + value.len(); + list.push((name.as_str().to_owned(), value)); + } + list +} + +#[cfg(test)] +mod tests; diff --git a/crates/platform/src/plugin_network/tests.rs b/crates/platform/src/plugin_network/tests.rs new file mode 100644 index 000000000..d9d443287 --- /dev/null +++ b/crates/platform/src/plugin_network/tests.rs @@ -0,0 +1,927 @@ +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex}; + +use reqwest::header::{HeaderName, HeaderValue}; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::net::TcpListener; + +use super::*; + +enum Reply { + Raw(Vec), + /// Never answers. + Hang, +} + +struct Server { + port: u16, + hits: Arc, + seen: Arc>>, +} + +impl Server { + fn url(&self, path: &str) -> Url { + Url::parse(&format!("http://127.0.0.1:{}{path}", self.port)).unwrap() + } + + fn origin(&self) -> String { + format!("http://127.0.0.1:{}", self.port) + } + + fn hits(&self) -> usize { + self.hits.load(Ordering::SeqCst) + } + + fn last_request(&self) -> String { + self.seen + .lock() + .unwrap() + .last() + .cloned() + .unwrap_or_default() + } +} + +/// A local HTTP server: every connection is one request, answered by `handler`. +async fn serve(handler: impl Fn(&str) -> Reply + Send + Sync + 'static) -> Server { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + let hits = Arc::new(AtomicUsize::new(0)); + let seen = Arc::new(Mutex::new(Vec::new())); + let handler = Arc::new(handler); + let (counted, recorded) = (hits.clone(), seen.clone()); + tokio::spawn(async move { + loop { + let Ok((mut stream, _)) = listener.accept().await else { + return; + }; + counted.fetch_add(1, Ordering::SeqCst); + let (handler, recorded) = (handler.clone(), recorded.clone()); + tokio::spawn(async move { + let mut buffer = Vec::new(); + let mut chunk = [0u8; 4096]; + let head_end = loop { + let read = stream.read(&mut chunk).await.unwrap_or(0); + if read == 0 { + return; + } + buffer.extend_from_slice(&chunk[..read]); + if let Some(at) = buffer.windows(4).position(|w| w == b"\r\n\r\n") { + break at + 4; + } + }; + let head = String::from_utf8_lossy(&buffer[..head_end]).to_lowercase(); + let length = head + .lines() + .find_map(|line| line.strip_prefix("content-length:")) + .and_then(|value| value.trim().parse::().ok()) + .unwrap_or(0); + while buffer.len() < head_end + length { + let read = stream.read(&mut chunk).await.unwrap_or(0); + if read == 0 { + break; + } + buffer.extend_from_slice(&chunk[..read]); + } + let raw = String::from_utf8_lossy(&buffer).into_owned(); + recorded.lock().unwrap().push(raw.clone()); + match handler(&raw) { + Reply::Raw(bytes) => { + let _ = stream.write_all(&bytes).await; + let _ = stream.shutdown().await; + } + Reply::Hang => tokio::time::sleep(Duration::from_secs(120)).await, + } + }); + } + }); + Server { port, hits, seen } +} + +fn ok(body: &str) -> Reply { + Reply::Raw( + format!( + "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nContent-Type: text/plain\r\nX-Reply: yes\r\nConnection: close\r\n\r\n{body}", + body.len() + ) + .into_bytes(), + ) +} + +fn redirect(code: u16, location: &str) -> Reply { + Reply::Raw( + format!( + "HTTP/1.1 {code} Redirect\r\nLocation: {location}\r\nContent-Length: 5\r\nConnection: close\r\n\r\nsecret" + ) + .into_bytes(), + ) +} + +/// A GET of `url`. The tests talk to plain-HTTP local servers, so the request is assembled +/// directly rather than through [`Request::build`], which only takes https. +fn get(url: Url) -> Request { + Request { + url, + method: Method::Get, + headers: Vec::new(), + body: Vec::new(), + max_response_bytes: DEFAULT_RESPONSE_BYTES, + timeout: Duration::from_secs(10), + } +} + +fn with_header(mut request: Request, name: &str, value: &str) -> Request { + request.headers.push((name.to_owned(), value.to_owned())); + request +} + +fn local() -> FetchClient { + FetchClient::for_tests(true) +} + +fn any(_: &str) -> bool { + true +} + +// ---- addresses and URLs ---- + +#[test] +fn only_public_addresses_are_allowed() { + let public = [ + "8.8.8.8", + "1.1.1.1", + "93.184.216.34", + "172.32.0.1", + "100.63.255.255", + "100.128.0.1", + "2606:4700:4700::1111", + "2a00:1450:4001::200e", + "::ffff:8.8.8.8", + "64:ff9b::808:808", + "2002:808:808::1", + ]; + for text in public { + assert!(is_public(text.parse().unwrap()), "{text} should be public"); + } + let forbidden = [ + "127.0.0.1", + "127.255.255.254", + "0.0.0.0", + "0.1.2.3", + "10.0.0.1", + "172.16.0.1", + "172.31.255.255", + "192.168.1.1", + "169.254.169.254", + "100.64.0.1", + "100.127.255.255", + "192.0.0.1", + "192.0.2.1", + "198.18.0.1", + "198.19.255.255", + "198.51.100.1", + "203.0.113.1", + "224.0.0.1", + "239.255.255.255", + "240.0.0.1", + "255.255.255.255", + "::", + "::1", + "fe80::1", + "fec0::1", + "fc00::1", + "fd12:3456::1", + "ff02::1", + "2001:db8::1", + "2001:0:4136:e378:8000:63bf:3fff:fdd2", + "::ffff:127.0.0.1", + "::ffff:10.0.0.1", + "::ffff:169.254.169.254", + "64:ff9b::7f00:1", + "64:ff9b::a00:1", + "2002:7f00:1::1", + "2002:c0a8:101::1", + "::1.2.3.4", + "100::1", + ]; + for text in forbidden { + assert!( + !is_public(text.parse().unwrap()), + "{text} should be refused" + ); + } +} + +#[test] +fn an_origin_is_scheme_host_and_port_exactly() { + let origin = |text: &str| origin_of(&Url::parse(text).unwrap()); + assert_eq!( + origin("https://Example.COM/a/b?q=1#f").as_deref(), + Some("https://example.com") + ); + assert_eq!( + origin("https://example.com:443/").as_deref(), + Some("https://example.com") + ); + assert_eq!( + origin("https://example.com:8443/").as_deref(), + Some("https://example.com:8443") + ); + assert_eq!( + origin("https://[2606:4700::1]:8443/").as_deref(), + Some("https://[2606:4700::1]:8443") + ); + assert_eq!( + origin("https://bücher.example/").as_deref(), + Some("https://xn--bcher-kva.example") + ); + assert_eq!(origin("http://example.com/"), None); + assert_eq!(origin("ftp://example.com/"), None); + // Different hosts, subdomains and ports are different origins. + assert_ne!( + origin("https://example.com/"), + origin("https://www.example.com/") + ); + assert_ne!( + origin("https://example.com/"), + origin("https://example.com:444/") + ); + // A host that merely starts like an approved one is another origin. + assert_ne!( + origin("https://example.com.evil.test/"), + origin("https://example.com/") + ); +} + +#[test] +fn targets_must_be_https_public_and_free_of_credentials() { + let strict = Policy { + require_https: true, + allow_local: false, + }; + let check = |text: &str| check_target(&Url::parse(text).unwrap(), strict); + assert_eq!( + check("https://example.com/path?x=1").as_deref(), + Ok("https://example.com") + ); + assert_eq!(check("https://8.8.8.8/").as_deref(), Ok("https://8.8.8.8")); + for denied in [ + "http://example.com/", + "ftp://example.com/", + "file:///etc/passwd", + "https://user@example.com/", + "https://user:pass@example.com/", + "https://127.0.0.1/", + "https://127.1/", + "https://2130706433/", + "https://0x7f.0.0.1/", + "https://[::1]/", + "https://[::ffff:127.0.0.1]/", + "https://10.1.2.3:8443/", + "https://192.168.0.10/", + "https://169.254.169.254/latest/meta-data/", + "https://[fd00::1]/", + "https://0.0.0.0/", + ] { + assert_eq!(check(denied), Err(FetchError::Denied), "{denied}"); + } + let long = format!("https://example.com/{}", "a".repeat(MAX_URL_BYTES)); + assert_eq!(check(&long), Err(FetchError::Denied)); +} + +// ---- the happy path ---- + +#[tokio::test] +async fn a_fetch_returns_status_headers_body_and_the_final_origin() { + let server = serve(|_| ok("hello")).await; + let request = with_header(get(server.url("/page?x=1")), "x-custom", "mine"); + let response = local().fetch(request, any).await.unwrap(); + assert_eq!(response.status, 200); + assert_eq!(response.body, b"hello"); + assert_eq!(response.final_origin, server.origin()); + let headers: std::collections::HashMap<_, _> = response.headers.into_iter().collect(); + assert_eq!(headers["x-reply"], "yes"); + assert_eq!(headers["content-type"], "text/plain"); + + let seen = server.last_request().to_lowercase(); + assert!(seen.starts_with("get /page?x=1 http/1.1"), "{seen}"); + assert!(seen.contains("x-custom: mine")); + // Nothing of GameNode's own: no cookie, no authorization, no referer. + assert!(seen.contains("user-agent: gamenode-desktop/"), "{seen}"); + for forbidden in [ + "cookie:", + "authorization:", + "referer:", + "proxy-authorization:", + ] { + assert!(!seen.contains(forbidden), "{forbidden} in {seen}"); + } +} + +#[tokio::test] +async fn a_body_is_sent_with_its_method_and_error_statuses_are_responses() { + let server = serve(|raw| { + if raw.starts_with("POST") && raw.ends_with("payload") { + Reply::Raw( + b"HTTP/1.1 404 Not Found\r\nContent-Length: 3\r\nConnection: close\r\n\r\nnah" + .to_vec(), + ) + } else { + ok("wrong") + } + }) + .await; + let mut request = get(server.url("/")); + request.method = Method::Post; + request.body = b"payload".to_vec(); + let response = local().fetch(request, any).await.unwrap(); + assert_eq!( + (response.status, response.body.as_slice()), + (404, &b"nah"[..]) + ); +} + +#[tokio::test] +async fn head_requests_return_no_body() { + let server = serve(|_| { + Reply::Raw(b"HTTP/1.1 200 OK\r\nContent-Length: 1000\r\nConnection: close\r\n\r\n".to_vec()) + }) + .await; + let mut request = get(server.url("/")); + request.method = Method::Head; + let response = local().fetch(request, any).await.unwrap(); + assert!(response.body.is_empty()); +} + +// ---- bounds ---- + +#[tokio::test] +async fn a_response_over_the_budget_is_refused_not_cut_short() { + let big = "x".repeat(1000); + let server = serve(move |_| ok(&big)).await; + let mut request = get(server.url("/")); + request.max_response_bytes = 999; + assert_eq!( + local().fetch(request.clone(), any).await.unwrap_err(), + FetchError::TooLarge + ); + request.max_response_bytes = 1000; + assert_eq!(local().fetch(request, any).await.unwrap().body.len(), 1000); +} + +#[tokio::test] +async fn a_body_that_outgrows_the_budget_while_streaming_is_refused() { + // No Content-Length: the size is only known by reading. + let server = serve(|_| { + let mut bytes = b"HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n".to_vec(); + bytes.extend(std::iter::repeat_n(b'y', 5000)); + Reply::Raw(bytes) + }) + .await; + let mut request = get(server.url("/")); + request.max_response_bytes = 4000; + assert_eq!( + local().fetch(request, any).await.unwrap_err(), + FetchError::TooLarge + ); +} + +#[tokio::test] +async fn the_budget_never_exceeds_the_hard_cap() { + let server = serve(|_| ok("small")).await; + let mut request = get(server.url("/")); + request.max_response_bytes = usize::MAX; + assert_eq!(local().fetch(request, any).await.unwrap().body, b"small"); + assert_eq!(MAX_RESPONSE_BYTES, 8 * 1024 * 1024); +} + +#[tokio::test] +async fn one_deadline_covers_the_whole_fetch() { + let hanging = serve(|_| Reply::Hang).await; + let mut request = get(hanging.url("/")); + request.timeout = Duration::from_millis(150); + let started = std::time::Instant::now(); + assert_eq!( + local().fetch(request, any).await.unwrap_err(), + FetchError::Timeout + ); + assert!(started.elapsed() < Duration::from_secs(5)); + + // A body that never finishes counts too. + let slow = serve(|_| { + Reply::Raw( + b"HTTP/1.1 200 OK\r\nContent-Length: 100\r\nConnection: close\r\n\r\nstart".to_vec(), + ) + }) + .await; + let mut request = get(slow.url("/")); + request.timeout = Duration::from_millis(300); + let error = local().fetch(request, any).await.unwrap_err(); + assert!( + matches!(error, FetchError::Timeout | FetchError::Unreachable), + "{error:?}" + ); +} + +#[tokio::test] +async fn the_deadline_is_capped_at_the_maximum() { + let server = serve(|_| ok("fast")).await; + let mut request = get(server.url("/")); + request.timeout = Duration::from_secs(3600); + assert_eq!(local().fetch(request, any).await.unwrap().body, b"fast"); + assert_eq!(MAX_TIMEOUT, Duration::from_secs(30)); +} + +// ---- redirects ---- + +#[tokio::test] +async fn redirects_are_followed_within_the_approved_origin() { + let server = serve(|raw| { + if raw.starts_with("GET /start") { + redirect(302, "/middle") + } else if raw.starts_with("GET /middle") { + redirect(301, "http://127.0.0.1:1/ignored-port-replaced") + } else { + ok("end") + } + }) + .await; + // The second hop names a different port: it is a different origin and must be asked about. + let asked = Mutex::new(Vec::new()); + let origin = server.origin(); + let error = local() + .fetch(get(server.url("/start")), |candidate| { + asked.lock().unwrap().push(candidate.to_owned()); + candidate == origin + }) + .await + .unwrap_err(); + assert_eq!(error, FetchError::Denied); + assert_eq!( + asked.lock().unwrap().as_slice(), + [ + origin.clone(), + origin.clone(), + "http://127.0.0.1:1".to_owned() + ] + ); + assert_eq!( + server.hits(), + 2, + "the unapproved origin was never contacted" + ); + + let server = serve(|raw| { + if raw.starts_with("GET /start") { + redirect(302, "/end") + } else { + ok("end") + } + }) + .await; + let origin = server.origin(); + let response = local() + .fetch(get(server.url("/start")), |c| c == origin) + .await + .unwrap(); + assert_eq!( + (response.body.as_slice(), response.final_origin), + (&b"end"[..], origin) + ); +} + +#[tokio::test] +async fn a_redirect_to_an_unapproved_origin_is_refused_before_anything_is_sent_there() { + let other = serve(|_| ok("loot")).await; + let target = other.url("/loot").to_string(); + let first = serve(move |_| redirect(302, &target)).await; + let approved = first.origin(); + let error = local() + .fetch(get(first.url("/")), |origin| origin == approved) + .await + .unwrap_err(); + assert_eq!(error, FetchError::Denied); + assert_eq!( + other.hits(), + 0, + "no connection reached the unapproved origin" + ); +} + +#[tokio::test] +async fn update_package_redirect_checks_the_new_origin_before_download() { + let destination = serve(|_| ok("signed package archive")).await; + let target = destination.url("/release.zip").to_string(); + let feed = serve(move |_| redirect(302, &target)).await; + let only_feed = feed.origin(); + let error = local() + .fetch(get(feed.url("/plugin.zip")), |origin| origin == only_feed) + .await + .unwrap_err(); + assert_eq!(error, FetchError::Denied); + assert_eq!(destination.hits(), 0); + + let allowed = [feed.origin(), destination.origin()]; + let response = local() + .fetch(get(feed.url("/plugin.zip")), |origin| { + allowed.contains(&origin.to_owned()) + }) + .await + .unwrap(); + assert_eq!(response.body, b"signed package archive"); +} + +#[tokio::test] +async fn a_widened_approval_is_checked_at_every_hop() { + let other = serve(|_| ok("fine")).await; + let target = other.url("/").to_string(); + let first = serve(move |_| redirect(302, &target)).await; + let both = [first.origin(), other.origin()]; + let response = local() + .fetch(get(first.url("/")), |o| both.contains(&o.to_owned())) + .await + .unwrap(); + assert_eq!(response.body, b"fine"); + // Revoking one origin between hops stops the second. + let only_first = [first.origin()]; + let error = local() + .fetch(get(first.url("/")), |o| only_first.contains(&o.to_owned())) + .await + .unwrap_err(); + assert_eq!(error, FetchError::Denied); +} + +#[tokio::test] +async fn redirect_chains_are_bounded() { + let server = serve(|_| redirect(302, "/again")).await; + let origin = server.origin(); + let error = local() + .fetch(get(server.url("/")), |o| o == origin) + .await + .unwrap_err(); + assert_eq!(error, FetchError::TooManyRedirects); + assert_eq!(server.hits(), MAX_REDIRECTS + 1); +} + +#[tokio::test] +async fn credentials_do_not_follow_a_redirect_to_another_origin() { + let other = serve(|_| ok("done")).await; + let target = other.url("/").to_string(); + let first = serve(move |raw| { + if raw.starts_with("GET /same") { + redirect(302, "/landing") + } else if raw.starts_with("GET /landing") { + ok("landed") + } else { + redirect(302, &target) + } + }) + .await; + let origins = [first.origin(), other.origin()]; + let with_credentials = |url| { + let request = with_header(get(url), "authorization", "Bearer secret"); + let request = with_header(request, "cookie", "sid=1"); + with_header(request, "x-keep", "yes") + }; + + // Same origin: the plugin's own credentials stay. + local() + .fetch(with_credentials(first.url("/same")), |o| { + origins.contains(&o.to_owned()) + }) + .await + .unwrap(); + let landing = first.last_request().to_lowercase(); + assert!( + landing.contains("authorization: bearer secret") && landing.contains("cookie: sid=1"), + "{landing}" + ); + + // Another origin: they are dropped, other headers stay. + local() + .fetch(with_credentials(first.url("/cross")), |o| { + origins.contains(&o.to_owned()) + }) + .await + .unwrap(); + let crossed = other.last_request().to_lowercase(); + assert!( + !crossed.contains("authorization") && !crossed.contains("cookie"), + "{crossed}" + ); + assert!(crossed.contains("x-keep: yes")); +} + +#[tokio::test] +async fn redirect_methods_follow_the_usual_rules() { + let server = serve(|raw| { + let path = raw.split_whitespace().nth(1).unwrap_or("").to_owned(); + match path.as_str() { + "/303" => redirect(303, "/final"), + "/307" => redirect(307, "/final"), + "/302" => redirect(302, "/final"), + _ => ok("ok"), + } + }) + .await; + let origin = server.origin(); + let post = |path: &str| { + let mut request = with_header(get(server.url(path)), "content-type", "text/plain"); + request.method = Method::Post; + request.body = b"data".to_vec(); + request + }; + for (path, method, keeps_body) in [ + ("/303", "GET", false), + ("/302", "GET", false), + ("/307", "POST", true), + ] { + local().fetch(post(path), |o| o == origin).await.unwrap(); + let landed = server.last_request(); + assert!( + landed.starts_with(&format!("{method} /final")), + "{path}: {landed}" + ); + assert_eq!(landed.ends_with("data"), keeps_body, "{path}: {landed}"); + } +} + +#[tokio::test] +async fn bad_redirects_are_errors_and_a_redirect_without_a_target_is_a_response() { + let bad = serve(|_| redirect(302, "http://[::bad")).await; + let origin = bad.origin(); + assert_eq!( + local() + .fetch(get(bad.url("/")), |o| o == origin) + .await + .unwrap_err(), + FetchError::BadResponse + ); + + let none = serve(|_| { + Reply::Raw( + b"HTTP/1.1 302 Found\r\nContent-Length: 4\r\nConnection: close\r\n\r\nbody".to_vec(), + ) + }) + .await; + let origin = none.origin(); + let response = local() + .fetch(get(none.url("/")), |o| o == origin) + .await + .unwrap(); + assert_eq!( + (response.status, response.body.as_slice()), + (302, &b"body"[..]) + ); +} + +#[tokio::test] +async fn a_redirect_never_discloses_its_target_or_its_body() { + let server = serve(|_| redirect(302, "https://internal.example/secret-path")).await; + let error = local() + .fetch(get(server.url("/")), |_| false) + .await + .unwrap_err(); + // The error is the bare reason; there is nowhere for the location to travel. + assert_eq!( + format!("{error} {error:?}"), + "the destination is not allowed Denied" + ); +} + +// ---- private and local destinations ---- + +#[tokio::test] +async fn local_and_private_destinations_are_refused_before_any_connection() { + let strict = FetchClient::build(Policy { + require_https: false, + allow_local: false, + }) + .unwrap(); + let server = serve(|_| ok("internal")).await; + for url in [ + server.url("/"), + Url::parse(&format!("http://localhost:{}/", server.port)).unwrap(), + Url::parse(&format!("http://[::1]:{}/", server.port)).unwrap(), + Url::parse(&format!("http://0.0.0.0:{}/", server.port)).unwrap(), + ] { + let error = strict.fetch(get(url.clone()), any).await.unwrap_err(); + assert!( + matches!(error, FetchError::Denied | FetchError::Unreachable), + "{url}: {error:?}" + ); + } + assert_eq!(server.hits(), 0, "no request reached a local server"); + // A name that resolves inside is refused by the resolver, not by the URL check. + let by_name = Url::parse(&format!("http://localhost:{}/", server.port)).unwrap(); + assert_eq!( + strict.fetch(get(by_name), any).await.unwrap_err(), + FetchError::Denied + ); +} + +#[tokio::test] +async fn the_real_client_only_speaks_https() { + let strict = FetchClient::new().unwrap(); + let server = serve(|_| ok("plain")).await; + assert_eq!( + strict.fetch(get(server.url("/")), any).await.unwrap_err(), + FetchError::Denied + ); + assert_eq!(server.hits(), 0); +} + +#[tokio::test] +async fn an_unreachable_host_is_just_unreachable() { + let port = { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + listener.local_addr().unwrap().port() + }; + let url = Url::parse(&format!("http://127.0.0.1:{port}/")).unwrap(); + assert_eq!( + local().fetch(get(url), any).await.unwrap_err(), + FetchError::Unreachable + ); +} + +// ---- response headers ---- + +#[test] +fn response_headers_are_lowercased_joined_and_bounded() { + let mut headers = HeaderMap::new(); + headers.append("Set-Cookie", HeaderValue::from_static("a=1")); + headers.append("Set-Cookie", HeaderValue::from_static("b=2")); + headers.append("X-One", HeaderValue::from_static("1")); + let list = header_list(&headers); + assert!(list.contains(&("set-cookie".to_owned(), "a=1, b=2".to_owned()))); + assert!(list.contains(&("x-one".to_owned(), "1".to_owned()))); + + let mut many = HeaderMap::new(); + for index in 0..200 { + many.insert( + HeaderName::from_bytes(format!("x-h{index}").as_bytes()).unwrap(), + HeaderValue::from_static("v"), + ); + } + assert_eq!(header_list(&many).len(), MAX_RESPONSE_HEADERS); + + let mut large = HeaderMap::new(); + for index in 0..20 { + large.insert( + HeaderName::from_bytes(format!("x-big{index}").as_bytes()).unwrap(), + HeaderValue::from_str(&"v".repeat(4000)).unwrap(), + ); + } + let total: usize = header_list(&large) + .iter() + .map(|(n, v)| n.len() + v.len()) + .sum(); + assert!(total <= MAX_RESPONSE_HEADER_BYTES); +} + +// ---- the shape of a request ---- + +fn build(url: &str) -> Result { + Request::build(url, "", [], Vec::new(), 0, 0) +} + +#[test] +fn a_request_needs_an_https_url_without_credentials_and_drops_the_fragment() { + let request = build("https://Example.com/a?b=1#frag").unwrap(); + assert_eq!(request.url.as_str(), "https://example.com/a?b=1"); + assert_eq!(request.origin().as_deref(), Some("https://example.com")); + for bad in [ + "http://example.com/", + "ftp://example.com/", + "https://user:pw@example.com/", + "https://user@example.com/", + "not a url", + "https://*.example.com/", + "https://exa mple.com/", + "", + ] { + assert_eq!(build(bad).unwrap_err(), RequestError::Url, "{bad:?}"); + } + let long = format!("https://example.com/{}", "a".repeat(MAX_URL_BYTES)); + assert_eq!(build(&long).unwrap_err(), RequestError::Url); +} + +#[test] +fn methods_are_the_usual_six_and_only_those() { + for (text, method) in [ + ("", Method::Get), + ("GET", Method::Get), + ("HEAD", Method::Head), + ("POST", Method::Post), + ("PUT", Method::Put), + ("PATCH", Method::Patch), + ("DELETE", Method::Delete), + ] { + let request = Request::build("https://example.com/", text, [], Vec::new(), 0, 0).unwrap(); + assert_eq!(request.method, method, "{text:?}"); + } + for bad in [ + "get", "CONNECT", "TRACE", "OPTIONS", "FOO", "GET ", "PROPFIND", + ] { + let error = Request::build("https://example.com/", bad, [], Vec::new(), 0, 0).unwrap_err(); + assert_eq!(error, RequestError::Method, "{bad:?}"); + } +} + +#[test] +fn headers_are_validated_lowercased_and_the_host_ones_are_refused() { + let with = |headers: Vec<(&str, &str)>| { + Request::build("https://example.com/", "POST", headers, b"x".to_vec(), 0, 0) + }; + let ok = with(vec![ + ("Accept", "text/plain"), + ("X-Custom", "v"), + ("Authorization", "Bearer t"), + ]) + .unwrap(); + assert_eq!( + ok.headers[0], + ("accept".to_owned(), "text/plain".to_owned()) + ); + for name in [ + "Host", + "Content-Length", + "Transfer-Encoding", + "Connection", + "Upgrade", + "TE", + "Expect", + "Proxy-Authorization", + "Proxy-Anything", + "Via", + "Forwarded", + "X-Forwarded-For", + ] { + assert!( + matches!(with(vec![(name, "x")]), Err(RequestError::Header(_))), + "{name}" + ); + } + for (name, value) in [ + ("bad name", "x"), + ("", "x"), + ("x-a", "line\r\nInjected: yes"), + ("x-a", "line\nbreak"), + ("x-a", "nul\0"), + ] { + assert!( + matches!(with(vec![(name, value)]), Err(RequestError::Header(_))), + "{name:?} {value:?}" + ); + } + assert!(matches!( + with(vec![("x-a", "1"), ("X-A", "2")]), + Err(RequestError::Header(_)) + )); + let long = "v".repeat(MAX_REQUEST_HEADER_VALUE_BYTES + 1); + assert!(matches!( + with(vec![("x-a", &long)]), + Err(RequestError::Header(_)) + )); + let many: Vec<(String, String)> = (0..=MAX_REQUEST_HEADERS) + .map(|i| (format!("x-{i}"), "v".into())) + .collect(); + let refs: Vec<(&str, &str)> = many.iter().map(|(n, v)| (n.as_str(), v.as_str())).collect(); + assert!(matches!(with(refs), Err(RequestError::Header(_)))); +} + +#[test] +fn bodies_are_bounded_and_only_for_methods_that_carry_one() { + let big = vec![0u8; MAX_REQUEST_BODY_BYTES + 1]; + assert!(matches!( + Request::build("https://example.com/", "POST", [], big, 0, 0), + Err(RequestError::Body(_)) + )); + let limit = vec![0u8; MAX_REQUEST_BODY_BYTES]; + assert!(Request::build("https://example.com/", "PUT", [], limit, 0, 0).is_ok()); + for method in ["GET", "HEAD", ""] { + assert!(matches!( + Request::build("https://example.com/", method, [], b"x".to_vec(), 0, 0), + Err(RequestError::Body(_)) + )); + } +} + +#[test] +fn the_budget_and_the_deadline_default_and_are_capped() { + let request = + |bytes, ms| Request::build("https://example.com/", "", [], Vec::new(), bytes, ms).unwrap(); + assert_eq!(request(0, 0).max_response_bytes, DEFAULT_RESPONSE_BYTES); + assert_eq!(request(0, 0).timeout, MAX_TIMEOUT); + assert_eq!(request(500, 1500).max_response_bytes, 500); + assert_eq!(request(500, 1500).timeout, Duration::from_millis(1500)); + assert_eq!( + request(u64::MAX, u32::MAX).max_response_bytes, + MAX_RESPONSE_BYTES + ); + assert_eq!(request(u64::MAX, u32::MAX).timeout, MAX_TIMEOUT); + assert_eq!( + request((MAX_RESPONSE_BYTES + 1) as u64, 30_001).max_response_bytes, + MAX_RESPONSE_BYTES + ); +} diff --git a/crates/platform/src/plugin_packages.rs b/crates/platform/src/plugin_packages.rs new file mode 100644 index 000000000..39e80ffd3 --- /dev/null +++ b/crates/platform/src/plugin_packages.rs @@ -0,0 +1,1154 @@ +//! Bounded, path-safe extraction for managed plugin packages. +//! +//! Package validation remains in the host. This module accepts the manifest's +//! allowlist and extracts only the files selected for the current target. + +use std::{ + collections::{BTreeMap, BTreeSet}, + fs::{self, File, OpenOptions}, + io::{self, Read, Seek}, + path::{Component, Path, PathBuf}, +}; + +use sha2::Digest; +use thiserror::Error; +use zip::ZipArchive; + +pub const MAX_COMPRESSED_BYTES: u64 = 256 * 1024 * 1024; +pub const MAX_EXPANDED_BYTES: u64 = 512 * 1024 * 1024; +pub const MAX_ENTRIES: usize = 4096; +pub const MAX_METADATA_BYTES: u64 = 4 * 1024 * 1024; +/// ASCII domain label followed by one NUL byte; signed before raw integrity.json bytes. +pub const SIGNATURE_DOMAIN_PREFIX: &[u8] = b"GameNode/.gnplugin/integrity/v1\0"; + +#[derive(Debug, Error, PartialEq, Eq)] +pub enum IntegrityError { + #[error("integrity metadata is malformed or exceeds the size limit")] + InvalidMetadata, + #[error("integrity file does not exactly match the package payload")] + PayloadSetMismatch, + #[error("integrity record contains an invalid SHA-256 digest")] + InvalidDigest, + #[error("a package payload hash does not match")] + HashMismatch, + #[error("publisher key or signature has an invalid length")] + InvalidKeyOrSignature, + #[error("Ed25519 integrity signature is invalid")] + InvalidSignature, +} + +#[derive(Clone, Debug, PartialEq, Eq, serde::Deserialize)] +#[serde(deny_unknown_fields)] +pub struct IntegrityManifest { + pub schema: u32, + pub files: UniqueFiles, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct UniqueFiles(pub BTreeMap); + +impl<'de> serde::Deserialize<'de> for UniqueFiles { + fn deserialize(deserializer: D) -> Result + where + D: serde::Deserializer<'de>, + { + struct FilesVisitor; + impl<'de> serde::de::Visitor<'de> for FilesVisitor { + type Value = UniqueFiles; + + fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str("an object mapping payload paths to SHA-256 digests") + } + + fn visit_map(self, mut map: M) -> Result + where + M: serde::de::MapAccess<'de>, + { + let mut files = BTreeMap::new(); + while let Some((path, digest)) = map.next_entry::()? { + if files.insert(path.clone(), digest).is_some() { + return Err(serde::de::Error::custom(format!( + "duplicate integrity path `{path}`" + ))); + } + } + Ok(UniqueFiles(files)) + } + } + deserializer.deserialize_map(FilesVisitor) + } +} + +/// Parse the bounded integrity record after verifying its detached signature. +pub fn parse_integrity_json(raw: &[u8]) -> Result { + if raw.is_empty() || raw.len() as u64 > MAX_METADATA_BYTES { + return Err(IntegrityError::InvalidMetadata); + } + let manifest: IntegrityManifest = + serde_json::from_slice(raw).map_err(|_| IntegrityError::InvalidMetadata)?; + if manifest.schema != 1 || manifest.files.0.is_empty() { + return Err(IntegrityError::InvalidMetadata); + } + for (path, digest) in &manifest.files.0 { + if validated_relative_path(path).is_err() + || path.ends_with('/') + || path.ends_with('\\') + || digest.len() != 64 + || !digest + .bytes() + .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)) + { + return Err(IntegrityError::InvalidMetadata); + } + } + Ok(manifest) +} + +/// Verify that every supplied payload is listed exactly once and matches its +/// lowercase SHA-256 digest. +pub fn verify_payload_hashes( + declared: &BTreeMap, + payloads: &BTreeMap>, +) -> Result<(), IntegrityError> { + if declared.len() != payloads.len() + || declared.keys().ne(payloads.keys()) + || declared.keys().any(|path| { + validated_relative_path(path).is_err() || path.ends_with('/') || path.ends_with('\\') + }) + { + return Err(IntegrityError::PayloadSetMismatch); + } + for (path, bytes) in payloads { + let expected = declared + .get(path) + .ok_or(IntegrityError::PayloadSetMismatch)?; + if expected.len() != 64 + || !expected + .bytes() + .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)) + { + return Err(IntegrityError::InvalidDigest); + } + let digest = sha2::Sha256::digest(bytes); + if format!("{digest:x}") != *expected { + return Err(IntegrityError::HashMismatch); + } + } + Ok(()) +} + +/// Re-hash the complete package payload from its immutable version directory. +/// This is intended for worker-side checks immediately before process launch. +pub fn verify_payload_files( + version_root: &Path, + declared: &BTreeMap, +) -> Result<(), IntegrityError> { + if declared.is_empty() { + return Err(IntegrityError::PayloadSetMismatch); + } + let root = fs::canonicalize(version_root).map_err(|_| IntegrityError::PayloadSetMismatch)?; + for (relative, expected) in declared { + if validated_relative_path(relative).is_err() + || relative.ends_with('/') + || relative.ends_with('\\') + { + return Err(IntegrityError::PayloadSetMismatch); + } + if expected.len() != 64 + || !expected + .bytes() + .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)) + { + return Err(IntegrityError::InvalidDigest); + } + let path = root.join(relative); + let metadata = + fs::symlink_metadata(&path).map_err(|_| IntegrityError::PayloadSetMismatch)?; + if metadata.file_type().is_symlink() || !metadata.is_file() { + return Err(IntegrityError::PayloadSetMismatch); + } + let canonical = fs::canonicalize(&path).map_err(|_| IntegrityError::PayloadSetMismatch)?; + if !canonical.starts_with(&root) { + return Err(IntegrityError::PayloadSetMismatch); + } + let mut file = File::open(canonical).map_err(|_| IntegrityError::PayloadSetMismatch)?; + let mut hasher = sha2::Sha256::new(); + let mut buffer = [0u8; 64 * 1024]; + loop { + let read = file + .read(&mut buffer) + .map_err(|_| IntegrityError::PayloadSetMismatch)?; + if read == 0 { + break; + } + hasher.update(&buffer[..read]); + } + if format!("{:x}", hasher.finalize()) != *expected { + return Err(IntegrityError::HashMismatch); + } + } + let mut actual_files = BTreeSet::new(); + collect_payload_files(&root, &root, &mut actual_files)?; + if actual_files.len() != declared.len() || actual_files.iter().ne(declared.keys()) { + return Err(IntegrityError::PayloadSetMismatch); + } + Ok(()) +} + +/// Validate the signed package directory produced by the bounded extractor. The detached +/// signature and integrity record are package metadata; every other regular file must be +/// declared and hashed by `integrity.json`. +pub fn verify_package_directory( + package_root: &Path, + publisher_key: &[u8], +) -> Result { + let integrity_path = package_root.join("integrity.json"); + let signature_path = package_root.join("signature.ed25519"); + let integrity_meta = + fs::symlink_metadata(&integrity_path).map_err(|_| IntegrityError::InvalidMetadata)?; + let signature_meta = + fs::symlink_metadata(&signature_path).map_err(|_| IntegrityError::InvalidMetadata)?; + if !integrity_meta.is_file() + || integrity_meta.file_type().is_symlink() + || !signature_meta.is_file() + || signature_meta.file_type().is_symlink() + { + return Err(IntegrityError::InvalidMetadata); + } + let raw = read_bounded(&integrity_path, MAX_METADATA_BYTES as usize) + .map_err(|_| IntegrityError::InvalidMetadata)?; + let signature = + read_bounded(&signature_path, 64).map_err(|_| IntegrityError::InvalidKeyOrSignature)?; + verify_integrity_signature(publisher_key, &raw, &signature)?; + let manifest = parse_integrity_json(&raw)?; + verify_payload_directory_with_metadata(package_root, &manifest.files.0)?; + Ok(manifest) +} + +fn read_bounded(path: &Path, limit: usize) -> io::Result> { + let file = File::open(path)?; + let mut bytes = Vec::with_capacity(limit.min(64 * 1024)); + file.take(limit as u64 + 1).read_to_end(&mut bytes)?; + if bytes.len() > limit { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "file exceeds limit", + )); + } + Ok(bytes) +} + +/// Revalidate an installed package immediately before launch using its pinned publisher key. +pub fn verify_installed_package( + package_root: &Path, + publisher_key: &[u8], +) -> Result<(), IntegrityError> { + verify_package_directory(package_root, publisher_key).map(|_| ()) +} + +/// Validate and extract an existing-format package ZIP into a new staging directory. +/// The ZIP's own signed integrity manifest defines the only payload paths that may be extracted; +/// the ordinary bounded extractor enforces path safety, duplicates, ZIP entry count and expansion +/// limits before the resulting directory is imported by the managed registry. +pub fn stage_package_archive( + archive_path: &Path, + staging_dir: &Path, + publisher_key: &[u8], +) -> Result { + stage_package_archive_inner(archive_path, staging_dir, Some(publisher_key)) +} + +/// Extract a package whose complete archive digest has already been authenticated by a signed +/// update feed. The caller must subsequently validate the extracted package signature using the +/// candidate manifest's publisher key before it can be installed or executed. +pub fn stage_package_archive_from_verified_feed( + archive_path: &Path, + staging_dir: &Path, +) -> Result { + stage_package_archive_inner(archive_path, staging_dir, None) +} + +fn stage_package_archive_inner( + archive_path: &Path, + staging_dir: &Path, + publisher_key: Option<&[u8]>, +) -> Result { + let archive_file = File::open(archive_path)?; + if archive_file.metadata()?.len() > MAX_COMPRESSED_BYTES { + return Err(PackageArchiveError::CompressedLimit); + } + let mut archive = ZipArchive::new(archive_file).map_err(PackageArchiveError::InvalidZip)?; + if archive.len() > MAX_ENTRIES { + return Err(PackageArchiveError::EntryLimit); + } + let raw_integrity = + read_zip_metadata(&mut archive, "integrity.json", MAX_METADATA_BYTES as usize)?; + let signature = read_zip_metadata(&mut archive, "signature.ed25519", 64)?; + if let Some(publisher_key) = publisher_key { + verify_integrity_signature(publisher_key, &raw_integrity, &signature)?; + } + let integrity = parse_integrity_json(&raw_integrity)?; + + let mut expected_files = integrity.files.0.keys().cloned().collect::>(); + let mut metadata_files = BTreeSet::new(); + for name in ["integrity.json", "signature.ed25519"] { + expected_files.insert(name.to_owned()); + metadata_files.insert(name.to_owned()); + } + let target_files = integrity.files.0.keys().cloned().collect::>(); + extract_selected_target( + archive_path, + staging_dir, + &expected_files, + &metadata_files, + &target_files, + )?; + if let Some(publisher_key) = publisher_key { + verify_package_directory(staging_dir, publisher_key)?; + } + Ok(integrity) +} + +fn read_zip_metadata( + archive: &mut ZipArchive, + name: &str, + limit: usize, +) -> Result, PackageArchiveError> { + let entry = archive + .by_name(name) + .map_err(PackageArchiveError::InvalidZip)?; + if entry.size() > limit as u64 { + return Err(PackageArchiveError::MetadataLimit); + } + let mut bytes = Vec::with_capacity(entry.size() as usize); + entry.take(limit as u64 + 1).read_to_end(&mut bytes)?; + if bytes.len() > limit { + return Err(PackageArchiveError::MetadataLimit); + } + Ok(bytes) +} + +fn verify_payload_directory_with_metadata( + root: &Path, + declared: &BTreeMap, +) -> Result<(), IntegrityError> { + let mut payload_files = BTreeMap::new(); + for (path, digest) in declared { + payload_files.insert(path.clone(), digest.clone()); + } + let canonical_root = fs::canonicalize(root).map_err(|_| IntegrityError::PayloadSetMismatch)?; + let mut actual = BTreeSet::new(); + collect_payload_files(&canonical_root, &canonical_root, &mut actual)?; + actual.remove("integrity.json"); + actual.remove("signature.ed25519"); + if actual.len() != declared.len() || actual.iter().ne(declared.keys()) { + return Err(IntegrityError::PayloadSetMismatch); + } + for (relative, expected) in &payload_files { + if validated_relative_path(relative).is_err() + || relative.ends_with('/') + || relative.ends_with('\\') + || expected.len() != 64 + || !expected + .bytes() + .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)) + { + return Err(IntegrityError::InvalidMetadata); + } + let path = canonical_root.join(relative); + let metadata = + fs::symlink_metadata(&path).map_err(|_| IntegrityError::PayloadSetMismatch)?; + if metadata.file_type().is_symlink() || !metadata.is_file() { + return Err(IntegrityError::PayloadSetMismatch); + } + let mut file = File::open(path).map_err(|_| IntegrityError::PayloadSetMismatch)?; + let mut hasher = sha2::Sha256::new(); + let mut buffer = [0u8; 64 * 1024]; + loop { + let read = file + .read(&mut buffer) + .map_err(|_| IntegrityError::PayloadSetMismatch)?; + if read == 0 { + break; + } + hasher.update(&buffer[..read]); + } + if format!("{:x}", hasher.finalize()) != *expected { + return Err(IntegrityError::HashMismatch); + } + } + Ok(()) +} + +fn collect_payload_files( + root: &Path, + current: &Path, + files: &mut BTreeSet, +) -> Result<(), IntegrityError> { + for entry in fs::read_dir(current).map_err(|_| IntegrityError::PayloadSetMismatch)? { + let entry = entry.map_err(|_| IntegrityError::PayloadSetMismatch)?; + let path = entry.path(); + let metadata = + fs::symlink_metadata(&path).map_err(|_| IntegrityError::PayloadSetMismatch)?; + if metadata.file_type().is_symlink() { + return Err(IntegrityError::PayloadSetMismatch); + } + if metadata.is_dir() { + collect_payload_files(root, &path, files)?; + } else if metadata.is_file() { + let canonical = + fs::canonicalize(&path).map_err(|_| IntegrityError::PayloadSetMismatch)?; + if !canonical.starts_with(root) { + return Err(IntegrityError::PayloadSetMismatch); + } + let relative = canonical + .strip_prefix(root) + .map_err(|_| IntegrityError::PayloadSetMismatch)? + .to_string_lossy() + .replace('\\', "/"); + if !files.insert(relative) { + return Err(IntegrityError::PayloadSetMismatch); + } + } else { + return Err(IntegrityError::PayloadSetMismatch); + } + } + Ok(()) +} + +/// Verify Ed25519 over the fixed domain prefix plus raw integrity JSON bytes, +/// without parsing or re-serializing the signed JSON. +pub fn verify_integrity_signature( + public_key: &[u8], + raw_integrity_json: &[u8], + signature: &[u8], +) -> Result<(), IntegrityError> { + if public_key.len() != 32 || signature.len() != 64 { + return Err(IntegrityError::InvalidKeyOrSignature); + } + let mut signed = Vec::with_capacity(SIGNATURE_DOMAIN_PREFIX.len() + raw_integrity_json.len()); + signed.extend_from_slice(SIGNATURE_DOMAIN_PREFIX); + signed.extend_from_slice(raw_integrity_json); + ring::signature::UnparsedPublicKey::new(&ring::signature::ED25519, public_key) + .verify(&signed, signature) + .map_err(|_| IntegrityError::InvalidSignature) +} + +#[derive(Debug, Error)] +pub enum PackageArchiveError { + #[error("package archive exceeds the compressed size limit")] + CompressedLimit, + #[error("package archive has too many entries")] + EntryLimit, + #[error("package archive expands beyond the size limit")] + ExpandedLimit, + #[error("package metadata exceeds the size limit")] + MetadataLimit, + #[error("package archive contains an invalid path")] + InvalidPath, + #[error("package archive contains duplicate or case-colliding paths")] + PathCollision, + #[error("package archive contains a link or special file")] + SpecialFile, + #[error("package archive contains an unlisted payload")] + UnlistedPayload, + #[error("selected target payload is missing")] + MissingTargetPayload, + #[error("staging directory is not empty or is unsafe")] + InvalidStagingDirectory, + #[error("invalid ZIP package")] + InvalidZip(#[source] zip::result::ZipError), + #[error("package signature or integrity manifest is invalid")] + Integrity(#[from] IntegrityError), + #[error("failed to read or write package staging files")] + Io(#[from] io::Error), +} + +/// Extract one selected target into a newly-created, empty staging directory. +/// +/// `expected_files` is the validated package payload allowlist after selecting +/// the current target. `target_files` must contain at least one executable or +/// other target-specific payload and is checked independently so an archive +/// for a different architecture cannot be staged by accident. +pub fn extract_selected_target( + archive_path: &Path, + staging_dir: &Path, + expected_files: &BTreeSet, + metadata_files: &BTreeSet, + target_files: &BTreeSet, +) -> Result<(), PackageArchiveError> { + if expected_files.is_empty() + || target_files.is_empty() + || !target_files.is_subset(expected_files) + { + return Err(PackageArchiveError::MissingTargetPayload); + } + let file = File::open(archive_path)?; + if file.metadata()?.len() > MAX_COMPRESSED_BYTES { + return Err(PackageArchiveError::CompressedLimit); + } + let central_attributes = read_central_attributes(archive_path)?; + let archive = ZipArchive::new(file).map_err(PackageArchiveError::InvalidZip)?; + match fs::symlink_metadata(staging_dir) { + Ok(_) => return Err(PackageArchiveError::InvalidStagingDirectory), + Err(error) if error.kind() == io::ErrorKind::NotFound => {} + Err(error) => return Err(error.into()), + } + fs::create_dir(staging_dir)?; + if let Err(error) = restrict_directory(staging_dir) { + let _ = fs::remove_dir_all(staging_dir); + return Err(error.into()); + } + + let result = extract_archive( + archive, + ¢ral_attributes, + staging_dir, + expected_files, + metadata_files, + target_files, + ); + if result.is_err() { + let _ = fs::remove_dir_all(staging_dir); + } + result +} + +fn extract_archive( + mut archive: ZipArchive, + central_attributes: &[(u8, u32)], + staging_dir: &Path, + expected_files: &BTreeSet, + metadata_files: &BTreeSet, + target_files: &BTreeSet, +) -> Result<(), PackageArchiveError> { + if expected_files.is_empty() + || target_files.is_empty() + || !target_files.is_subset(expected_files) + { + return Err(PackageArchiveError::MissingTargetPayload); + } + + let staging_root = fs::canonicalize(staging_dir)?; + let mut seen = BTreeMap::::new(); + let mut found = BTreeSet::new(); + let mut expanded_total = 0u64; + let mut metadata_total = 0u64; + + if archive.len() > MAX_ENTRIES { + return Err(PackageArchiveError::EntryLimit); + } + if central_attributes.len() != archive.len() { + return Err(PackageArchiveError::InvalidStagingDirectory); + } + for (index, &(creator_system, external_attributes)) in central_attributes.iter().enumerate() { + let mut entry = archive + .by_index(index) + .map_err(PackageArchiveError::InvalidZip)?; + let raw_name = entry.name().to_owned(); + let (relative, is_directory) = validated_relative_path(&raw_name)?; + let normalized = relative.to_string_lossy().replace('\\', "/"); + let folded = normalized.to_lowercase(); + if let Some(previous) = seen.insert(folded, normalized.clone()) { + if previous != normalized { + return Err(PackageArchiveError::PathCollision); + } + return Err(PackageArchiveError::PathCollision); + } + + if entry.is_symlink() + || has_special_unix_type(entry.unix_mode(), is_directory) + || (creator_system == 0 && external_attributes as u16 & 0x0440 != 0) + { + return Err(PackageArchiveError::SpecialFile); + } + if is_directory { + if !expected_files + .iter() + .any(|p| p.starts_with(&format!("{normalized}/"))) + { + return Err(PackageArchiveError::UnlistedPayload); + } + let destination = staging_root.join(&relative); + ensure_contained(&staging_root, &destination)?; + fs::create_dir_all(destination)?; + continue; + } + + if !expected_files.contains(&normalized) { + return Err(PackageArchiveError::UnlistedPayload); + } + found.insert(normalized.clone()); + expanded_total = expanded_total + .checked_add(entry.size()) + .ok_or(PackageArchiveError::ExpandedLimit)?; + if expanded_total > MAX_EXPANDED_BYTES { + return Err(PackageArchiveError::ExpandedLimit); + } + if metadata_files.contains(&normalized) { + metadata_total = metadata_total + .checked_add(entry.size()) + .ok_or(PackageArchiveError::MetadataLimit)?; + if metadata_total > MAX_METADATA_BYTES { + return Err(PackageArchiveError::MetadataLimit); + } + } + + let destination = staging_root.join(&relative); + ensure_contained(&staging_root, &destination)?; + let parent = destination + .parent() + .ok_or(PackageArchiveError::InvalidPath)?; + fs::create_dir_all(parent)?; + let mut output = OpenOptions::new() + .write(true) + .create_new(true) + .open(&destination)?; + let declared_size = entry.size(); + let copied = { + let mut bounded_entry = (&mut entry).take(declared_size); + io::copy(&mut bounded_entry, &mut output)? + }; + let mut extra = [0u8; 1]; + if copied != declared_size || entry.read(&mut extra)? != 0 { + return Err(PackageArchiveError::InvalidZip(zip::result::ZipError::Io( + io::Error::new( + io::ErrorKind::InvalidData, + "ZIP entry length does not match its metadata", + ), + ))); + } + output.sync_all()?; + } + + if !target_files.is_subset(&found) || !expected_files.is_subset(&found) { + return Err(PackageArchiveError::MissingTargetPayload); + } + Ok(()) +} + +/// Read central-directory creator-system and external attributes. The ZIP crate +/// normalizes DOS attributes, so inspect the raw record to reject Windows +/// device and reparse-point flags before extraction. +fn read_central_attributes(path: &Path) -> Result, PackageArchiveError> { + let mut file = File::open(path)?; + let length = file.metadata()?.len(); + let tail_len = length.min(65_557) as usize; + let mut tail = vec![0; tail_len]; + file.seek(io::SeekFrom::End(-(tail_len as i64)))?; + file.read_exact(&mut tail)?; + let eocd = tail + .windows(4) + .rposition(|window| window == b"PK\x05\x06") + .ok_or(PackageArchiveError::InvalidStagingDirectory)?; + if eocd + 22 > tail.len() { + return Err(PackageArchiveError::InvalidStagingDirectory); + } + let disk = u16::from_le_bytes([tail[eocd + 4], tail[eocd + 5]]); + let central_disk = u16::from_le_bytes([tail[eocd + 6], tail[eocd + 7]]); + let entries = u16::from_le_bytes([tail[eocd + 10], tail[eocd + 11]]); + let central_size = u32::from_le_bytes(tail[eocd + 12..eocd + 16].try_into().unwrap()); + let central_offset = u32::from_le_bytes(tail[eocd + 16..eocd + 20].try_into().unwrap()); + if disk != 0 + || central_disk != 0 + || entries == u16::MAX + || central_size == u32::MAX + || central_offset == u32::MAX + || entries as usize > MAX_ENTRIES + || central_offset as u64 + central_size as u64 > length + { + return Err(PackageArchiveError::InvalidStagingDirectory); + } + + file.seek(io::SeekFrom::Start(central_offset as u64))?; + let mut attributes = Vec::with_capacity(entries as usize); + for _ in 0..entries { + let mut fixed = [0u8; 46]; + file.read_exact(&mut fixed)?; + if &fixed[..4] != b"PK\x01\x02" { + return Err(PackageArchiveError::InvalidStagingDirectory); + } + let name_len = u16::from_le_bytes([fixed[28], fixed[29]]) as u64; + let extra_len = u16::from_le_bytes([fixed[30], fixed[31]]) as u64; + let comment_len = u16::from_le_bytes([fixed[32], fixed[33]]) as u64; + let skip = name_len + extra_len + comment_len; + if file.stream_position()?.saturating_add(skip) > length { + return Err(PackageArchiveError::InvalidStagingDirectory); + } + file.seek(io::SeekFrom::Current(skip as i64))?; + attributes.push(( + fixed[5], + u32::from_le_bytes(fixed[38..42].try_into().unwrap()), + )); + } + Ok(attributes) +} + +fn validated_relative_path(name: &str) -> Result<(PathBuf, bool), PackageArchiveError> { + if name.is_empty() || name.contains('\0') || name.starts_with('/') || name.starts_with('\\') { + return Err(PackageArchiveError::InvalidPath); + } + let directory = name.ends_with('/') || name.ends_with('\\'); + let normalized = name.replace('\\', "/"); + let path_text = if directory { + normalized.strip_suffix('/').unwrap_or(&normalized) + } else { + normalized.as_str() + }; + if normalized.starts_with("//") + || normalized.as_bytes().get(1) == Some(&b':') + || path_text.split('/').any(str::is_empty) + { + return Err(PackageArchiveError::InvalidPath); + } + let path = Path::new(path_text); + if path.components().any(|component| { + !matches!(component, Component::Normal(_)) + || component.as_os_str().to_string_lossy().contains(':') + }) { + return Err(PackageArchiveError::InvalidPath); + } + Ok((path.to_path_buf(), directory)) +} + +fn ensure_contained(root: &Path, destination: &Path) -> Result<(), PackageArchiveError> { + if !destination.starts_with(root) { + return Err(PackageArchiveError::InvalidPath); + } + Ok(()) +} + +#[cfg(unix)] +fn restrict_directory(path: &Path) -> io::Result<()> { + use std::os::unix::fs::PermissionsExt; + fs::set_permissions(path, fs::Permissions::from_mode(0o700)) +} + +#[cfg(not(unix))] +fn restrict_directory(_path: &Path) -> io::Result<()> { + Ok(()) +} + +fn has_special_unix_type(mode: Option, is_directory: bool) -> bool { + let Some(mode) = mode else { return false }; + let kind = mode & 0o170000; + if kind == 0 { + return false; + } + if is_directory { + kind != 0o040000 + } else { + kind != 0o100000 + } +} + +#[cfg(test)] +mod tests { + use std::{collections::BTreeSet, fs::File, io::Write}; + + use ring::signature::KeyPair; + use tempfile::tempdir; + use zip::{ZipWriter, write::SimpleFileOptions}; + + use super::*; + + fn archive(entries: &[(&str, &[u8])], symlink: Option<&str>) -> (tempfile::TempDir, PathBuf) { + let temp = tempdir().unwrap(); + let path = temp.path().join("package.zip"); + let mut zip = ZipWriter::new(File::create(&path).unwrap()); + for (name, contents) in entries { + zip.start_file(*name, SimpleFileOptions::default()).unwrap(); + zip.write_all(contents).unwrap(); + } + if let Some(name) = symlink { + let opts = SimpleFileOptions::default().unix_permissions(0o120777); + zip.start_file(name, opts).unwrap(); + zip.write_all(b"../../outside").unwrap(); + } + zip.finish().unwrap(); + if let Some(name) = symlink { + // The high-level writer masks the POSIX type bits. Encode a real + // Unix symlink marker in the central-directory fixture metadata. + let mut bytes = fs::read(&path).unwrap(); + for offset in 0..bytes.len().saturating_sub(46) { + if &bytes[offset..offset + 4] == b"PK\x01\x02" { + let name_len = + u16::from_le_bytes([bytes[offset + 28], bytes[offset + 29]]) as usize; + let entry_name = &bytes[offset + 46..offset + 46 + name_len]; + if entry_name == name.as_bytes() { + bytes[offset + 4] = 20; + bytes[offset + 5] = 3; + bytes[offset + 38..offset + 42] + .copy_from_slice(&((0o120777u32) << 16).to_le_bytes()); + } + } + } + fs::write(&path, bytes).unwrap(); + } + (temp, path) + } + + fn set(values: &[&str]) -> BTreeSet { + values.iter().map(|s| s.to_string()).collect() + } + + fn signed_archive(temp: &Path, key: &ring::signature::Ed25519KeyPair, extra: bool) -> PathBuf { + let payload = b"signed package payload"; + let files = [( + "bin/plugin".to_owned(), + format!("{:x}", sha2::Sha256::digest(payload)), + )] + .into_iter() + .collect::>(); + let integrity = + serde_json::to_vec(&serde_json::json!({"schema": 1, "files": files})).unwrap(); + let mut signed = SIGNATURE_DOMAIN_PREFIX.to_vec(); + signed.extend_from_slice(&integrity); + let signature = key.sign(&signed); + let path = temp.join("signed-package.zip"); + let mut zip = ZipWriter::new(File::create(&path).unwrap()); + for (name, contents) in [ + ("integrity.json", integrity.as_slice()), + ("signature.ed25519", signature.as_ref()), + ("bin/plugin", payload.as_slice()), + ] { + zip.start_file(name, SimpleFileOptions::default()).unwrap(); + zip.write_all(contents).unwrap(); + } + if extra { + zip.start_file("unlisted", SimpleFileOptions::default()) + .unwrap(); + zip.write_all(b"unexpected").unwrap(); + } + zip.finish().unwrap(); + path + } + + #[test] + fn update_zip_uses_signed_allowlist_and_bounded_extraction() { + let temp = tempdir().unwrap(); + let key = ring::signature::Ed25519KeyPair::from_seed_unchecked(&[19; 32]).unwrap(); + let public_key = key.public_key().as_ref(); + let archive = signed_archive(temp.path(), &key, false); + let staging = temp.path().join("staging"); + stage_package_archive(&archive, &staging, public_key).unwrap(); + assert_eq!( + fs::read(staging.join("bin/plugin")).unwrap(), + b"signed package payload" + ); + assert!(staging.join("integrity.json").is_file()); + + let feed_staging = temp.path().join("feed-staging"); + stage_package_archive_from_verified_feed(&archive, &feed_staging).unwrap(); + verify_package_directory(&feed_staging, public_key).unwrap(); + assert!(verify_package_directory(&feed_staging, &[0; 32]).is_err()); + + let bad_archive = signed_archive(temp.path(), &key, true); + let bad_staging = temp.path().join("bad-staging"); + assert!(stage_package_archive(&bad_archive, &bad_staging, public_key).is_err()); + assert!( + !bad_staging.exists(), + "failed extraction removes its staging tree" + ); + } + + #[test] + fn extracts_only_allowlisted_selected_target_files() { + let (temp, zip) = archive( + &[("plugin.json", b"{}"), ("bin/linux-x64/plugin", b"bin")], + None, + ); + let staging = temp.path().join("stage"); + extract_selected_target( + &zip, + &staging, + &set(&["plugin.json", "bin/linux-x64/plugin"]), + &set(&["plugin.json"]), + &set(&["bin/linux-x64/plugin"]), + ) + .unwrap(); + assert_eq!(fs::read(staging.join("plugin.json")).unwrap(), b"{}"); + } + + #[test] + fn rejects_traversal_links_unlisted_files_and_case_collisions() { + for (entries, link, expected, target) in [ + ( + vec![("../escape", b"x".as_slice())], + None, + set(&["../escape"]), + set(&["../escape"]), + ), + ( + vec![("plugin.json", b"{}".as_slice())], + Some("link"), + set(&["plugin.json", "link"]), + set(&["plugin.json"]), + ), + ( + vec![ + ("plugin.json", b"{}".as_slice()), + ("extra", b"x".as_slice()), + ], + None, + set(&["plugin.json"]), + set(&["plugin.json"]), + ), + ( + vec![("Foo", b"x".as_slice()), ("foo", b"y".as_slice())], + None, + set(&["Foo", "foo"]), + set(&["Foo"]), + ), + ] { + let (temp, zip) = archive(&entries, link); + let staging = temp.path().join("stage"); + assert!( + extract_selected_target(&zip, &staging, &expected, &BTreeSet::new(), &target,) + .is_err() + ); + assert!(!temp.path().join("escape").exists()); + } + } + + #[test] + fn rejects_missing_target_and_nonempty_staging_directory() { + let (temp, zip) = archive(&[("plugin.json", b"{}")], None); + let staging = temp.path().join("stage"); + assert!(matches!( + extract_selected_target( + &zip, + &staging, + &set(&["plugin.json", "bin/windows-x64/plugin.exe"]), + &BTreeSet::new(), + &set(&["bin/windows-x64/plugin.exe"]), + ), + Err(PackageArchiveError::MissingTargetPayload) + )); + assert!(!staging.exists()); + fs::create_dir(&staging).unwrap(); + File::create(staging.join("existing")).unwrap(); + assert!(matches!( + extract_selected_target( + &zip, + &staging, + &set(&["plugin.json"]), + &BTreeSet::new(), + &set(&["plugin.json"]), + ), + Err(PackageArchiveError::InvalidStagingDirectory) + )); + } + + #[test] + fn rejects_windows_reparse_point_attributes() { + let (temp, zip) = archive(&[("plugin.json", b"{}")], None); + let mut bytes = fs::read(&zip).unwrap(); + for offset in 0..bytes.len().saturating_sub(46) { + if &bytes[offset..offset + 4] == b"PK\x01\x02" { + let name_len = + u16::from_le_bytes([bytes[offset + 28], bytes[offset + 29]]) as usize; + let name = &bytes[offset + 46..offset + 46 + name_len]; + if name == b"plugin.json" { + bytes[offset + 4] = 20; + bytes[offset + 5] = 0; // DOS creator system. + bytes[offset + 38..offset + 42].copy_from_slice(&0x0400u32.to_le_bytes()); + // REPARSE_POINT. + } + } + } + fs::write(&zip, bytes).unwrap(); + + assert!(matches!( + extract_selected_target( + &zip, + &temp.path().join("stage"), + &set(&["plugin.json"]), + &BTreeSet::new(), + &set(&["plugin.json"]), + ), + Err(PackageArchiveError::SpecialFile) + )); + } + + #[test] + fn verifies_exact_payload_hash_sets_and_rejects_changed_bytes() { + let bytes = b"license notice and binary".to_vec(); + let digest = format!("{:x}", sha2::Sha256::digest(&bytes)); + let declared = BTreeMap::from([("licenses/LICENSE".to_owned(), digest)]); + let payloads = BTreeMap::from([("licenses/LICENSE".to_owned(), bytes.clone())]); + verify_payload_hashes(&declared, &payloads).unwrap(); + + assert_eq!( + verify_payload_hashes( + &declared, + &BTreeMap::from([("licenses/LICENSE".to_owned(), b"changed".to_vec())]), + ), + Err(IntegrityError::HashMismatch) + ); + assert_eq!( + verify_payload_hashes( + &declared, + &BTreeMap::from([ + ("licenses/LICENSE".to_owned(), bytes), + ("extra".to_owned(), b"unlisted".to_vec()), + ]), + ), + Err(IntegrityError::PayloadSetMismatch) + ); + assert_eq!( + verify_payload_hashes( + &BTreeMap::from([("licenses/LICENSE".to_owned(), "A".repeat(64))]), + &payloads, + ), + Err(IntegrityError::InvalidDigest) + ); + } + + #[test] + fn integrity_json_rejects_duplicate_paths_unsafe_names_and_bad_digests() { + let digest = "a".repeat(64); + let valid = format!(r#"{{"schema":1,"files":{{"plugin.json":"{digest}"}}}}"#); + let parsed = parse_integrity_json(valid.as_bytes()).unwrap(); + assert_eq!(parsed.schema, 1); + assert_eq!(parsed.files.0.len(), 1); + + for malformed in [ + format!(r#"{{"schema":1,"schema":1,"files":{{"plugin.json":"{digest}"}}}}"#), + format!( + r#"{{"schema":1,"files":{{"plugin.json":"{digest}","plugin.json":"{digest}"}}}}"# + ), + format!(r#"{{"schema":1,"files":{{"../escape":"{digest}"}}}}"#), + r#"{"schema":1,"files":{"plugin.json":"ABC"}}"#.into(), + ] { + assert_eq!( + parse_integrity_json(malformed.as_bytes()), + Err(IntegrityError::InvalidMetadata) + ); + } + } + + #[test] + fn rechecks_all_payload_files_before_launch_and_rejects_extras_or_links() { + let temp = tempdir().unwrap(); + let root = temp.path().join("version"); + fs::create_dir_all(root.join("bin")).unwrap(); + fs::write(root.join("plugin.json"), b"manifest").unwrap(); + fs::write(root.join("bin/plugin"), b"executable").unwrap(); + let declared = BTreeMap::from([ + ( + "plugin.json".to_owned(), + format!("{:x}", sha2::Sha256::digest(b"manifest")), + ), + ( + "bin/plugin".to_owned(), + format!("{:x}", sha2::Sha256::digest(b"executable")), + ), + ]); + verify_payload_files(&root, &declared).unwrap(); + + fs::write(root.join("plugin.json"), b"changed manifest").unwrap(); + assert_eq!( + verify_payload_files(&root, &declared), + Err(IntegrityError::HashMismatch) + ); + fs::write(root.join("plugin.json"), b"manifest").unwrap(); + fs::write(root.join("bin/plugin"), b"modified").unwrap(); + assert_eq!( + verify_payload_files(&root, &declared), + Err(IntegrityError::HashMismatch) + ); + fs::write(root.join("bin/plugin"), b"executable").unwrap(); + fs::write(root.join("extra"), b"not signed").unwrap(); + assert_eq!( + verify_payload_files(&root, &declared), + Err(IntegrityError::PayloadSetMismatch) + ); + + fs::remove_file(root.join("extra")).unwrap(); + #[cfg(unix)] + { + std::os::unix::fs::symlink(root.join("plugin.json"), root.join("link")).unwrap(); + assert_eq!( + verify_payload_files(&root, &declared), + Err(IntegrityError::PayloadSetMismatch) + ); + } + } + + #[test] + fn verifies_domain_separated_ed25519_signature_over_exact_bytes() { + use ring::signature::KeyPair; + + let key = ring::signature::Ed25519KeyPair::from_seed_unchecked(&[7u8; 32]).unwrap(); + let raw = br#"{"schema":1,"files":{}}"#; + let mut signed = SIGNATURE_DOMAIN_PREFIX.to_vec(); + signed.extend_from_slice(raw); + let signature = key.sign(&signed); + verify_integrity_signature(key.public_key().as_ref(), raw, signature.as_ref()).unwrap(); + let unsigned_domain_signature = key.sign(raw); + assert_eq!( + verify_integrity_signature( + key.public_key().as_ref(), + raw, + unsigned_domain_signature.as_ref(), + ), + Err(IntegrityError::InvalidSignature) + ); + assert_eq!( + verify_integrity_signature( + key.public_key().as_ref(), + b"{\"schema\":1,\"files\":{}} ", + signature.as_ref(), + ), + Err(IntegrityError::InvalidSignature) + ); + assert_eq!( + verify_integrity_signature(&[0; 31], raw, signature.as_ref()), + Err(IntegrityError::InvalidKeyOrSignature) + ); + } + + #[test] + fn validates_signed_package_and_rechecks_notices_and_payload_files() { + use ring::signature::KeyPair; + let temp = tempdir().unwrap(); + let root = temp.path(); + fs::create_dir_all(root.join("licenses")).unwrap(); + fs::write(root.join("plugin.json"), b"manifest").unwrap(); + fs::write(root.join("licenses/NOTICE"), b"notice").unwrap(); + fs::write(root.join("bin"), b"executable").unwrap(); + let files = BTreeMap::from([ + ( + "plugin.json".to_owned(), + format!("{:x}", sha2::Sha256::digest(b"manifest")), + ), + ( + "licenses/NOTICE".to_owned(), + format!("{:x}", sha2::Sha256::digest(b"notice")), + ), + ( + "bin".to_owned(), + format!("{:x}", sha2::Sha256::digest(b"executable")), + ), + ]); + let raw = serde_json::to_vec(&serde_json::json!({"schema": 1, "files": files})).unwrap(); + let key = ring::signature::Ed25519KeyPair::from_seed_unchecked(&[9u8; 32]).unwrap(); + let mut signed = SIGNATURE_DOMAIN_PREFIX.to_vec(); + signed.extend_from_slice(&raw); + fs::write(root.join("integrity.json"), &raw).unwrap(); + fs::write(root.join("signature.ed25519"), key.sign(&signed).as_ref()).unwrap(); + + verify_package_directory(root, key.public_key().as_ref()).unwrap(); + verify_installed_package(root, key.public_key().as_ref()).unwrap(); + fs::write(root.join("licenses/NOTICE"), b"changed notice").unwrap(); + assert_eq!( + verify_installed_package(root, key.public_key().as_ref()), + Err(IntegrityError::HashMismatch) + ); + assert!(matches!( + verify_package_directory(root, &[0; 31]), + Err(IntegrityError::InvalidKeyOrSignature) + )); + } +} diff --git a/crates/platform/src/plugin_persistence.rs b/crates/platform/src/plugin_persistence.rs new file mode 100644 index 000000000..1d90dcf1e --- /dev/null +++ b/crates/platform/src/plugin_persistence.rs @@ -0,0 +1,676 @@ +//! Owner-scoped durable plugin records, separate from the plugin's private KV store. +//! +//! This layer accepts a host-resolved namespace and never accepts a path, plugin id from an RPC, +//! or a cross-owner selector. Callers must open and use it on a blocking worker. The application +//! host remains responsible for authenticating the namespace, checking `storage.persist` and +//! retention consent, and deciding whether archived records may be explicitly reused. + +use std::fs; +use std::path::{Path, PathBuf}; + +use rusqlite::{Connection, OptionalExtension, TransactionBehavior, params}; +use sha2::{Digest, Sha256}; + +const FILE_NAME: &str = "plugin-persistence.sqlite3"; +const SCHEMA_VERSION: i64 = 1; +pub const MAX_CATEGORY_BYTES: usize = 128; +pub const MAX_LOGICAL_KEY_BYTES: usize = 256; +pub const MAX_RECORD_BYTES: usize = 1024 * 1024; +pub const MAX_PAGE_SIZE: u32 = 200; +pub const MAX_OWNER_LOGICAL_BYTES: u64 = 128 * 1024 * 1024; +pub const MAX_CATEGORY_LOGICAL_BYTES: u64 = 64 * 1024 * 1024; +pub const MAX_RETENTION_AGE_SECONDS: u64 = 365 * 24 * 60 * 60; +const RECORD_OVERHEAD_BYTES: u64 = 128; + +/// Namespace resolved by the host from the authenticated plugin and account profile. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct OwnerNamespace { + pub publisher_id: String, + pub plugin_id: String, + pub profile_id: String, +} + +impl OwnerNamespace { + fn validate(&self) -> Result<(), PersistenceError> { + for value in [&self.publisher_id, &self.plugin_id, &self.profile_id] { + if value.is_empty() || value.len() > 256 || value.chars().any(char::is_control) { + return Err(PersistenceError::InvalidNamespace); + } + } + Ok(()) + } +} + +/// Provenance copied from the authenticated producer package by the host. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct RecordProvenance { + pub source_plugin_id: String, + pub source_publisher_id: String, + pub source_version: String, + pub package_id: String, +} + +impl RecordProvenance { + fn validate(&self) -> Result<(), PersistenceError> { + for value in [ + &self.source_plugin_id, + &self.source_publisher_id, + &self.source_version, + &self.package_id, + ] { + if value.is_empty() || value.len() > 256 || value.chars().any(char::is_control) { + return Err(PersistenceError::InvalidProvenance); + } + } + Ok(()) + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct PersistedRecord { + pub category: String, + pub logical_key: String, + pub value: Vec, + pub revision: u64, + pub provenance: RecordProvenance, + pub created_at: i64, + pub updated_at: i64, + pub expires_at: Option, + pub user_protected: bool, + /// Archived records are invisible to ordinary plugin reads and survive uninstall retention. + pub archived: bool, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PutOutcome { + Stored { + revision: u64, + logical_bytes: u64, + }, + Conflict { + current_revision: u64, + }, + OverQuota { + category_bytes: u64, + owner_bytes: u64, + }, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct CategoryUsage { + pub category: String, + pub logical_bytes: u64, + pub records: u64, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Usage { + pub categories: Vec, + pub logical_bytes: u64, + /// SQLite page allocation for the complete namespace database. This is an estimate for + /// plugin persistence because SQLite metadata and free pages are shared across categories. + pub physical_bytes_estimate: u64, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct RetentionPolicy { + pub category: String, + pub max_age_seconds: Option, + pub max_logical_bytes: Option, +} + +#[derive(Debug, thiserror::Error)] +pub enum PersistenceError { + #[error("invalid plugin persistence namespace")] + InvalidNamespace, + #[error("invalid plugin persistence provenance")] + InvalidProvenance, + #[error("invalid plugin persistence selector or payload")] + InvalidInput, + #[error("plugin persistence record is protected by the user")] + Protected, + #[error("archived plugin persistence requires an explicit host reuse decision")] + ArchivedRecordExists, + #[error("plugin persistence database could not be opened")] + Open(#[source] std::io::Error), + #[error("plugin persistence database operation failed")] + Database(#[from] rusqlite::Error), + #[error("plugin persistence database was written by a newer host")] + NewerVersion, +} + +/// One host-attributed record write with optimistic revision control. +pub struct RecordWrite<'a> { + pub category: &'a str, + pub logical_key: &'a str, + pub value: &'a [u8], + pub provenance: &'a RecordProvenance, + pub expected_revision: u64, + pub expires_at: Option, + pub now: i64, +} + +/// One logical owner/profile persistence database. +pub struct PluginPersistence { + conn: Connection, +} + +impl PluginPersistence { + /// Opens the persistence file below `root` using only the host-authenticated namespace. + /// No path is returned to API callers. This function performs blocking filesystem work. + pub fn open(root: &Path, owner: &OwnerNamespace) -> Result { + owner.validate()?; + let dir = owner_dir(root, owner); + fs::create_dir_all(&dir).map_err(PersistenceError::Open)?; + let conn = Connection::open(dir.join(FILE_NAME))?; + conn.busy_timeout(std::time::Duration::from_secs(5))?; + let version: i64 = conn.query_row("PRAGMA user_version", [], |row| row.get(0))?; + if version > SCHEMA_VERSION { + return Err(PersistenceError::NewerVersion); + } + if version < 1 { + conn.execute_batch( + "BEGIN IMMEDIATE; + CREATE TABLE IF NOT EXISTS records ( + category TEXT NOT NULL, + logical_key TEXT NOT NULL, + value BLOB NOT NULL, + revision INTEGER NOT NULL CHECK (revision > 0), + source_plugin_id TEXT NOT NULL, + source_publisher_id TEXT NOT NULL, + source_version TEXT NOT NULL, + package_id TEXT NOT NULL, + created_at INTEGER NOT NULL, + updated_at INTEGER NOT NULL, + expires_at INTEGER, + user_protected INTEGER NOT NULL DEFAULT 0 CHECK (user_protected IN (0, 1)), + archived INTEGER NOT NULL DEFAULT 0 CHECK (archived IN (0, 1)), + PRIMARY KEY (category, logical_key) + ) STRICT; + CREATE INDEX IF NOT EXISTS records_expiry ON records(category, expires_at); + CREATE TABLE IF NOT EXISTS retention ( + category TEXT PRIMARY KEY, + max_age_seconds INTEGER, + max_logical_bytes INTEGER, + updated_at INTEGER NOT NULL + ) STRICT; + PRAGMA user_version = 1; + COMMIT;", + )?; + } + Ok(Self { conn }) + } + + /// Reads one active, unexpired record. Archived and expired values are not returned. + pub fn get( + &self, + category: &str, + logical_key: &str, + now: i64, + ) -> Result, PersistenceError> { + validate_selector(category, logical_key)?; + self.conn + .query_row( + "SELECT category, logical_key, value, revision, source_plugin_id, + source_publisher_id, source_version, package_id, created_at, + updated_at, expires_at, user_protected, archived + FROM records WHERE category=?1 AND logical_key=?2 AND archived=0 + AND (expires_at IS NULL OR expires_at>?3)", + params![category, logical_key, now], + record_from, + ) + .optional() + .map_err(Into::into) + } + + /// Stores one host-attributed record with optimistic revision control and bounded logical + /// quotas. A revision of zero creates; updates must present the current revision. + pub fn put(&mut self, write: RecordWrite<'_>) -> Result { + let RecordWrite { + category, + logical_key, + value, + provenance, + expected_revision, + expires_at, + now, + } = write; + validate_selector(category, logical_key)?; + provenance.validate()?; + if value.len() > MAX_RECORD_BYTES || expires_at.is_some_and(|expiry| expiry <= now) { + return Err(PersistenceError::InvalidInput); + } + let tx = self + .conn + .transaction_with_behavior(TransactionBehavior::Immediate)?; + tx.execute( + "DELETE FROM records WHERE archived=0 AND expires_at IS NOT NULL AND expires_at<=?1 AND user_protected=0", + [now], + )?; + let archived: bool = tx.query_row( + "SELECT EXISTS(SELECT 1 FROM records WHERE category=?1 AND logical_key=?2 AND archived=1)", + params![category, logical_key], + |row| row.get(0), + )?; + if archived { + return Err(PersistenceError::ArchivedRecordExists); + } + let existing: Option<(u64, i64, i64)> = tx + .query_row( + "SELECT revision, created_at, user_protected FROM records WHERE category=?1 AND logical_key=?2 AND archived=0", + params![category, logical_key], + |row| Ok((row.get::<_, i64>(0)? as u64, row.get(1)?, row.get(2)?)), + ) + .optional()?; + let current = existing.as_ref().map_or(0, |entry| entry.0); + if existing.as_ref().is_some_and(|entry| entry.2 != 0) { + return Err(PersistenceError::Protected); + } + if current != expected_revision { + return Ok(PutOutcome::Conflict { + current_revision: current, + }); + } + let revision = current.saturating_add(1); + let created_at = existing.map_or(now, |entry| entry.1); + let candidate_charge = record_charge(category, logical_key, value.len(), provenance); + let category_bytes = usage_bytes(&tx, Some(category), Some((category, logical_key)), now)?; + let owner_bytes = usage_bytes(&tx, None, Some((category, logical_key)), now)?; + let category_quota = tx + .query_row( + "SELECT max_logical_bytes FROM retention WHERE category=?1", + [category], + |row| row.get::<_, Option>(0), + ) + .optional()? + .flatten() + .map(|value| value.max(0) as u64) + .unwrap_or(MAX_CATEGORY_LOGICAL_BYTES) + .min(MAX_CATEGORY_LOGICAL_BYTES); + if category_bytes.saturating_add(candidate_charge) > category_quota + || owner_bytes.saturating_add(candidate_charge) > MAX_OWNER_LOGICAL_BYTES + { + return Ok(PutOutcome::OverQuota { + category_bytes, + owner_bytes, + }); + } + tx.execute( + "INSERT INTO records(category,logical_key,value,revision,source_plugin_id, + source_publisher_id,source_version,package_id,created_at,updated_at,expires_at, + user_protected,archived) + VALUES(?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11,?12,0) + ON CONFLICT(category,logical_key) DO UPDATE SET value=excluded.value, + revision=excluded.revision, source_plugin_id=excluded.source_plugin_id, + source_publisher_id=excluded.source_publisher_id, source_version=excluded.source_version, + package_id=excluded.package_id, updated_at=excluded.updated_at, + expires_at=excluded.expires_at, user_protected=excluded.user_protected, archived=0", + params![category, logical_key, value, revision as i64, provenance.source_plugin_id, + provenance.source_publisher_id, provenance.source_version, provenance.package_id, + created_at, now, expires_at, false], + )?; + tx.commit()?; + Ok(PutOutcome::Stored { + revision, + logical_bytes: category_bytes.saturating_add(candidate_charge), + }) + } + + /// Returns one logical page, ordered by key. `after_key` is an opaque host-issued cursor + /// value bound by the host to this owner and category; it is never interpreted as a path. + pub fn list( + &self, + category: &str, + after_key: Option<&str>, + page_size: u32, + now: i64, + ) -> Result, PersistenceError> { + validate_category(category)?; + if page_size == 0 || page_size > MAX_PAGE_SIZE { + return Err(PersistenceError::InvalidInput); + } + let mut statement = self.conn.prepare( + "SELECT category, logical_key, value, revision, source_plugin_id, + source_publisher_id, source_version, package_id, created_at, + updated_at, expires_at, user_protected, archived + FROM records WHERE category=?1 AND archived=0 + AND (expires_at IS NULL OR expires_at>?2) AND (?3 IS NULL OR logical_key>?3) + ORDER BY logical_key LIMIT ?4", + )?; + statement + .query_map(params![category, now, after_key, page_size], record_from)? + .collect::, _>>() + .map_err(Into::into) + } + + /// Deletes one record only when its revision matches; protected user records are retained. + pub fn delete( + &mut self, + category: &str, + logical_key: &str, + expected_revision: u64, + ) -> Result { + validate_selector(category, logical_key)?; + let tx = self + .conn + .transaction_with_behavior(TransactionBehavior::Immediate)?; + let found: Option<(u64, bool)> = tx + .query_row( + "SELECT revision,user_protected FROM records WHERE category=?1 AND logical_key=?2 AND archived=0", + params![category, logical_key], + |row| Ok((row.get::<_, i64>(0)? as u64, row.get::<_, i64>(1)? != 0)), + ) + .optional()?; + let Some((revision, protected)) = found else { + return Ok(false); + }; + if protected { + return Err(PersistenceError::Protected); + } + if revision != expected_revision { + return Ok(false); + } + tx.execute( + "DELETE FROM records WHERE category=?1 AND logical_key=?2 AND revision=?3", + params![category, logical_key, expected_revision as i64], + )?; + tx.commit()?; + Ok(true) + } + + /// Clears unprotected, active records in one category. Archived and user-protected records + /// remain inert and are reserved for explicit host administration. + pub fn clear_category(&mut self, category: &str) -> Result { + validate_category(category)?; + let tx = self + .conn + .transaction_with_behavior(TransactionBehavior::Immediate)?; + let removed = tx.execute( + "DELETE FROM records WHERE category=?1 AND archived=0 AND user_protected=0", + [category], + )? as u64; + tx.commit()?; + Ok(removed) + } + + /// Applies a host-only user protection decision. Plugin publication never controls this bit. + pub fn set_user_protected( + &mut self, + category: &str, + logical_key: &str, + protected: bool, + ) -> Result { + validate_selector(category, logical_key)?; + let changed = self.conn.execute( + "UPDATE records SET user_protected=?3 WHERE category=?1 AND logical_key=?2 AND archived=0", + params![category, logical_key, protected], + )?; + Ok(changed != 0) + } + + /// Sets a bounded category retention policy. `None` leaves that dimension uncapped up to + /// the hard host maximum; user-level UI policy and permission checks belong to the host. + pub fn set_retention_policy( + &mut self, + category: &str, + max_age_seconds: Option, + max_logical_bytes: Option, + now: i64, + ) -> Result<(), PersistenceError> { + validate_category(category)?; + if max_age_seconds.is_some_and(|age| age == 0 || age > MAX_RETENTION_AGE_SECONDS) + || max_logical_bytes + .is_some_and(|bytes| bytes == 0 || bytes > MAX_CATEGORY_LOGICAL_BYTES) + { + return Err(PersistenceError::InvalidInput); + } + self.conn.execute( + "INSERT INTO retention(category,max_age_seconds,max_logical_bytes,updated_at) + VALUES(?1,?2,?3,?4) ON CONFLICT(category) DO UPDATE SET + max_age_seconds=excluded.max_age_seconds,max_logical_bytes=excluded.max_logical_bytes, + updated_at=excluded.updated_at", + params![ + category, + max_age_seconds.map(|v| v as i64), + max_logical_bytes.map(|v| v as i64), + now + ], + )?; + Ok(()) + } + + pub fn retention_policy( + &self, + category: &str, + ) -> Result, PersistenceError> { + validate_category(category)?; + self.conn + .query_row( + "SELECT category,max_age_seconds,max_logical_bytes FROM retention WHERE category=?1", + [category], + |row| Ok(RetentionPolicy { + category: row.get(0)?, + max_age_seconds: row.get::<_, Option>(1)?.map(|v| v.max(0) as u64), + max_logical_bytes: row.get::<_, Option>(2)?.map(|v| v.max(0) as u64), + }), + ) + .optional() + .map_err(Into::into) + } + + /// Applies expiry and age/size retention atomically. It deletes only unprotected, active + /// records; archived and user-protected records are not reclaimed by owner policy. + pub fn cleanup_category(&mut self, category: &str, now: i64) -> Result { + validate_category(category)?; + let tx = self + .conn + .transaction_with_behavior(TransactionBehavior::Immediate)?; + // Include expired rows in reclaimed logical bytes, although ordinary usage reports omit + // them. This reports the logical amount removed, not SQLite pages that may remain allocated. + let before = usage_bytes(&tx, Some(category), None, i64::MIN)?; + tx.execute( + "DELETE FROM records WHERE category=?1 AND archived=0 AND user_protected=0 + AND expires_at IS NOT NULL AND expires_at<=?2", + params![category, now], + )?; + let max_age = tx + .query_row( + "SELECT max_age_seconds FROM retention WHERE category=?1", + [category], + |r| r.get::<_, Option>(0), + ) + .optional()? + .flatten(); + if let Some(age) = max_age { + tx.execute( + "DELETE FROM records WHERE category=?1 AND archived=0 AND user_protected=0 AND updated_at<=?2", + params![category, now.saturating_sub(age)], + )?; + } + let max_bytes = tx + .query_row( + "SELECT max_logical_bytes FROM retention WHERE category=?1", + [category], + |r| r.get::<_, Option>(0), + ) + .optional()? + .flatten() + .unwrap_or(MAX_CATEGORY_LOGICAL_BYTES as i64) + .max(0) as u64; + while usage_bytes(&tx, Some(category), None, now)? > max_bytes { + let victim: Option = tx.query_row( + "SELECT logical_key FROM records WHERE category=?1 AND archived=0 AND user_protected=0 + ORDER BY updated_at ASC, logical_key ASC LIMIT 1", + [category], |r| r.get(0), + ).optional()?; + let Some(victim) = victim else { break }; + tx.execute( + "DELETE FROM records WHERE category=?1 AND logical_key=?2", + params![category, victim], + )?; + } + let after = usage_bytes(&tx, Some(category), None, i64::MIN)?; + tx.commit()?; + Ok(before.saturating_sub(after)) + } + + /// Makes this owner's records inert for uninstall retention. Ordinary plugin queries exclude + /// them; a later install needs a separate host-authorized reuse flow. + pub fn archive_all(&mut self, now: i64) -> Result { + let tx = self + .conn + .transaction_with_behavior(TransactionBehavior::Immediate)?; + let count = tx.execute( + "UPDATE records SET archived=1,updated_at=?1 WHERE archived=0", + [now], + )? as u64; + tx.commit()?; + Ok(count) + } + + /// Host-side reclaim of archived records in this owner namespace only. + pub fn reclaim_archived(&mut self) -> Result { + let tx = self + .conn + .transaction_with_behavior(TransactionBehavior::Immediate)?; + let count = tx.execute( + "DELETE FROM records WHERE archived=1 AND user_protected=0", + [], + )? as u64; + tx.commit()?; + Ok(count) + } + + pub fn usage(&self, now: i64) -> Result { + let mut statement = self.conn.prepare( + "SELECT category,COALESCE(SUM(length(value)+length(category)+length(logical_key)+ + length(source_plugin_id)+length(source_publisher_id)+length(source_version)+length(package_id)+?1),0),COUNT(*) + FROM records WHERE archived=0 AND (expires_at IS NULL OR expires_at>?2) GROUP BY category ORDER BY category", + )?; + let categories = statement + .query_map(params![RECORD_OVERHEAD_BYTES as i64, now], |row| { + Ok(CategoryUsage { + category: row.get(0)?, + logical_bytes: row.get::<_, i64>(1)?.max(0) as u64, + records: row.get::<_, i64>(2)?.max(0) as u64, + }) + })? + .collect::, _>>()?; + let logical_bytes = categories.iter().map(|c| c.logical_bytes).sum(); + let page_count: i64 = self.conn.query_row("PRAGMA page_count", [], |r| r.get(0))?; + let page_size: i64 = self.conn.query_row("PRAGMA page_size", [], |r| r.get(0))?; + Ok(Usage { + categories, + logical_bytes, + physical_bytes_estimate: page_count.max(0) as u64 * page_size.max(0) as u64, + }) + } +} + +fn owner_dir(root: &Path, owner: &OwnerNamespace) -> PathBuf { + root.join(component(&owner.publisher_id)) + .join(component(&owner.plugin_id)) + .join(component(&owner.profile_id)) +} + +fn component(value: &str) -> String { + if value.len() <= 100 + && !value.is_empty() + && value != "." + && value != ".." + && value + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.')) + { + value.to_owned() + } else { + let digest = Sha256::digest(value.as_bytes()); + format!( + "h-{}", + digest[..16] + .iter() + .map(|byte| format!("{byte:02x}")) + .collect::() + ) + } +} + +fn validate_category(category: &str) -> Result<(), PersistenceError> { + if category.is_empty() + || category.len() > MAX_CATEGORY_BYTES + || category + .chars() + .any(|ch| ch.is_control() || ch == '/' || ch == '\\') + { + return Err(PersistenceError::InvalidInput); + } + Ok(()) +} + +fn validate_selector(category: &str, key: &str) -> Result<(), PersistenceError> { + validate_category(category)?; + if key.is_empty() || key.len() > MAX_LOGICAL_KEY_BYTES || key.chars().any(char::is_control) { + return Err(PersistenceError::InvalidInput); + } + Ok(()) +} + +fn record_charge( + category: &str, + key: &str, + value_len: usize, + provenance: &RecordProvenance, +) -> u64 { + category.len() as u64 + + key.len() as u64 + + value_len as u64 + + provenance.source_plugin_id.len() as u64 + + provenance.source_publisher_id.len() as u64 + + provenance.source_version.len() as u64 + + provenance.package_id.len() as u64 + + RECORD_OVERHEAD_BYTES +} + +fn usage_bytes( + conn: &Connection, + category: Option<&str>, + except: Option<(&str, &str)>, + now: i64, +) -> Result { + let query = "SELECT COALESCE(SUM(length(value)+length(category)+length(logical_key)+ + length(source_plugin_id)+length(source_publisher_id)+length(source_version)+length(package_id)+?1),0) + FROM records WHERE archived=0 AND (expires_at IS NULL OR expires_at>?2) + AND (?3 IS NULL OR category=?3) AND (?4 IS NULL OR category<>?4 OR logical_key<>?5)"; + let bytes: i64 = conn.query_row( + query, + params![ + RECORD_OVERHEAD_BYTES as i64, + now, + category, + except.map(|e| e.0), + except.map(|e| e.1) + ], + |r| r.get(0), + )?; + Ok(bytes.max(0) as u64) +} + +fn record_from(row: &rusqlite::Row<'_>) -> rusqlite::Result { + Ok(PersistedRecord { + category: row.get(0)?, + logical_key: row.get(1)?, + value: row.get(2)?, + revision: row.get::<_, i64>(3)?.max(0) as u64, + provenance: RecordProvenance { + source_plugin_id: row.get(4)?, + source_publisher_id: row.get(5)?, + source_version: row.get(6)?, + package_id: row.get(7)?, + }, + created_at: row.get(8)?, + updated_at: row.get(9)?, + expires_at: row.get(10)?, + user_protected: row.get::<_, i64>(11)? != 0, + archived: row.get::<_, i64>(12)? != 0, + }) +} diff --git a/crates/platform/src/plugin_registry.rs b/crates/platform/src/plugin_registry.rs new file mode 100644 index 000000000..d7641c8e8 --- /dev/null +++ b/crates/platform/src/plugin_registry.rs @@ -0,0 +1,1418 @@ +//! Per-user immutable plugin package versions and crash-safe active pointers. +//! +//! The low-level import helper never validates package signatures or executes installation +//! hooks. `install_signed` is the integrity-checked path for package candidates. All methods +//! perform blocking filesystem work and must run on a worker thread. + +use serde::{Deserialize, Serialize}; +use std::fs::{self, File, OpenOptions}; +use std::io::{self, Write}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; + +const COMPLETE_FILE: &str = "registry-record.json"; +static NEXT_TEMP: AtomicU64 = AtomicU64::new(1); + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct InstalledPluginVersion { + pub plugin_id: String, + pub version: String, + pub package_path: PathBuf, +} + +#[derive(Serialize, Deserialize)] +struct VersionRecord { + schema: u32, + plugin_id: String, + version: String, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct ActivationRecord { + schema: u32, + plugin_id: String, + previous_version: String, + candidate_version: String, +} + +/// Durable handle for a version swap that is waiting for a supervised readiness check. +#[derive(Clone, Debug)] +pub struct ActivationTransaction { + record: ActivationRecord, +} + +/// Persistent per-user package registry. Paths under `versions/` are create-once; activation +/// changes only an atomic pointer and never edits an installed version tree. +#[derive(Clone, Debug)] +pub struct PluginPackageRegistry { + root: PathBuf, +} + +impl PluginPackageRegistry { + pub fn open(data_paths: &crate::paths::DataPaths) -> io::Result { + Self::at(data_paths.plugin_packages_dir()) + } + + pub fn at(root: impl Into) -> io::Result { + let root = root.into(); + ensure_owner_dir(&root)?; + let registry = Self { root }; + registry.recover()?; + Ok(registry) + } + + /// Imports an already verified directory as a new immutable version and optionally makes + /// it active. A failed copy leaves the current active pointer untouched. The source tree is + /// copied without following symlinks, and no source entry is executed. + pub fn install_verified( + &self, + plugin_id: &str, + version: &str, + verified_source: &Path, + activate: bool, + ) -> io::Result { + self.install_with_checkpoint(plugin_id, version, verified_source, activate, |_| Ok(())) + } + + /// Verify the detached Ed25519 signature and complete payload before import, verify the + /// copied immutable version again before activation, and leave any previous active version + /// untouched if either verification fails. The caller must supply the publisher key pinned + /// by the user's trust decision. + pub fn install_signed( + &self, + plugin_id: &str, + version: &str, + package_source: &Path, + publisher_key: &[u8], + activate: bool, + ) -> Result { + self.install_signed_impl( + plugin_id, + version, + package_source, + publisher_key, + None, + activate, + ) + } + + /// Import a signed package and prepare only its manifest-selected executable entrypoint. + /// The entrypoint must be a regular file below the copied package root and no path component + /// may be a symlink. ZIP permission bits are deliberately ignored; on Unix the host grants + /// execute permission only to this exact file before changing the active pointer. + pub fn install_signed_with_entrypoint( + &self, + plugin_id: &str, + version: &str, + package_source: &Path, + publisher_key: &[u8], + entrypoint: &str, + activate: bool, + ) -> Result { + self.install_signed_impl( + plugin_id, + version, + package_source, + publisher_key, + Some(entrypoint), + activate, + ) + } + + fn install_signed_impl( + &self, + plugin_id: &str, + version: &str, + package_source: &Path, + publisher_key: &[u8], + entrypoint: Option<&str>, + activate: bool, + ) -> Result { + crate::plugin_packages::verify_package_directory(package_source, publisher_key) + .map_err(InstallSignedError::Integrity)?; + let installed = self.install_verified(plugin_id, version, package_source, false)?; + crate::plugin_packages::verify_installed_package(&installed.package_path, publisher_key) + .map_err(InstallSignedError::Integrity)?; + if let Some(entrypoint) = entrypoint { + prepare_signed_entrypoint(&installed.package_path, entrypoint)?; + } + if activate { + self.set_active(plugin_id, version)?; + } + Ok(installed) + } + + /// Recheck the active installed version's signed files immediately before launch. + pub fn verify_active_package( + &self, + plugin_id: &str, + publisher_key: &[u8], + ) -> Result, InstallSignedError> { + let Some(installed) = self.active(plugin_id)? else { + return Ok(None); + }; + crate::plugin_packages::verify_installed_package(&installed.package_path, publisher_key) + .map_err(InstallSignedError::Integrity)?; + Ok(Some(installed)) + } + + fn install_with_checkpoint( + &self, + plugin_id: &str, + version: &str, + verified_source: &Path, + activate: bool, + mut checkpoint: F, + ) -> io::Result + where + F: FnMut(InstallCheckpoint) -> io::Result<()>, + { + validate_identity(plugin_id)?; + validate_identity(version)?; + let source_meta = fs::symlink_metadata(verified_source)?; + if !source_meta.is_dir() || source_meta.file_type().is_symlink() { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "verified package source must be a real directory", + )); + } + + let plugin_key = encode_key(plugin_id); + let version_key = encode_key(version); + let plugin_dir = self.root.join("plugins").join(&plugin_key); + let versions_dir = plugin_dir.join("versions"); + let final_path = versions_dir.join(&version_key); + ensure_owner_dir(&versions_dir)?; + sync_dir(&plugin_dir)?; + sync_dir(&self.root.join("plugins"))?; + sync_dir(&self.root)?; + match fs::symlink_metadata(&final_path) { + Ok(_) => { + return Err(io::Error::new( + io::ErrorKind::AlreadyExists, + "plugin version paths are immutable", + )); + } + Err(error) if error.kind() == io::ErrorKind::NotFound => {} + Err(error) => return Err(error), + } + let staging = versions_dir.join(format!( + ".staging-{}-{}", + std::process::id(), + NEXT_TEMP.fetch_add(1, Ordering::Relaxed) + )); + ensure_owner_dir(&staging)?; + let result = (|| { + let staged_package = staging.join("package"); + ensure_owner_dir(&staged_package)?; + copy_tree_no_links(verified_source, &staged_package)?; + sync_dir(&staged_package)?; + checkpoint(InstallCheckpoint::PayloadCopied)?; + let metadata = InstalledPluginVersion { + plugin_id: plugin_id.into(), + version: version.into(), + package_path: final_path.join("package"), + }; + let record = VersionRecord { + schema: 1, + plugin_id: plugin_id.into(), + version: version.into(), + }; + let metadata_bytes = serde_json::to_vec(&record).map_err(io::Error::other)?; + write_new_synced(&staging.join(COMPLETE_FILE), &metadata_bytes)?; + sync_dir(&staging)?; + checkpoint(InstallCheckpoint::CompleteMarkerSynced)?; + // A rename on the same filesystem publishes the fully synced directory atomically. + fs::rename(&staging, &final_path)?; + sync_dir(&versions_dir)?; + checkpoint(InstallCheckpoint::VersionPublished)?; + if activate { + self.set_active(plugin_id, version)?; + } + Ok(metadata) + })(); + if result.is_err() { + // A staging tree is never visible as a version or active entry. Best-effort removal + // is safe; if recovery is interrupted, open() removes the orphan on next start. + let _ = remove_tree_no_links(&staging); + } + result + } + + /// Atomically switches the active pointer to a complete immutable version. + pub fn set_active(&self, plugin_id: &str, version: &str) -> io::Result<()> { + validate_identity(plugin_id)?; + validate_identity(version)?; + let package = self.version_path(plugin_id, version); + if self.read_complete(&package, plugin_id, version).is_none() { + return Err(io::Error::new( + io::ErrorKind::NotFound, + "cannot activate an incomplete or missing plugin version", + )); + } + let active_dir = self.root.join("active"); + ensure_owner_dir(&active_dir)?; + sync_dir(&self.root)?; + let pointer = active_dir.join(encode_key(plugin_id)); + atomic_replace(&pointer, version.as_bytes())?; + sync_dir(&active_dir) + } + + /// Selects a fully published candidate while retaining a durable rollback record. Callers + /// must not start the candidate until this returns successfully; `recover` restores the old + /// version (or leaves the plugin inactive) if the application exits before `commit_activation`. + pub fn begin_activation( + &self, + plugin_id: &str, + expected_previous_version: &str, + candidate_version: &str, + ) -> io::Result { + validate_identity(plugin_id)?; + validate_identity(expected_previous_version)?; + validate_identity(candidate_version)?; + let previous = self.active(plugin_id)?.ok_or_else(|| { + io::Error::new(io::ErrorKind::NotFound, "plugin has no active version") + })?; + if previous.version != expected_previous_version { + return Err(io::Error::new( + io::ErrorKind::WouldBlock, + "active plugin changed before staged activation", + )); + } + if previous.version == candidate_version { + return Err(io::Error::new( + io::ErrorKind::AlreadyExists, + "candidate version is already active", + )); + } + let candidate = self.version_path(plugin_id, candidate_version); + if self + .read_complete(&candidate, plugin_id, candidate_version) + .is_none() + { + return Err(io::Error::new( + io::ErrorKind::NotFound, + "candidate package is incomplete or missing", + )); + } + + let record = ActivationRecord { + schema: 1, + plugin_id: plugin_id.to_owned(), + previous_version: previous.version, + candidate_version: candidate_version.to_owned(), + }; + let transaction_dir = self.activation_transactions_dir(); + ensure_owner_dir(&transaction_dir)?; + let transaction_path = self.activation_transaction_path(plugin_id); + let bytes = serde_json::to_vec(&record).map_err(io::Error::other)?; + let mut file = OpenOptions::new() + .write(true) + .create_new(true) + .open(&transaction_path)?; + file.write_all(&bytes)?; + file.sync_all()?; + sync_dir(&transaction_dir)?; + + if let Err(error) = self.set_active(plugin_id, candidate_version) { + let _ = fs::remove_file(&transaction_path); + let _ = sync_dir(&transaction_dir); + return Err(error); + } + Ok(ActivationTransaction { record }) + } + + /// Commits a candidate only if it is still the active version named by the transaction. + pub fn commit_activation(&self, transaction: ActivationTransaction) -> io::Result<()> { + self.finish_activation(transaction, true) + } + + /// Restores the prior package pointer without changing the permission store. Any permission + /// revocations made while the candidate was starting therefore remain in force. + pub fn rollback_activation(&self, transaction: ActivationTransaction) -> io::Result<()> { + self.finish_activation(transaction, false) + } + + fn finish_activation( + &self, + transaction: ActivationTransaction, + commit: bool, + ) -> io::Result<()> { + let record = transaction.record; + let path = self.activation_transaction_path(&record.plugin_id); + let file = match File::open(&path) { + Ok(file) => file, + Err(error) if error.kind() == io::ErrorKind::NotFound && commit => { + let active = self.active(&record.plugin_id)?; + if active.as_ref().map(|version| version.version.as_str()) + == Some(record.candidate_version.as_str()) + { + // A worker may finish the durable commit as its caller is cancelled. Retrying + // that commit is safe once the pointer already names the ready candidate. + return Ok(()); + } + return Err(error); + } + Err(error) => return Err(error), + }; + let persisted: ActivationRecord = serde_json::from_reader(file) + .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?; + if persisted.schema != 1 || persisted.plugin_id != record.plugin_id { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "activation transaction does not match its durable record", + )); + } + let active = self.active(&record.plugin_id)?; + if active.as_ref().map(|version| version.version.as_str()) + != Some(record.candidate_version.as_str()) + { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "active package changed during activation", + )); + } + if !commit { + self.set_active(&record.plugin_id, &record.previous_version)?; + } + fs::remove_file(&path)?; + sync_dir(&self.activation_transactions_dir()) + } + + fn activation_transactions_dir(&self) -> PathBuf { + self.root.join("activation-transactions") + } + + fn activation_transaction_path(&self, plugin_id: &str) -> PathBuf { + self.activation_transactions_dir() + .join(format!("{}.json", encode_key(plugin_id))) + } + + pub fn active(&self, plugin_id: &str) -> io::Result> { + validate_identity(plugin_id)?; + let pointer = self.root.join("active").join(encode_key(plugin_id)); + match fs::symlink_metadata(&pointer) { + Ok(meta) if meta.is_file() && !meta.file_type().is_symlink() => {} + Ok(_) => return Ok(None), + Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None), + Err(error) => return Err(error), + } + let version = fs::read_to_string(pointer)?; + validate_identity(&version)?; + Ok(self.read_complete(&self.version_path(plugin_id, &version), plugin_id, &version)) + } + + /// Lists valid active package versions. Callers must perform filesystem work on a blocking + /// worker; malformed pointers and incomplete packages are omitted. + pub fn active_versions(&self) -> io::Result> { + let active_dir = self.root.join("active"); + match fs::symlink_metadata(&active_dir) { + Ok(meta) if meta.is_dir() && !meta.file_type().is_symlink() => {} + Ok(_) => { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "active path is not a real directory", + )); + } + Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()), + Err(error) => return Err(error), + } + let mut active = Vec::new(); + for entry in fs::read_dir(active_dir)? { + let entry = entry?; + if !entry.file_type()?.is_file() { + continue; + } + let Some(plugin_id) = decode_key(&entry.file_name().to_string_lossy()) else { + continue; + }; + let Ok(version) = fs::read_to_string(entry.path()) else { + continue; + }; + if let Some(installed) = self.read_complete( + &self.version_path(&plugin_id, &version), + &plugin_id, + &version, + ) { + active.push(installed); + } + } + active.sort_by(|left, right| left.plugin_id.cmp(&right.plugin_id)); + Ok(active) + } + + pub fn versions(&self, plugin_id: &str) -> io::Result> { + validate_identity(plugin_id)?; + let versions_dir = self + .root + .join("plugins") + .join(encode_key(plugin_id)) + .join("versions"); + let mut versions = Vec::new(); + match fs::symlink_metadata(&versions_dir) { + Ok(meta) if meta.is_dir() && !meta.file_type().is_symlink() => {} + Ok(_) => { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "plugin versions path is not a real directory", + )); + } + Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(versions), + Err(error) => return Err(error), + } + let entries = match fs::read_dir(versions_dir) { + Ok(entries) => entries, + Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(versions), + Err(error) => return Err(error), + }; + for entry in entries { + let entry = entry?; + if !entry.file_type()?.is_dir() + || entry.file_name().to_string_lossy().starts_with(".staging-") + { + continue; + } + if let Some(metadata) = self.read_complete(&entry.path(), plugin_id, "") { + versions.push(metadata); + } + } + versions.sort_by(|left, right| left.version.cmp(&right.version)); + Ok(versions) + } + + /// Removes one published immutable version and, when that version is the active one, the + /// active pointer first so nothing keeps pointing at deleted files. Callers must stop its + /// supervised processes and revoke sessions before invoking this method. This is the rollback + /// primitive for a staged install that failed before it completed; every other version + /// belonging to the plugin is left untouched. + pub fn remove_version(&self, plugin_id: &str, version: &str) -> io::Result<()> { + validate_identity(plugin_id)?; + validate_identity(version)?; + let pointer = self.root.join("active").join(encode_key(plugin_id)); + match fs::symlink_metadata(&pointer) { + Ok(meta) if meta.is_file() && !meta.file_type().is_symlink() => { + if fs::read_to_string(&pointer)? == version { + self.remove_active_pointer(plugin_id)?; + } + } + Ok(_) => { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "plugin active pointer is not a regular file", + )); + } + Err(error) if error.kind() == io::ErrorKind::NotFound => {} + Err(error) => return Err(error), + } + let versions_dir = self + .root + .join("plugins") + .join(encode_key(plugin_id)) + .join("versions"); + remove_tree_no_links(&versions_dir.join(encode_key(version)))?; + match fs::symlink_metadata(&versions_dir) { + Ok(meta) if meta.is_dir() && !meta.file_type().is_symlink() => sync_dir(&versions_dir), + Ok(_) => Err(io::Error::new( + io::ErrorKind::InvalidData, + "plugin versions path is not a real directory", + )), + Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()), + Err(error) => Err(error), + } + } + + /// Removes the active pointer and every installed package version for one plugin. Callers + /// must stop its supervised processes and revoke sessions before invoking this method. + pub fn remove_plugin(&self, plugin_id: &str) -> io::Result<()> { + validate_identity(plugin_id)?; + let active_dir = self.root.join("active"); + match fs::symlink_metadata(&active_dir) { + Ok(meta) if meta.is_dir() && !meta.file_type().is_symlink() => { + let pointer = active_dir.join(encode_key(plugin_id)); + match fs::symlink_metadata(&pointer) { + Ok(meta) if meta.is_file() && !meta.file_type().is_symlink() => { + fs::remove_file(pointer)?; + sync_dir(&active_dir)?; + } + Ok(_) => { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "plugin active pointer is not a regular file", + )); + } + Err(error) if error.kind() == io::ErrorKind::NotFound => {} + Err(error) => return Err(error), + } + } + Ok(_) => { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "active path is not a real directory", + )); + } + Err(error) if error.kind() == io::ErrorKind::NotFound => {} + Err(error) => return Err(error), + } + let plugins_dir = self.root.join("plugins"); + match fs::symlink_metadata(&plugins_dir) { + Ok(meta) if meta.is_dir() && !meta.file_type().is_symlink() => { + let plugin_dir = plugins_dir.join(encode_key(plugin_id)); + remove_tree_no_links(&plugin_dir)?; + sync_dir(&plugins_dir)?; + } + Ok(_) => { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "plugins path is not a real directory", + )); + } + Err(error) if error.kind() == io::ErrorKind::NotFound => {} + Err(error) => return Err(error), + } + Ok(()) + } + + /// Removes interrupted staging transactions and invalid active pointers. Valid old active + /// pointers are never changed by an incomplete update; fully published but unactivated + /// versions are retained for inspection or a later explicit activation. + pub fn recover(&self) -> io::Result<()> { + self.recover_activation_transactions()?; + let plugins = self.root.join("plugins"); + if plugins.exists() + && fs::symlink_metadata(&plugins)?.is_dir() + && !fs::symlink_metadata(&plugins)?.file_type().is_symlink() + { + for plugin_entry in fs::read_dir(&plugins)? { + let plugin_entry = plugin_entry?; + if !plugin_entry.file_type()?.is_dir() { + continue; + } + let versions_dir = plugin_entry.path().join("versions"); + if !versions_dir.exists() { + continue; + } + let version_meta = fs::symlink_metadata(&versions_dir)?; + if !version_meta.is_dir() || version_meta.file_type().is_symlink() { + continue; + } + for version_entry in fs::read_dir(&versions_dir)? { + let version_entry = version_entry?; + if version_entry + .file_name() + .to_string_lossy() + .starts_with(".staging-") + || (version_entry.file_type()?.is_dir() + && self.read_record(&version_entry.path()).is_none()) + { + remove_tree_no_links(&version_entry.path())?; + } + } + } + } + let active_dir = self.root.join("active"); + if !active_dir.exists() { + return Ok(()); + } + let active_meta = fs::symlink_metadata(&active_dir)?; + if !active_meta.is_dir() || active_meta.file_type().is_symlink() { + return Ok(()); + } + for pointer_entry in fs::read_dir(&active_dir)? { + let pointer_entry = pointer_entry?; + if pointer_entry + .file_name() + .to_string_lossy() + .starts_with(".pointer-") + { + if pointer_entry.file_type()?.is_file() { + fs::remove_file(pointer_entry.path())?; + } + continue; + } + if !pointer_entry.file_type()?.is_file() { + if pointer_entry.file_type()?.is_symlink() { + fs::remove_file(pointer_entry.path())?; + } + continue; + } + let plugin_id = decode_key(&pointer_entry.file_name().to_string_lossy()); + let valid = plugin_id.as_deref().is_some_and(|plugin_id| { + fs::read_to_string(pointer_entry.path()) + .ok() + .and_then(|version| { + self.read_complete( + &self.version_path(plugin_id, &version), + plugin_id, + &version, + ) + }) + .is_some() + }); + if !valid { + fs::remove_file(pointer_entry.path())?; + } + } + sync_dir(&self.root) + } + + fn recover_activation_transactions(&self) -> io::Result<()> { + let directory = self.activation_transactions_dir(); + match fs::symlink_metadata(&directory) { + Ok(metadata) if metadata.is_dir() && !metadata.file_type().is_symlink() => {} + Ok(_) => { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "activation transaction path is not a real directory", + )); + } + Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(()), + Err(error) => return Err(error), + } + for entry in fs::read_dir(&directory)? { + let entry = entry?; + let name = entry.file_name().to_string_lossy().into_owned(); + let Some(encoded_id) = name.strip_suffix(".json") else { + if entry.file_type()?.is_file() { + fs::remove_file(entry.path())?; + } + continue; + }; + let Some(plugin_id) = decode_key(encoded_id) else { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "activation transaction has an invalid plugin id", + )); + }; + if !entry.file_type()?.is_file() { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "activation transaction is not a regular file", + )); + } + let record = File::open(entry.path()).and_then(|file| { + serde_json::from_reader::<_, ActivationRecord>(file).map_err(io::Error::other) + }); + let Ok(record) = record else { + self.remove_active_pointer(&plugin_id)?; + fs::remove_file(entry.path())?; + continue; + }; + if record.schema != 1 + || record.plugin_id != plugin_id + || validate_identity(&record.previous_version).is_err() + || validate_identity(&record.candidate_version).is_err() + { + self.remove_active_pointer(&plugin_id)?; + fs::remove_file(entry.path())?; + continue; + } + let active = self.active(&plugin_id)?; + if active + .as_ref() + .is_some_and(|active| active.version == record.candidate_version) + { + if self + .read_complete( + &self.version_path(&plugin_id, &record.previous_version), + &plugin_id, + &record.previous_version, + ) + .is_some() + { + self.set_active(&plugin_id, &record.previous_version)?; + } else { + self.remove_active_pointer(&plugin_id)?; + } + } + fs::remove_file(entry.path())?; + } + sync_dir(&directory) + } + + fn remove_active_pointer(&self, plugin_id: &str) -> io::Result<()> { + let directory = self.root.join("active"); + let pointer = directory.join(encode_key(plugin_id)); + match fs::symlink_metadata(&pointer) { + Ok(metadata) if metadata.is_file() && !metadata.file_type().is_symlink() => { + fs::remove_file(pointer)?; + sync_dir(&directory) + } + Ok(_) => Err(io::Error::new( + io::ErrorKind::InvalidData, + "active plugin pointer is not a regular file", + )), + Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()), + Err(error) => Err(error), + } + } + + fn version_path(&self, plugin_id: &str, version: &str) -> PathBuf { + self.root + .join("plugins") + .join(encode_key(plugin_id)) + .join("versions") + .join(encode_key(version)) + } + + fn read_complete( + &self, + path: &Path, + expected_plugin: &str, + expected_version: &str, + ) -> Option { + let record = self.read_record(path)?; + if record.plugin_id != expected_plugin + || (!expected_version.is_empty() && record.version != expected_version) + { + return None; + } + Some(record) + } + + fn read_record(&self, path: &Path) -> Option { + let metadata = fs::symlink_metadata(path).ok()?; + if !metadata.is_dir() || metadata.file_type().is_symlink() { + return None; + } + let marker = fs::symlink_metadata(path.join(COMPLETE_FILE)).ok()?; + if !marker.is_file() || marker.file_type().is_symlink() { + return None; + } + let file = File::open(path.join(COMPLETE_FILE)).ok()?; + let record: VersionRecord = serde_json::from_reader(file).ok()?; + if record.schema != 1 { + return None; + } + Some(InstalledPluginVersion { + plugin_id: record.plugin_id, + version: record.version, + package_path: { + let package = path.join("package"); + let payload = fs::symlink_metadata(&package).ok()?; + if !payload.is_dir() || payload.file_type().is_symlink() { + return None; + } + package + }, + }) + } +} + +#[derive(Debug, thiserror::Error)] +pub enum InstallSignedError { + #[error("plugin package integrity validation failed: {0}")] + Integrity(#[from] crate::plugin_packages::IntegrityError), + #[error(transparent)] + Io(#[from] io::Error), +} + +fn prepare_signed_entrypoint(package_root: &Path, entrypoint: &str) -> io::Result<()> { + let relative = Path::new(entrypoint); + if relative.as_os_str().is_empty() + || relative + .components() + .any(|component| !matches!(component, std::path::Component::Normal(_))) + { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "signed plugin entrypoint must be a normalized package-relative path", + )); + } + + let mut current = package_root.to_owned(); + for component in relative.components() { + current.push(component.as_os_str()); + let metadata = fs::symlink_metadata(¤t)?; + if metadata.file_type().is_symlink() { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "signed plugin entrypoint cannot traverse a symlink", + )); + } + if current != package_root.join(relative) && !metadata.is_dir() { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "signed plugin entrypoint parent must be a directory", + )); + } + if current == package_root.join(relative) && !metadata.is_file() { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "signed plugin entrypoint must be a regular file", + )); + } + } + + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + fs::set_permissions(current, fs::Permissions::from_mode(0o700))?; + } + Ok(()) +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum InstallCheckpoint { + PayloadCopied, + CompleteMarkerSynced, + VersionPublished, +} + +fn validate_identity(value: &str) -> io::Result<()> { + if value.trim().is_empty() + || value.len() > 256 + || value == "." + || value == ".." + || value.chars().any(char::is_control) + { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "invalid plugin identity", + )); + } + Ok(()) +} + +fn encode_key(value: &str) -> String { + value + .as_bytes() + .iter() + .map(|byte| format!("{byte:02x}")) + .collect() +} + +fn decode_key(value: &str) -> Option { + if value.is_empty() || !value.len().is_multiple_of(2) { + return None; + } + let bytes = (0..value.len()) + .step_by(2) + .map(|index| u8::from_str_radix(&value[index..index + 2], 16).ok()) + .collect::>>()?; + String::from_utf8(bytes).ok() +} + +fn ensure_owner_dir(path: &Path) -> io::Result<()> { + match fs::symlink_metadata(path) { + Ok(meta) if meta.is_dir() && !meta.file_type().is_symlink() => {} + Ok(_) => { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "registry path is not a real directory", + )); + } + Err(error) if error.kind() == io::ErrorKind::NotFound => { + if let Some(parent) = path.parent() { + ensure_owner_dir(parent)?; + } + #[cfg(unix)] + { + use std::os::unix::fs::DirBuilderExt; + fs::DirBuilder::new().mode(0o700).create(path)?; + } + #[cfg(not(unix))] + fs::create_dir(path)?; + } + Err(error) => return Err(error), + } + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let mode = fs::metadata(path)?.permissions().mode(); + if mode & 0o077 != 0 { + fs::set_permissions(path, fs::Permissions::from_mode(mode & !0o077))?; + } + } + Ok(()) +} + +fn copy_tree_no_links(source: &Path, destination: &Path) -> io::Result<()> { + for entry in fs::read_dir(source)? { + let entry = entry?; + let from = entry.path(); + let to = destination.join(entry.file_name()); + let metadata = fs::symlink_metadata(&from)?; + if metadata.file_type().is_symlink() { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "symlink in verified package tree", + )); + } + if metadata.is_dir() { + ensure_owner_dir(&to)?; + copy_tree_no_links(&from, &to)?; + sync_dir(&to)?; + } else if metadata.is_file() { + let mut input = File::open(from)?; + let mut output = OpenOptions::new().write(true).create_new(true).open(to)?; + io::copy(&mut input, &mut output)?; + output.sync_all()?; + } else { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "unsupported filesystem entry in verified package tree", + )); + } + } + Ok(()) +} + +fn write_new_synced(path: &Path, bytes: &[u8]) -> io::Result<()> { + let mut file = OpenOptions::new().write(true).create_new(true).open(path)?; + file.write_all(bytes)?; + file.sync_all() +} + +fn atomic_replace(path: &Path, bytes: &[u8]) -> io::Result<()> { + let parent = path + .parent() + .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "pointer has no parent"))?; + ensure_owner_dir(parent)?; + let temp = parent.join(format!( + ".pointer-{}-{}", + std::process::id(), + NEXT_TEMP.fetch_add(1, Ordering::Relaxed) + )); + write_new_synced(&temp, bytes)?; + #[cfg(windows)] + { + use std::os::windows::ffi::OsStrExt; + use windows_sys::Win32::Storage::FileSystem::{ + MOVEFILE_REPLACE_EXISTING, MOVEFILE_WRITE_THROUGH, MoveFileExW, + }; + let from = temp + .as_os_str() + .encode_wide() + .chain(Some(0)) + .collect::>(); + let to = path + .as_os_str() + .encode_wide() + .chain(Some(0)) + .collect::>(); + // SAFETY: both paths are NUL-terminated UTF-16 buffers valid for the call. + let result = unsafe { + MoveFileExW( + from.as_ptr(), + to.as_ptr(), + MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH, + ) + }; + if result == 0 { + let error = io::Error::last_os_error(); + let _ = fs::remove_file(temp); + return Err(error); + } + Ok(()) + } + #[cfg(not(windows))] + { + if let Err(error) = fs::rename(&temp, path) { + let _ = fs::remove_file(temp); + return Err(error); + } + Ok(()) + } +} + +fn sync_dir(path: &Path) -> io::Result<()> { + #[cfg(unix)] + { + File::open(path)?.sync_all() + } + #[cfg(not(unix))] + { + let _ = path; + Ok(()) + } +} + +fn remove_tree_no_links(path: &Path) -> io::Result<()> { + let metadata = match fs::symlink_metadata(path) { + Ok(metadata) => metadata, + Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(()), + Err(error) => return Err(error), + }; + if metadata.file_type().is_symlink() || metadata.is_file() { + return fs::remove_file(path); + } + if !metadata.is_dir() { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "unexpected registry filesystem object", + )); + } + for entry in fs::read_dir(path)? { + remove_tree_no_links(&entry?.path())?; + } + fs::remove_dir(path) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::path::Component; + use tempfile::TempDir; + + fn source(temp: &TempDir, name: &str, content: &[u8]) -> PathBuf { + let path = temp.path().join(name); + fs::create_dir(&path).unwrap(); + fs::write(path.join("plugin.bin"), content).unwrap(); + path + } + + fn signed_source(temp: &TempDir, name: &str) -> (PathBuf, Vec) { + use ring::signature::KeyPair; + use sha2::Digest; + let path = temp.path().join(name); + fs::create_dir(&path).unwrap(); + fs::write(path.join("plugin.bin"), b"signed bytes").unwrap(); + let files = std::collections::BTreeMap::from([( + "plugin.bin".to_owned(), + format!("{:x}", sha2::Sha256::digest(b"signed bytes")), + )]); + let raw = serde_json::to_vec(&serde_json::json!({"schema": 1, "files": files})).unwrap(); + let key = ring::signature::Ed25519KeyPair::from_seed_unchecked(&[11u8; 32]).unwrap(); + let mut signed = crate::plugin_packages::SIGNATURE_DOMAIN_PREFIX.to_vec(); + signed.extend_from_slice(&raw); + fs::write(path.join("integrity.json"), raw).unwrap(); + fs::write(path.join("signature.ed25519"), key.sign(&signed).as_ref()).unwrap(); + (path, key.public_key().as_ref().to_vec()) + } + + #[test] + fn signed_install_checks_copy_and_active_payload_against_pinned_key() { + let temp = TempDir::new().unwrap(); + let registry = PluginPackageRegistry::at(temp.path().join("registry")).unwrap(); + let (candidate, key) = signed_source(&temp, "signed"); + let installed = registry + .install_signed("demo", "1", &candidate, &key, true) + .unwrap(); + assert_eq!( + registry.verify_active_package("demo", &key).unwrap(), + Some(installed.clone()) + ); + fs::write(installed.package_path.join("plugin.bin"), b"tampered").unwrap(); + assert!(matches!( + registry.verify_active_package("demo", &key), + Err(InstallSignedError::Integrity( + crate::plugin_packages::IntegrityError::HashMismatch + )) + )); + } + + #[cfg(unix)] + #[test] + fn signed_entrypoint_preparation_is_exact_and_rejects_symlinks() { + use std::os::unix::fs::{PermissionsExt, symlink}; + + let temp = TempDir::new().unwrap(); + let root = temp.path().join("package"); + fs::create_dir_all(root.join("bin")).unwrap(); + fs::write(root.join("bin/provider"), b"executable").unwrap(); + fs::write(root.join("README.md"), b"data").unwrap(); + + prepare_signed_entrypoint(&root, "bin/provider").unwrap(); + assert_eq!( + fs::metadata(root.join("bin/provider")) + .unwrap() + .permissions() + .mode() + & 0o777, + 0o700 + ); + assert_eq!( + fs::metadata(root.join("README.md")) + .unwrap() + .permissions() + .mode() + & 0o111, + 0, + "data files must not gain executable bits" + ); + + let outside = temp.path().join("outside"); + fs::write(&outside, b"outside").unwrap(); + symlink(&outside, root.join("linked-provider")).unwrap(); + assert!(prepare_signed_entrypoint(&root, "linked-provider").is_err()); + assert!(prepare_signed_entrypoint(&root, "../outside").is_err()); + } + + #[test] + fn install_publishes_complete_version_then_switches_active_pointer() { + let temp = TempDir::new().unwrap(); + let registry = PluginPackageRegistry::at(temp.path().join("registry")).unwrap(); + let one = source(&temp, "one", b"one"); + registry + .install_verified("community.demo", "1.0.0", &one, true) + .unwrap(); + let active = registry.active("community.demo").unwrap().unwrap(); + assert_eq!(active.version, "1.0.0"); + assert_eq!( + fs::read(active.package_path.join("plugin.bin")).unwrap(), + b"one" + ); + assert!(!active.package_path.join(COMPLETE_FILE).exists()); + } + + #[test] + fn active_versions_lists_only_complete_active_packages() { + let temp = TempDir::new().unwrap(); + let registry = PluginPackageRegistry::at(temp.path().join("registry")).unwrap(); + let package = source(&temp, "package", b"payload"); + registry + .install_verified("org.example.one", "1.0.0", &package, true) + .unwrap(); + registry + .install_verified("org.example.two", "2.0.0", &package, false) + .unwrap(); + let active = registry.active_versions().unwrap(); + assert_eq!(active.len(), 1); + assert_eq!(active[0].plugin_id, "org.example.one"); + assert_eq!(active[0].version, "1.0.0"); + } + + #[test] + fn remove_plugin_deactivates_and_deletes_all_versions_without_touching_other_plugins() { + let temp = TempDir::new().unwrap(); + let registry = PluginPackageRegistry::at(temp.path().join("registry")).unwrap(); + let one = source(&temp, "one", b"one"); + let two = source(&temp, "two", b"two"); + let removed = registry + .install_verified("org.example.remove", "1.0.0", &one, true) + .unwrap(); + registry + .install_verified("org.example.remove", "2.0.0", &two, false) + .unwrap(); + let retained = registry + .install_verified("org.example.keep", "1.0.0", &one, true) + .unwrap(); + + registry.remove_plugin("org.example.remove").unwrap(); + + assert!(registry.active("org.example.remove").unwrap().is_none()); + assert!(registry.versions("org.example.remove").unwrap().is_empty()); + assert!(!removed.package_path.exists()); + assert_eq!(registry.active("org.example.keep").unwrap(), Some(retained)); + } + + #[test] + fn remove_version_drops_only_one_version_and_clears_a_matching_pointer() { + let temp = TempDir::new().unwrap(); + let registry = PluginPackageRegistry::at(temp.path().join("registry")).unwrap(); + let one = source(&temp, "one", b"one"); + let two = source(&temp, "two", b"two"); + let older = registry + .install_verified("org.example.rollback", "1.0.0", &one, true) + .unwrap(); + let newer = registry + .install_verified("org.example.rollback", "2.0.0", &two, true) + .unwrap(); + let other = registry + .install_verified("org.example.keep", "1.0.0", &one, true) + .unwrap(); + + // A version that is not active is removed without touching the pointer. + registry + .remove_version("org.example.rollback", "1.0.0") + .unwrap(); + assert!(!older.package_path.exists()); + assert_eq!( + registry.active("org.example.rollback").unwrap(), + Some(newer.clone()) + ); + + // Removing the active version clears its pointer and keeps the other plugin intact. + registry + .remove_version("org.example.rollback", "2.0.0") + .unwrap(); + assert!(!newer.package_path.exists()); + assert!(registry.active("org.example.rollback").unwrap().is_none()); + assert!( + registry + .versions("org.example.rollback") + .unwrap() + .is_empty() + ); + assert_eq!( + registry.active("org.example.keep").unwrap(), + Some(other.clone()) + ); + + // A repeated rollback is a no-op rather than an error. + registry + .remove_version("org.example.rollback", "2.0.0") + .unwrap(); + } + + #[test] + fn restart_after_interrupted_copy_keeps_old_active_and_discards_staging() { + let temp = TempDir::new().unwrap(); + let root = temp.path().join("registry"); + let registry = PluginPackageRegistry::at(&root).unwrap(); + let one = source(&temp, "one", b"stable"); + registry.install_verified("demo", "1", &one, true).unwrap(); + let two = source(&temp, "two", b"partial candidate"); + let interrupted = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let _ = registry.install_with_checkpoint("demo", "2", &two, true, |stage| { + if stage == InstallCheckpoint::PayloadCopied { + panic!("simulated process interruption"); + } + Ok(()) + }); + })); + assert!(interrupted.is_err()); + let restarted = PluginPackageRegistry::at(&root).unwrap(); + assert_eq!(restarted.active("demo").unwrap().unwrap().version, "1"); + assert_eq!( + restarted + .versions("demo") + .unwrap() + .iter() + .map(|v| v.version.as_str()) + .collect::>(), + vec!["1"] + ); + } + + #[test] + fn restart_after_publish_before_pointer_swap_retains_old_active_and_new_inactive_version() { + let temp = TempDir::new().unwrap(); + let root = temp.path().join("registry"); + let registry = PluginPackageRegistry::at(&root).unwrap(); + let one = source(&temp, "one", b"stable"); + registry.install_verified("demo", "1", &one, true).unwrap(); + let two = source(&temp, "two", b"candidate"); + let interrupted = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let _ = registry.install_with_checkpoint("demo", "2", &two, true, |stage| { + if stage == InstallCheckpoint::VersionPublished { + panic!("simulated process interruption"); + } + Ok(()) + }); + })); + assert!(interrupted.is_err()); + let restarted = PluginPackageRegistry::at(&root).unwrap(); + assert_eq!(restarted.active("demo").unwrap().unwrap().version, "1"); + assert_eq!( + restarted + .versions("demo") + .unwrap() + .iter() + .map(|v| v.version.as_str()) + .collect::>(), + vec!["1", "2"] + ); + restarted.set_active("demo", "2").unwrap(); + assert_eq!(restarted.active("demo").unwrap().unwrap().version, "2"); + } + + #[test] + fn staged_activation_can_commit_or_roll_back_after_readiness() { + let temp = TempDir::new().unwrap(); + let root = temp.path().join("registry"); + let registry = PluginPackageRegistry::at(&root).unwrap(); + let one = source(&temp, "one", b"stable"); + registry.install_verified("demo", "1", &one, true).unwrap(); + let two = source(&temp, "two", b"candidate"); + registry.install_verified("demo", "2", &two, false).unwrap(); + + let failed_candidate = registry.begin_activation("demo", "1", "2").unwrap(); + assert_eq!(registry.active("demo").unwrap().unwrap().version, "2"); + registry.rollback_activation(failed_candidate).unwrap(); + assert_eq!(registry.active("demo").unwrap().unwrap().version, "1"); + + let ready_candidate = registry.begin_activation("demo", "1", "2").unwrap(); + registry.commit_activation(ready_candidate.clone()).unwrap(); + registry.commit_activation(ready_candidate).unwrap(); + assert_eq!(registry.active("demo").unwrap().unwrap().version, "2"); + assert_eq!(registry.versions("demo").unwrap().len(), 2); + } + + #[test] + fn interrupted_staged_activation_recovers_to_last_known_good_version() { + let temp = TempDir::new().unwrap(); + let root = temp.path().join("registry"); + let registry = PluginPackageRegistry::at(&root).unwrap(); + let one = source(&temp, "one", b"stable"); + registry.install_verified("demo", "1", &one, true).unwrap(); + let two = source(&temp, "two", b"candidate"); + registry.install_verified("demo", "2", &two, false).unwrap(); + + let _transaction = registry.begin_activation("demo", "1", "2").unwrap(); + assert_eq!(registry.active("demo").unwrap().unwrap().version, "2"); + + let restarted = PluginPackageRegistry::at(&root).unwrap(); + assert_eq!(restarted.active("demo").unwrap().unwrap().version, "1"); + assert_eq!(restarted.versions("demo").unwrap().len(), 2); + assert_eq!( + fs::read_dir(restarted.activation_transactions_dir()) + .unwrap() + .count(), + 0 + ); + } + + #[test] + fn first_interrupted_install_recovers_to_inactive_state() { + let temp = TempDir::new().unwrap(); + let root = temp.path().join("registry"); + let registry = PluginPackageRegistry::at(&root).unwrap(); + let candidate = source(&temp, "candidate", b"candidate"); + let interrupted = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let _ = registry + .install_with_checkpoint("demo", "1", &candidate, true, |_| panic!("crash")); + })); + assert!(interrupted.is_err()); + let restarted = PluginPackageRegistry::at(&root).unwrap(); + assert!(restarted.active("demo").unwrap().is_none()); + assert!(restarted.versions("demo").unwrap().is_empty()); + } + + #[test] + fn refuses_duplicate_version_paths_and_symlink_content() { + let temp = TempDir::new().unwrap(); + let registry = PluginPackageRegistry::at(temp.path().join("registry")).unwrap(); + let one = source(&temp, "one", b"one"); + registry.install_verified("demo", "1", &one, false).unwrap(); + assert_eq!( + registry + .install_verified("demo", "1", &one, true) + .unwrap_err() + .kind(), + io::ErrorKind::AlreadyExists + ); + #[cfg(unix)] + { + std::os::unix::fs::symlink(one.join("plugin.bin"), one.join("linked")).unwrap(); + assert!(registry.install_verified("demo", "2", &one, true).is_err()); + assert!(registry.active("demo").unwrap().is_none()); + } + } + + #[test] + fn data_paths_expose_persistent_registry_location() { + let temp = TempDir::new().unwrap(); + let paths = crate::paths::DataPaths::at(temp.path()); + let registry = PluginPackageRegistry::open(&paths).unwrap(); + assert!(registry.root.starts_with(paths.data_dir())); + assert_eq!( + paths.plugin_packages_dir(), + temp.path().join("plugin-packages") + ); + } + + #[test] + fn identity_path_encoding_is_traversal_safe_and_reversible() { + let value = "../plugin\0id".replace('\0', "-zero-"); + let encoded = encode_key(&value); + assert!( + !Path::new(&encoded) + .components() + .any(|component| matches!(component, Component::ParentDir)) + ); + assert_eq!(decode_key(&encoded).as_deref(), Some(value.as_str())); + assert!(validate_identity("../plugin").is_ok()); + } +} diff --git a/crates/platform/src/plugin_shared_data.rs b/crates/platform/src/plugin_shared_data.rs new file mode 100644 index 000000000..650da48b3 --- /dev/null +++ b/crates/platform/src/plugin_shared_data.rs @@ -0,0 +1,1734 @@ +//! Host-owned durable pool for public shared-data records. +//! +//! The pool lives in its own SQLite file, `plugin-shared-data.gnpersistence`, below the application +//! data directory. It is separate from the application settings/library database and from the +//! private `plugin-data` stores, so a public publication can outlive its producer session without +//! making private storage public. +//! +//! The store accepts only host-resolved values: an opaque owner key, host-assigned provenance and +//! an already validated payload. It never accepts a plugin id from an RPC, a path, a plugin +//! selector for another owner, or a session id; session-only rows are never written here. Every +//! method performs blocking SQLite work and must run on the host's storage worker, never on the UI +//! thread. No method or error message discloses a physical path. +//! +//! A record with a resource id is replaced in place for the same owner, dataset and resource: +//! its record id stays stable, its record revision increases by one and it gets the next pool +//! revision. A record without a resource id is appended with a new host-assigned record id. The +//! pool revision is persisted in `shared_state` and shared by lists and watches; pruning or +//! protection changes also advance it when the visible pool changed. +//! +//! Uninstall retention can archive every row of one owner. Archived rows stay attributed to the +//! original owner and remain on disk, but ordinary reads, lists, usage and automatic pruning skip +//! them. A separate host review restores them (`reuse_archived_owner`) or the host deletes them; +//! a plugin can never archive, reuse or inspect archived records through an RPC. + +use std::fs; +use std::path::Path; + +use rusqlite::{Connection, OptionalExtension, TransactionBehavior, params}; + +/// File name of the shared-data pool inside the application data directory. +pub const FILE_NAME: &str = "plugin-shared-data.gnpersistence"; +/// Pre-release builds used the generic SQLite extension. Existing pools are renamed on open. +pub const LEGACY_FILE_NAME: &str = "plugin-shared-data.sqlite3"; + +/// The schema version this build writes. +pub const CURRENT_SCHEMA_VERSION: u32 = 3; + +/// The longest dataset, schema and resource identifier. +pub const MAX_IDENTIFIER_BYTES: usize = 256; +/// The longest sharing class string. +pub const MAX_CLASS_BYTES: usize = 32; +/// The largest payload (structured JSON or opaque bytes) of one record. +pub const MAX_RECORD_BYTES: usize = 1024 * 1024; +/// The hard per-owner logical byte ceiling, regardless of a lower user policy. +pub const MAX_OWNER_LOGICAL_BYTES: u64 = 64 * 1024 * 1024; +/// The longest age a user retention policy may select (365 days). +pub const MAX_RETENTION_AGE_SECONDS: u64 = 365 * 24 * 60 * 60; +/// The longest time-to-live a producer may request (30 days). +pub const MAX_TTL_SECONDS: u64 = 30 * 24 * 60 * 60; +/// How many rows one bounded prune may remove. +pub const MAX_PRUNE_ROWS: u64 = 1024; +/// Charged per record on top of its identifiers, provenance and payload. +const RECORD_OVERHEAD_BYTES: u64 = 256; + +struct Migration { + version: u32, + sql: &'static str, +} + +/// Every schema step this build knows. Versions start at 1 and increase by exactly one. +/// +/// Version 1 is the initial pool; version 2 adds host-controlled retention protection, which is +/// never supplied by a plugin. An existing database is upgraded in order and keeps its records. +const MIGRATIONS: &[Migration] = &[ + Migration { + version: 1, + sql: "CREATE TABLE shared_state ( + id INTEGER PRIMARY KEY CHECK (id = 1), + revision INTEGER NOT NULL CHECK (revision >= 0) + ) STRICT; + INSERT INTO shared_state (id, revision) VALUES (1, 0); + CREATE TABLE shared_owners ( + owner_key BLOB PRIMARY KEY CHECK (length(owner_key) = 32), + profile_epoch INTEGER NOT NULL CHECK (profile_epoch > 0), + updated_at INTEGER NOT NULL + ) STRICT; + CREATE TABLE shared_records ( + record_id TEXT PRIMARY KEY, + owner_key BLOB NOT NULL + REFERENCES shared_owners(owner_key) ON DELETE CASCADE + CHECK (length(owner_key) = 32), + dataset_id TEXT NOT NULL, + resource_id TEXT, + category INTEGER CHECK (category IS NULL OR category >= 0), + class TEXT NOT NULL, + schema_id TEXT NOT NULL, + schema_version INTEGER NOT NULL CHECK (schema_version > 0), + fields_json TEXT NOT NULL, + opaque_payload BLOB NOT NULL, + source_plugin_id TEXT NOT NULL, + source_publisher_fingerprint TEXT NOT NULL, + source_profile_id TEXT NOT NULL, + declared_developer TEXT NOT NULL, + origin TEXT NOT NULL, + package_version TEXT NOT NULL, + package_digest BLOB NOT NULL, + observed_at INTEGER NOT NULL CHECK (observed_at >= 0), + received_at INTEGER NOT NULL, + updated_at INTEGER NOT NULL, + expires_at INTEGER, + sequence INTEGER NOT NULL CHECK (sequence >= 0), + source_observation_id TEXT NOT NULL, + revision INTEGER NOT NULL CHECK (revision >= 1), + pool_revision INTEGER NOT NULL CHECK (pool_revision >= 1), + logical_bytes INTEGER NOT NULL CHECK (logical_bytes >= 0), + UNIQUE (owner_key, dataset_id, resource_id) + ) STRICT; + CREATE INDEX shared_records_owner_dataset + ON shared_records(owner_key, dataset_id, received_at, record_id); + CREATE INDEX shared_records_owner_expiry + ON shared_records(owner_key, expires_at); + CREATE INDEX shared_records_owner_updated + ON shared_records(owner_key, updated_at); + CREATE TABLE shared_retention ( + owner_key BLOB PRIMARY KEY + REFERENCES shared_owners(owner_key) ON DELETE CASCADE, + max_age_seconds INTEGER CHECK (max_age_seconds IS NULL OR max_age_seconds > 0), + max_bytes INTEGER CHECK (max_bytes IS NULL OR max_bytes > 0), + updated_at INTEGER NOT NULL + ) STRICT;", + }, + Migration { + version: 2, + sql: "ALTER TABLE shared_records + ADD COLUMN user_protected INTEGER NOT NULL DEFAULT 0 + CHECK (user_protected IN (0, 1)); + CREATE INDEX shared_records_owner_protection + ON shared_records(owner_key, user_protected, updated_at);", + }, + Migration { + version: 3, + sql: "ALTER TABLE shared_records + ADD COLUMN archived INTEGER NOT NULL DEFAULT 0 + CHECK (archived IN (0, 1)); + CREATE INDEX shared_records_owner_archived + ON shared_records(owner_key, archived, updated_at);", + }, +]; + +const RECORD_COLUMNS: &str = "record_id, dataset_id, category, class, schema_id, schema_version, \ + fields_json, opaque_payload, resource_id, observed_at, received_at, updated_at, expires_at, \ + sequence, source_observation_id, revision, pool_revision, logical_bytes, user_protected, \ + source_plugin_id, source_publisher_fingerprint, source_profile_id, declared_developer, \ + origin, package_version, package_digest, archived"; + +/// Why the shared-data pool could not be used. Messages never contain a path. +#[derive(Debug, thiserror::Error)] +pub enum SharedDataError { + #[error("the shared-data pool could not be opened")] + Open(#[source] std::io::Error), + #[error("the shared-data pool operation failed")] + Database(#[from] rusqlite::Error), + #[error("the shared-data pool was written by a newer version of GameNode")] + NewerVersion, + #[error("the file is not a GameNode shared-data pool")] + ForeignDatabase, + #[error("the shared-data schema migration failed")] + MigrationFailed { version: u32 }, + #[error("invalid shared-data owner scope")] + InvalidOwner, + #[error("invalid shared-data record")] + InvalidRecord, + #[error("the shared-data record exceeds the size limit")] + RecordTooLarge, + #[error("the shared-data owner scope is stale")] + StaleProfileEpoch, + #[error("archived shared data requires an explicit host reuse decision")] + ArchivedRecordExists, + #[error("a publisher migration needs two different owner scopes")] + InvalidMigration, +} + +/// Host-resolved ownership. The opaque key is derived by the host from the authenticated plugin, +/// publisher and profile; the epoch fences operations queued for an earlier profile session. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct OwnerScope { + key: [u8; 32], + profile_epoch: u64, +} + +impl OwnerScope { + pub fn new(key: [u8; 32], profile_epoch: u64) -> Result { + if profile_epoch == 0 || profile_epoch > i64::MAX as u64 { + return Err(SharedDataError::InvalidOwner); + } + Ok(Self { key, profile_epoch }) + } + + fn key(&self) -> &[u8] { + &self.key + } +} + +/// Provenance assigned by the host from the signed producer package and authenticated session. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct RecordProvenance { + pub source_plugin_id: String, + pub source_publisher_fingerprint: String, + pub source_profile_id: String, + pub declared_developer: String, + pub origin: String, + pub package_version: String, + pub package_digest: Vec, +} + +impl RecordProvenance { + fn validate(&self) -> Result<(), SharedDataError> { + for value in [ + &self.source_plugin_id, + &self.source_publisher_fingerprint, + &self.source_profile_id, + &self.declared_developer, + &self.origin, + &self.package_version, + ] { + validate_text(value, MAX_IDENTIFIER_BYTES)?; + } + if self.package_digest.len() != 32 { + return Err(SharedDataError::InvalidRecord); + } + Ok(()) + } +} + +/// One host-validated publication for the durable pool. +pub struct RecordWrite<'a> { + pub dataset_id: &'a str, + pub category: Option, + pub class: &'a str, + pub schema_id: &'a str, + pub schema_version: u32, + /// A non-empty JSON object for structured data, otherwise empty. + pub fields_json: &'a str, + /// Opaque bytes for a binary record, otherwise empty. + pub opaque_payload: &'a [u8], + /// Some for a producer resource that is replaced in place; None appends a new record. + pub resource_id: Option<&'a str>, + pub observed_at: i64, + pub sequence: u64, + pub source_observation_id: &'a str, + /// Unix seconds, already bounded by [`MAX_TTL_SECONDS`] from `now`. + pub expires_at: Option, + /// Unix seconds of the host's receipt. + pub now: i64, + pub provenance: &'a RecordProvenance, + /// Some requires the current record revision; None replaces unconditionally. + pub expected_revision: Option, +} + +/// One durable record as read back. Only logical values are exposed; no path is included. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct SharedRecord { + pub record_id: String, + pub dataset_id: String, + pub category: Option, + pub class: String, + pub schema_id: String, + pub schema_version: u32, + pub fields_json: String, + pub opaque_payload: Vec, + pub resource_id: Option, + pub observed_at: i64, + pub received_at: i64, + pub updated_at: i64, + pub expires_at: Option, + pub sequence: u64, + pub source_observation_id: String, + /// Increments only when this owner/dataset/resource record is replaced. + pub revision: u64, + /// Pool sequence of the latest write to this record. + pub pool_revision: u64, + /// Logical bytes this record is charged. + pub size_bytes: u64, + /// Host-only retention protection; a plugin cannot set it. + pub user_protected: bool, + /// True while the record is retained from an uninstalled producer. Ordinary reads and usage + /// exclude archived rows; a host review restores them or the host deletes them. + pub archived: bool, + pub provenance: RecordProvenance, +} + +/// A stable page of one owner's dataset plus the pool revision it was read at. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct DatasetRecords { + pub records: Vec, + pub pool_revision: u64, +} + +/// The result of a successful write. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct WriteReceipt { + pub record: SharedRecord, + pub replaced: bool, + /// Rows removed by the bounded retention pass that accompanied the write. + pub pruned_records: u64, + pub reclaimed_bytes: u64, +} + +/// The outcome of a publication attempt. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum WriteOutcome { + Stored(Box), + /// The expected record revision did not match. Nothing changed. + Conflict { + current_revision: u64, + }, + /// Even after bounded pruning the owner would exceed its byte limit. Nothing changed. + OverQuota { + usage: OwnerUsage, + }, +} + +/// The result of a bounded prune. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct PruneOutcome { + pub removed_records: u64, + pub reclaimed_bytes: u64, + pub pool_revision: u64, +} + +/// The result of archiving or reusing one owner's retained records. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct ArchiveOutcome { + /// Rows whose archived flag actually changed. + pub records: u64, + pub pool_revision: u64, +} + +/// User-selected limits. `None` leaves that dimension at the host default: no age limit and +/// [`MAX_OWNER_LOGICAL_BYTES`] for size. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct RetentionPolicy { + pub max_age_seconds: Option, + pub max_bytes: Option, +} + +/// Logical usage of one owner. `max_bytes` and `max_age_seconds` are the effective limits. +/// +/// `records` and `logical_bytes` count only rows visible to ordinary reads and quota. Archived +/// rows retained for an uninstalled producer are reported separately and are never pruned +/// automatically. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct OwnerUsage { + pub records: u64, + pub logical_bytes: u64, + pub max_bytes: u64, + pub max_age_seconds: Option, + pub oldest_updated_at: Option, + pub archived_records: u64, + pub archived_logical_bytes: u64, + /// Live records the user protected from pruning. + pub protected_records: u64, + /// SQLite page allocation for the whole pool; shared across owners. + pub physical_bytes_estimate: u64, +} + +/// One owner's live records as a reviewed publisher migration sees them: logical metadata only, +/// never a payload or a path. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct RecordMetadata { + pub record_id: String, + pub dataset_id: String, + pub resource_id: Option, + pub class: String, + pub schema_id: String, + pub schema_version: u32, + pub observed_at: i64, + pub received_at: i64, + pub updated_at: i64, + pub expires_at: Option, + pub sequence: u64, + pub size_bytes: u64, + pub user_protected: bool, +} + +/// Everything the old publisher identity holds in the durable pool for one migration preview. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct MigrationSource { + /// Live, unexpired records; archived and expired rows are only counted. + pub records: Vec, + pub expired_records: u64, + pub archived_records: u64, + pub logical_bytes: u64, +} + +/// One record copied into the new publisher identity. Provenance keeps the original source. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct MigratedRecord { + pub source_record_id: String, + pub record_id: String, + pub dataset_id: String, + pub resource_id: Option, + pub schema_id: String, + pub schema_version: u32, + pub size_bytes: u64, +} + +/// Why one candidate record was not copied. Nothing changed for it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct MigrationSkip { + pub source_record_id: String, + pub dataset_id: String, + pub resource_id: Option, + /// `conflict` or `over_quota`. + pub reason: String, +} + +/// The result of copying one old publisher identity's records to its successor. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct MigrationOutcome { + pub copied: Vec, + pub skipped: Vec, + pub pool_revision: u64, +} + +/// The result of removing one migration's copies. The old identity's rows stay. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct MigrationRevertOutcome { + pub removed_records: u64, + pub reclaimed_bytes: u64, + /// Copies the user protected since the migration; rollback keeps them. + pub kept_protected_records: u64, + pub pool_revision: u64, +} + +/// The host-owned durable public pool. +pub struct SharedDataStore { + conn: Connection, +} + +impl SharedDataStore { + /// Opens the pool below `data_dir`, creating the directory, file and schema on first use. + /// Blocking: call this on the storage worker. + pub fn open(data_dir: &Path) -> Result { + Self::open_with(data_dir, MIGRATIONS) + } + + /// Opens an existing pool without creating anything; `None` when this host never persisted a + /// shared record. + pub fn open_existing(data_dir: &Path) -> Result, SharedDataError> { + Self::migrate_legacy_name(data_dir)?; + if !data_dir.join(FILE_NAME).is_file() { + return Ok(None); + } + Self::open(data_dir).map(Some) + } + + /// Renames a pre-release `plugin-shared-data.sqlite3` pool, including its WAL sidecars, before + /// the new name is opened. A failed rename is an error instead of silently starting empty. + fn migrate_legacy_name(data_dir: &Path) -> Result<(), SharedDataError> { + let current = data_dir.join(FILE_NAME); + let legacy = data_dir.join(LEGACY_FILE_NAME); + if current.exists() || !legacy.is_file() { + return Ok(()); + } + fs::rename(&legacy, ¤t).map_err(SharedDataError::Open)?; + for suffix in ["-wal", "-shm"] { + let from = data_dir.join(format!("{LEGACY_FILE_NAME}{suffix}")); + if from.is_file() { + fs::rename(&from, data_dir.join(format!("{FILE_NAME}{suffix}"))) + .map_err(SharedDataError::Open)?; + } + } + Ok(()) + } + + fn open_with(data_dir: &Path, migrations: &[Migration]) -> Result { + Self::migrate_legacy_name(data_dir)?; + fs::create_dir_all(data_dir).map_err(SharedDataError::Open)?; + let mut conn = Connection::open(data_dir.join(FILE_NAME))?; + conn.busy_timeout(std::time::Duration::from_secs(5))?; + + // Read the guard before any pragma that could write, so a newer database stays untouched. + let supported = migrations.last().map_or(0, |migration| migration.version) as i64; + let version: i64 = conn.query_row("PRAGMA user_version", [], |row| row.get(0))?; + if version > supported { + return Err(SharedDataError::NewerVersion); + } + if version == 0 { + let tables: i64 = conn.query_row( + "SELECT COUNT(*) FROM sqlite_master WHERE name NOT LIKE 'sqlite_%'", + [], + |row| row.get(0), + )?; + if tables > 0 { + return Err(SharedDataError::ForeignDatabase); + } + } + + for (index, migration) in migrations.iter().enumerate() { + if migration.version != index as u32 + 1 { + return Err(SharedDataError::MigrationFailed { + version: migration.version, + }); + } + } + + conn.execute_batch( + "PRAGMA journal_mode = WAL; + PRAGMA synchronous = NORMAL; + PRAGMA foreign_keys = ON;", + )?; + for migration in migrations + .iter() + .filter(|migration| migration.version as i64 > version) + { + apply( + conn.transaction_with_behavior(TransactionBehavior::Immediate)?, + migration, + ) + .map_err(|_| SharedDataError::MigrationFailed { + version: migration.version, + })?; + } + Ok(Self { conn }) + } + + /// The current pool revision. It only grows and survives restarts. + pub fn pool_revision(&self) -> Result { + let revision: i64 = self.conn.query_row( + "SELECT revision FROM shared_state WHERE id = 1", + [], + |row| row.get(0), + )?; + Ok(revision.max(0) as u64) + } + + /// Stores a publication, replacing the owner's record for the same dataset and resource. + pub fn write( + &mut self, + owner: OwnerScope, + write: RecordWrite<'_>, + ) -> Result { + validate_write(&write)?; + write.provenance.validate()?; + let charge = record_charge(&write)?; + let tx = self + .conn + .transaction_with_behavior(TransactionBehavior::Immediate)?; + check_owner(&tx, &owner, write.now, true)?; + + let existing = match write.resource_id { + Some(resource_id) => tx + .query_row( + "SELECT record_id, revision, archived FROM shared_records + WHERE owner_key = ?1 AND dataset_id = ?2 AND resource_id = ?3", + params![owner.key(), write.dataset_id, resource_id], + |row| { + Ok(ExistingRecord { + record_id: row.get(0)?, + revision: row.get::<_, i64>(1)?.max(0) as u64, + archived: row.get::<_, i64>(2)? != 0, + }) + }, + ) + .optional()?, + None => None, + }; + // A producer that was uninstalled with retained data, then reinstalled, must not replace + // an archived row before the host reviews reuse. Refuse the write without changing it. + if existing.as_ref().is_some_and(|record| record.archived) { + return Err(SharedDataError::ArchivedRecordExists); + } + let current_revision = existing.as_ref().map_or(0, |record| record.revision); + if let Some(expected) = write.expected_revision + && expected != current_revision + { + return Ok(WriteOutcome::Conflict { current_revision }); + } + + let usage_before = owner_usage(&tx, &owner, write.now)?; + let mut pruned = PruneProgress::default(); + prune_expired(&tx, &owner, write.now, &mut pruned)?; + prune_aged(&tx, &owner, write.now, &mut pruned)?; + + let keep_id = existing.as_ref().map(|record| record.record_id.as_str()); + let mut live_bytes = usage_excluding(&tx, &owner, write.now, keep_id)?; + while live_bytes.saturating_add(charge) > usage_before.max_bytes + && pruned.records < MAX_PRUNE_ROWS + { + let Some(victim) = oldest_unprotected(&tx, &owner, write.now, keep_id)? else { + break; + }; + delete_record(&tx, &victim)?; + pruned.records += 1; + pruned.bytes = pruned.bytes.saturating_add(victim.size_bytes); + live_bytes = live_bytes.saturating_sub(victim.size_bytes); + } + if live_bytes.saturating_add(charge) > usage_before.max_bytes { + return Ok(WriteOutcome::OverQuota { + usage: usage_before, + }); + } + + let pool_revision = advance_pool(&tx)?; + // Durable ids use their own prefix so they can never collide with the in-memory broker's + // `shared-` ids, which are numbered in a separate sequence. + let record_id = existing.as_ref().map_or_else( + || format!("durable-{pool_revision:016x}"), + |record| record.record_id.clone(), + ); + let revision = current_revision.saturating_add(1); + if let Some(existing) = &existing { + tx.execute( + "UPDATE shared_records SET + dataset_id = ?2, resource_id = ?3, category = ?4, class = ?5, + schema_id = ?6, schema_version = ?7, fields_json = ?8, + opaque_payload = ?9, source_plugin_id = ?10, + source_publisher_fingerprint = ?11, source_profile_id = ?12, + declared_developer = ?13, origin = ?14, package_version = ?15, + package_digest = ?16, observed_at = ?17, updated_at = ?18, + expires_at = ?19, sequence = ?20, source_observation_id = ?21, + revision = ?22, pool_revision = ?23, logical_bytes = ?24 + WHERE owner_key = ?25 AND record_id = ?1", + params![ + existing.record_id, + write.dataset_id, + write.resource_id, + write.category, + write.class, + write.schema_id, + i64::from(write.schema_version), + write.fields_json, + write.opaque_payload, + write.provenance.source_plugin_id, + write.provenance.source_publisher_fingerprint, + write.provenance.source_profile_id, + write.provenance.declared_developer, + write.provenance.origin, + write.provenance.package_version, + write.provenance.package_digest, + write.observed_at, + write.now, + write.expires_at, + write.sequence as i64, + write.source_observation_id, + revision as i64, + pool_revision as i64, + charge as i64, + owner.key(), + ], + )?; + } else { + tx.execute( + "INSERT INTO shared_records + (record_id, owner_key, dataset_id, resource_id, category, class, + schema_id, schema_version, fields_json, opaque_payload, + source_plugin_id, source_publisher_fingerprint, source_profile_id, + declared_developer, origin, package_version, package_digest, + observed_at, received_at, updated_at, expires_at, sequence, + source_observation_id, revision, pool_revision, logical_bytes) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, + ?16, ?17, ?18, ?19, ?19, ?20, ?21, ?22, ?23, ?24, ?25)", + params![ + record_id, + owner.key(), + write.dataset_id, + write.resource_id, + write.category, + write.class, + write.schema_id, + i64::from(write.schema_version), + write.fields_json, + write.opaque_payload, + write.provenance.source_plugin_id, + write.provenance.source_publisher_fingerprint, + write.provenance.source_profile_id, + write.provenance.declared_developer, + write.provenance.origin, + write.provenance.package_version, + write.provenance.package_digest, + write.observed_at, + write.now, + write.expires_at, + write.sequence as i64, + write.source_observation_id, + revision as i64, + pool_revision as i64, + charge as i64, + ], + )?; + } + let record = record_by_id(&tx, &owner, &record_id, write.now)? + .ok_or(SharedDataError::InvalidRecord)?; + tx.commit()?; + Ok(WriteOutcome::Stored(Box::new(WriteReceipt { + record, + replaced: existing.is_some(), + pruned_records: pruned.records, + reclaimed_bytes: pruned.bytes, + }))) + } + + /// Reads one unexpired record only inside this owner scope. + pub fn get( + &self, + owner: &OwnerScope, + record_id: &str, + now: i64, + ) -> Result, SharedDataError> { + validate_now(now)?; + validate_text(record_id, 64)?; + check_owner(&self.conn, owner, now, false)?; + record_by_id(&self.conn, owner, record_id, now) + } + + /// Reads one unexpired record by host id across every owner. This is a host-only read for the + /// public read path: the caller must authorize the returned source identity against the + /// current grant before disclosing any field. Record ids are globally unique. + pub fn get_any( + &self, + record_id: &str, + now: i64, + ) -> Result, SharedDataError> { + validate_now(now)?; + validate_text(record_id, 64)?; + Ok(self + .conn + .query_row( + &format!( + "SELECT {RECORD_COLUMNS} FROM shared_records + WHERE record_id = ?1 AND archived = 0 + AND (expires_at IS NULL OR expires_at > ?2)" + ), + params![record_id, now], + record_from, + ) + .optional()?) + } + + /// Lists one dataset's unexpired records across every owner in the same stable order as the + /// owner-scoped list. Host-only: the public read path authorizes each record's source identity + /// against the current grant before disclosing it. + pub fn list_dataset_any( + &self, + dataset_id: &str, + now: i64, + ) -> Result, SharedDataError> { + validate_now(now)?; + validate_text(dataset_id, MAX_IDENTIFIER_BYTES)?; + let mut statement = self.conn.prepare(&format!( + "SELECT {RECORD_COLUMNS} FROM shared_records + WHERE dataset_id = ?1 AND archived = 0 + AND (expires_at IS NULL OR expires_at > ?2) + ORDER BY received_at ASC, record_id ASC" + ))?; + statement + .query_map(params![dataset_id, now], record_from)? + .collect::, _>>() + .map_err(Into::into) + } + + /// Lists one owner's dataset in a stable order (oldest receipt first, then record id) and + /// returns the pool revision at which the page was read. + pub fn list_dataset( + &self, + owner: &OwnerScope, + dataset_id: &str, + now: i64, + ) -> Result { + validate_now(now)?; + validate_text(dataset_id, MAX_IDENTIFIER_BYTES)?; + check_owner(&self.conn, owner, now, false)?; + let mut statement = self.conn.prepare(&format!( + "SELECT {RECORD_COLUMNS} FROM shared_records + WHERE owner_key = ?1 AND dataset_id = ?2 AND archived = 0 + AND (expires_at IS NULL OR expires_at > ?3) + ORDER BY received_at ASC, record_id ASC" + ))?; + let records = statement + .query_map(params![owner.key(), dataset_id, now], record_from)? + .collect::, _>>()?; + Ok(DatasetRecords { + records, + pool_revision: self.pool_revision()?, + }) + } + + /// Logical usage and effective limits of one owner. Expired rows are not counted. + pub fn usage(&self, owner: &OwnerScope, now: i64) -> Result { + validate_now(now)?; + check_owner(&self.conn, owner, now, false)?; + owner_usage(&self.conn, owner, now) + } + + /// Sets the owner's age/byte limits and immediately runs a bounded prune. + pub fn set_retention( + &mut self, + owner: &OwnerScope, + policy: RetentionPolicy, + now: i64, + ) -> Result { + validate_now(now)?; + if policy + .max_age_seconds + .is_some_and(|age| age == 0 || age > MAX_RETENTION_AGE_SECONDS) + || policy + .max_bytes + .is_some_and(|bytes| bytes == 0 || bytes > MAX_OWNER_LOGICAL_BYTES) + { + return Err(SharedDataError::InvalidRecord); + } + let tx = self + .conn + .transaction_with_behavior(TransactionBehavior::Immediate)?; + check_owner(&tx, owner, now, true)?; + tx.execute( + "INSERT INTO shared_retention + (owner_key, max_age_seconds, max_bytes, updated_at) + VALUES (?1, ?2, ?3, ?4) + ON CONFLICT(owner_key) DO UPDATE SET + max_age_seconds = excluded.max_age_seconds, + max_bytes = excluded.max_bytes, + updated_at = excluded.updated_at", + params![ + owner.key(), + policy.max_age_seconds.map(|age| age as i64), + policy.max_bytes.map(|bytes| bytes as i64), + now + ], + )?; + let (pruned, removed) = prune_owner(&tx, owner, now)?; + let pool_revision = if removed { + advance_pool(&tx)? + } else { + current_pool_revision(&tx)? + }; + tx.commit()?; + Ok(PruneOutcome { + removed_records: pruned.records, + reclaimed_bytes: pruned.bytes, + pool_revision, + }) + } + + /// Expires and prunes this owner only, expired first, then age, then the oldest unprotected + /// rows until the byte limit is met or [`MAX_PRUNE_ROWS`] is reached. + pub fn prune(&mut self, owner: &OwnerScope, now: i64) -> Result { + validate_now(now)?; + let tx = self + .conn + .transaction_with_behavior(TransactionBehavior::Immediate)?; + check_owner(&tx, owner, now, true)?; + let (pruned, removed) = prune_owner(&tx, owner, now)?; + let pool_revision = if removed { + advance_pool(&tx)? + } else { + current_pool_revision(&tx)? + }; + tx.commit()?; + Ok(PruneOutcome { + removed_records: pruned.records, + reclaimed_bytes: pruned.bytes, + pool_revision, + }) + } + + /// Removes every durable record of one owner and reports the bytes actually reclaimed. + /// + /// This is the host's user-initiated cleanup: it removes retained public records without + /// uninstalling the producer, including protected and expired rows. Another owner's records, + /// the owner's retention policy and the private `plugin-data` stores are untouched. Blocking: + /// call this on the storage worker. + pub fn delete_owner( + &mut self, + owner: &OwnerScope, + now: i64, + ) -> Result { + validate_now(now)?; + let tx = self + .conn + .transaction_with_behavior(TransactionBehavior::Immediate)?; + check_owner(&tx, owner, now, false)?; + let (records, bytes): (i64, i64) = tx.query_row( + "SELECT COUNT(*), COALESCE(SUM(logical_bytes), 0) FROM shared_records + WHERE owner_key = ?1", + [owner.key()], + |row| Ok((row.get(0)?, row.get(1)?)), + )?; + if records > 0 { + tx.execute( + "DELETE FROM shared_records WHERE owner_key = ?1", + [owner.key()], + )?; + let pool_revision = advance_pool(&tx)?; + tx.commit()?; + return Ok(PruneOutcome { + removed_records: records.max(0) as u64, + reclaimed_bytes: bytes.max(0) as u64, + pool_revision, + }); + } + let pool_revision = current_pool_revision(&tx)?; + tx.commit()?; + Ok(PruneOutcome { + removed_records: 0, + reclaimed_bytes: 0, + pool_revision, + }) + } + + /// Reads one owner's live records and the counts of rows that a migration cannot copy, without + /// loading or disclosing a payload. Host-only: the caller binds the owner from authenticated + /// identity. Blocking: call this on the storage worker. + pub fn migration_source( + &self, + owner: &OwnerScope, + now: i64, + ) -> Result { + validate_now(now)?; + check_owner(&self.conn, owner, now, false)?; + let (expired_records, archived_records, logical_bytes): (i64, i64, i64) = + self.conn.query_row( + "SELECT + COALESCE(SUM(CASE WHEN archived = 0 AND expires_at IS NOT NULL + AND expires_at <= ?2 THEN 1 ELSE 0 END), 0), + COALESCE(SUM(CASE WHEN archived = 1 THEN 1 ELSE 0 END), 0), + COALESCE(SUM(CASE WHEN archived = 0 + AND (expires_at IS NULL OR expires_at > ?2) + THEN logical_bytes ELSE 0 END), 0) + FROM shared_records WHERE owner_key = ?1", + params![owner.key(), now], + |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)), + )?; + let mut statement = self.conn.prepare(&format!( + "SELECT {RECORD_COLUMNS} FROM shared_records + WHERE owner_key = ?1 AND archived = 0 + AND (expires_at IS NULL OR expires_at > ?2) + ORDER BY dataset_id ASC, received_at ASC, record_id ASC" + ))?; + let records = statement + .query_map(params![owner.key(), now], record_from)? + .map(|record| record.map(metadata_from)) + .collect::, _>>()?; + Ok(MigrationSource { + records, + expired_records: expired_records.max(0) as u64, + archived_records: archived_records.max(0) as u64, + logical_bytes: logical_bytes.max(0) as u64, + }) + } + + /// Copies one owner's live records to another owner after a reviewed publisher re-trust. + /// + /// This is the host's migration, never a plugin route. Provenance keeps the original source + /// identity and package version, and the old owner's rows stay untouched. A record whose + /// dataset and resource already exist on the new owner is skipped as a conflict, and a record + /// that would exceed the new owner's byte limit is skipped as over quota; neither changes + /// anything. One transaction covers every copy. Blocking: call this on the storage worker. + pub fn migrate_records( + &mut self, + source: &OwnerScope, + target: &OwnerScope, + record_ids: &[String], + now: i64, + ) -> Result { + validate_now(now)?; + if source.key() == target.key() { + return Err(SharedDataError::InvalidMigration); + } + let selected: std::collections::BTreeSet<&str> = + record_ids.iter().map(String::as_str).collect(); + let tx = self + .conn + .transaction_with_behavior(TransactionBehavior::Immediate)?; + let records = records_for_owner(&tx, source, now)? + .into_iter() + .filter(|record| selected.contains(record.record_id.as_str())) + .collect::>(); + let max_bytes = effective_max_bytes(retention_policy(&tx, target)?); + let mut usage = usage_excluding(&tx, target, now, None)?; + // Creating the successor owner row only happens on the confirmed mutation. + check_owner(&tx, target, now, true)?; + let mut outcome = MigrationOutcome { + copied: Vec::new(), + skipped: Vec::new(), + pool_revision: 0, + }; + for record in records { + if record.resource_id.is_some() && resource_exists(&tx, target, &record)? { + outcome.skipped.push(MigrationSkip { + source_record_id: record.record_id, + dataset_id: record.dataset_id, + resource_id: record.resource_id, + reason: "conflict".to_owned(), + }); + continue; + } + if usage.saturating_add(record.size_bytes) > max_bytes { + outcome.skipped.push(MigrationSkip { + source_record_id: record.record_id, + dataset_id: record.dataset_id, + resource_id: record.resource_id, + reason: "over_quota".to_owned(), + }); + continue; + } + let pool_revision = advance_pool(&tx)?; + let record_id = format!("durable-{pool_revision:016x}"); + insert_migrated_record(&tx, target, &record_id, &record, pool_revision, now)?; + usage = usage.saturating_add(record.size_bytes); + outcome.copied.push(MigratedRecord { + source_record_id: record.record_id, + record_id, + dataset_id: record.dataset_id, + resource_id: record.resource_id, + schema_id: record.schema_id, + schema_version: record.schema_version, + size_bytes: record.size_bytes, + }); + outcome.pool_revision = pool_revision; + } + if outcome.pool_revision == 0 { + outcome.pool_revision = current_pool_revision(&tx)?; + } + tx.commit()?; + Ok(outcome) + } + + /// Removes one migration's copies from the new publisher identity after a reviewed rollback. + /// + /// A copy is identified by the original provenance the migration preserved, so the new + /// identity's own publications are never touched, and the old identity's rows are never + /// touched either. A copy the user protected since the migration stays. Blocking: call this on + /// the storage worker. + pub fn revert_migrated( + &mut self, + target: &OwnerScope, + source_publisher_fingerprint: &str, + source_plugin_id: &str, + now: i64, + ) -> Result { + validate_now(now)?; + validate_text(source_publisher_fingerprint, MAX_IDENTIFIER_BYTES)?; + validate_text(source_plugin_id, MAX_IDENTIFIER_BYTES)?; + let tx = self + .conn + .transaction_with_behavior(TransactionBehavior::Immediate)?; + check_owner(&tx, target, now, false)?; + let (records, bytes): (i64, i64) = tx.query_row( + "SELECT COUNT(*), COALESCE(SUM(logical_bytes), 0) FROM shared_records + WHERE owner_key = ?1 AND source_publisher_fingerprint = ?2 + AND source_plugin_id = ?3 AND user_protected = 0", + params![target.key(), source_publisher_fingerprint, source_plugin_id], + |row| Ok((row.get(0)?, row.get(1)?)), + )?; + let removed = tx.execute( + "DELETE FROM shared_records + WHERE owner_key = ?1 AND source_publisher_fingerprint = ?2 + AND source_plugin_id = ?3 AND user_protected = 0", + params![target.key(), source_publisher_fingerprint, source_plugin_id], + )? as u64; + let kept: i64 = tx.query_row( + "SELECT COUNT(*) FROM shared_records + WHERE owner_key = ?1 AND source_publisher_fingerprint = ?2 + AND source_plugin_id = ?3 AND user_protected = 1", + params![target.key(), source_publisher_fingerprint, source_plugin_id], + |row| row.get(0), + )?; + let pool_revision = if removed > 0 { + advance_pool(&tx)? + } else { + current_pool_revision(&tx)? + }; + tx.commit()?; + Ok(MigrationRevertOutcome { + removed_records: records.max(0) as u64, + reclaimed_bytes: bytes.max(0) as u64, + kept_protected_records: kept.max(0) as u64, + pool_revision, + }) + } + + /// Makes every record of one owner inert for uninstall retention. + /// + /// Archived rows stay attributed to the original owner and on disk, but ordinary reads, + /// lists and usage skip them, automatic retention never prunes them and a producer cannot + /// replace an archived resource record. A later install needs the separate host reuse review. + /// Blocking: call this on the storage worker. + pub fn archive_owner( + &mut self, + owner: &OwnerScope, + now: i64, + ) -> Result { + validate_now(now)?; + let tx = self + .conn + .transaction_with_behavior(TransactionBehavior::Immediate)?; + check_owner(&tx, owner, now, false)?; + let archived = tx.execute( + "UPDATE shared_records SET archived = 1 + WHERE owner_key = ?1 AND archived = 0", + [owner.key()], + )? as u64; + let pool_revision = if archived > 0 { + advance_pool(&tx)? + } else { + current_pool_revision(&tx)? + }; + tx.commit()?; + Ok(ArchiveOutcome { + records: archived, + pool_revision, + }) + } + + /// Restores one owner's archived records after an explicit host review. + /// + /// This is the only way retained records become visible again. It never touches another + /// owner. Blocking: call this on the storage worker. + pub fn reuse_archived_owner( + &mut self, + owner: &OwnerScope, + now: i64, + ) -> Result { + validate_now(now)?; + let tx = self + .conn + .transaction_with_behavior(TransactionBehavior::Immediate)?; + check_owner(&tx, owner, now, false)?; + let reused = tx.execute( + "UPDATE shared_records SET archived = 0 + WHERE owner_key = ?1 AND archived = 1", + [owner.key()], + )? as u64; + let pool_revision = if reused > 0 { + advance_pool(&tx)? + } else { + current_pool_revision(&tx)? + }; + tx.commit()?; + Ok(ArchiveOutcome { + records: reused, + pool_revision, + }) + } + + /// Reclaims one owner's archived, unprotected rows in a reviewed host cleanup. A protected + /// archived row stays. Blocking: call this on the storage worker. + pub fn reclaim_archived_owner( + &mut self, + owner: &OwnerScope, + ) -> Result { + let tx = self + .conn + .transaction_with_behavior(TransactionBehavior::Immediate)?; + check_owner(&tx, owner, 0, false)?; + let (records, bytes): (i64, i64) = tx.query_row( + "SELECT COUNT(*), COALESCE(SUM(logical_bytes), 0) FROM shared_records + WHERE owner_key = ?1 AND archived = 1 AND user_protected = 0", + [owner.key()], + |row| Ok((row.get(0)?, row.get(1)?)), + )?; + let removed = tx.execute( + "DELETE FROM shared_records + WHERE owner_key = ?1 AND archived = 1 AND user_protected = 0", + [owner.key()], + )? as u64; + let pool_revision = if removed > 0 { + advance_pool(&tx)? + } else { + current_pool_revision(&tx)? + }; + tx.commit()?; + Ok(PruneOutcome { + removed_records: records.max(0) as u64, + reclaimed_bytes: bytes.max(0) as u64, + pool_revision, + }) + } + + /// Marks a record as protected from retention pruning, or releases it. Host-only: no plugin + /// request reaches this method. It never changes the payload or the record revision. + pub fn set_user_protected( + &mut self, + owner: &OwnerScope, + record_id: &str, + protected: bool, + now: i64, + ) -> Result { + validate_now(now)?; + validate_text(record_id, 64)?; + let tx = self + .conn + .transaction_with_behavior(TransactionBehavior::Immediate)?; + check_owner(&tx, owner, now, true)?; + let changed = tx.execute( + "UPDATE shared_records SET user_protected = ?3 + WHERE owner_key = ?1 AND record_id = ?2 AND user_protected != ?3", + params![owner.key(), record_id, protected], + )?; + if changed > 0 { + advance_pool(&tx)?; + } + tx.commit()?; + Ok(changed > 0) + } +} + +#[derive(Clone, Debug)] +struct ExistingRecord { + record_id: String, + revision: u64, + archived: bool, +} + +#[derive(Clone, Debug)] +struct Victim { + record_id: String, + size_bytes: u64, +} + +#[derive(Clone, Copy, Debug, Default)] +struct PruneProgress { + records: u64, + bytes: u64, +} + +fn apply(tx: rusqlite::Transaction<'_>, migration: &Migration) -> rusqlite::Result<()> { + tx.execute_batch(migration.sql)?; + tx.pragma_update(None, "user_version", migration.version)?; + tx.commit() +} + +fn validate_write(write: &RecordWrite<'_>) -> Result<(), SharedDataError> { + validate_now(write.now)?; + validate_text(write.dataset_id, MAX_IDENTIFIER_BYTES)?; + validate_text(write.schema_id, MAX_IDENTIFIER_BYTES)?; + validate_text(write.class, MAX_CLASS_BYTES)?; + // A producer observation id is optional without a sequence, matching the session broker. + if !write.source_observation_id.is_empty() { + validate_text(write.source_observation_id, MAX_IDENTIFIER_BYTES)?; + } + if let Some(resource_id) = write.resource_id { + validate_text(resource_id, MAX_IDENTIFIER_BYTES)?; + } + if write.schema_version == 0 || write.category.is_some_and(|category| category < 0) { + return Err(SharedDataError::InvalidRecord); + } + if write.observed_at < 0 { + return Err(SharedDataError::InvalidRecord); + } + let structured = !write.fields_json.is_empty(); + let opaque = !write.opaque_payload.is_empty(); + if structured == opaque { + return Err(SharedDataError::InvalidRecord); + } + if write + .fields_json + .len() + .saturating_add(write.opaque_payload.len()) + > MAX_RECORD_BYTES + { + return Err(SharedDataError::RecordTooLarge); + } + if structured { + let fields: serde_json::Map = + serde_json::from_str(write.fields_json).map_err(|_| SharedDataError::InvalidRecord)?; + if fields.is_empty() { + return Err(SharedDataError::InvalidRecord); + } + } + if let Some(expires_at) = write.expires_at + && (expires_at <= write.now + || expires_at.saturating_sub(write.now) > MAX_TTL_SECONDS as i64) + { + return Err(SharedDataError::InvalidRecord); + } + Ok(()) +} + +fn validate_now(now: i64) -> Result<(), SharedDataError> { + if now <= 0 { + return Err(SharedDataError::InvalidRecord); + } + Ok(()) +} + +fn validate_text(value: &str, max_bytes: usize) -> Result<(), SharedDataError> { + if value.is_empty() || value.len() > max_bytes || value.chars().any(char::is_control) { + return Err(SharedDataError::InvalidRecord); + } + Ok(()) +} + +fn record_charge(write: &RecordWrite<'_>) -> Result { + if write.sequence > i64::MAX as u64 { + return Err(SharedDataError::InvalidRecord); + } + let provenance = write.provenance; + let bytes = write.dataset_id.len() as u64 + + write.class.len() as u64 + + write.schema_id.len() as u64 + + write.resource_id.map_or(0, |id| id.len() as u64) + + write.source_observation_id.len() as u64 + + write.fields_json.len() as u64 + + write.opaque_payload.len() as u64 + + provenance.source_plugin_id.len() as u64 + + provenance.source_publisher_fingerprint.len() as u64 + + provenance.source_profile_id.len() as u64 + + provenance.declared_developer.len() as u64 + + provenance.origin.len() as u64 + + provenance.package_version.len() as u64 + + provenance.package_digest.len() as u64 + + RECORD_OVERHEAD_BYTES; + Ok(bytes) +} + +/// Checks the owner generation. A lower epoch is stale and fails closed; a higher epoch is the +/// current profile session and may advance the stored generation on a write. +fn check_owner( + conn: &Connection, + owner: &OwnerScope, + now: i64, + advance: bool, +) -> Result<(), SharedDataError> { + let stored: Option = conn + .query_row( + "SELECT profile_epoch FROM shared_owners WHERE owner_key = ?1", + [owner.key()], + |row| row.get(0), + ) + .optional()?; + match stored { + Some(stored) if owner.profile_epoch < stored as u64 => { + Err(SharedDataError::StaleProfileEpoch) + } + Some(stored) if advance && owner.profile_epoch > stored as u64 => { + conn.execute( + "UPDATE shared_owners SET profile_epoch = ?2, updated_at = ?3 + WHERE owner_key = ?1", + params![owner.key(), owner.profile_epoch as i64, now], + )?; + Ok(()) + } + Some(_) => Ok(()), + None if advance => { + conn.execute( + "INSERT INTO shared_owners (owner_key, profile_epoch, updated_at) + VALUES (?1, ?2, ?3)", + params![owner.key(), owner.profile_epoch as i64, now], + )?; + Ok(()) + } + None => Ok(()), + } +} + +fn retention_policy( + conn: &Connection, + owner: &OwnerScope, +) -> Result { + let row: Option<(Option, Option)> = conn + .query_row( + "SELECT max_age_seconds, max_bytes FROM shared_retention WHERE owner_key = ?1", + [owner.key()], + |row| Ok((row.get(0)?, row.get(1)?)), + ) + .optional()?; + let (max_age_seconds, max_bytes) = row.unwrap_or((None, None)); + Ok(RetentionPolicy { + max_age_seconds: max_age_seconds.and_then(|age| u64::try_from(age).ok()), + max_bytes: max_bytes.and_then(|bytes| u64::try_from(bytes).ok()), + }) +} + +fn effective_max_bytes(policy: RetentionPolicy) -> u64 { + policy + .max_bytes + .unwrap_or(MAX_OWNER_LOGICAL_BYTES) + .min(MAX_OWNER_LOGICAL_BYTES) +} + +fn owner_usage( + conn: &Connection, + owner: &OwnerScope, + now: i64, +) -> Result { + let policy = retention_policy(conn, owner)?; + let (records, logical_bytes, oldest_updated_at, protected_records): ( + i64, + i64, + Option, + i64, + ) = conn.query_row( + "SELECT COUNT(*), COALESCE(SUM(logical_bytes), 0), MIN(updated_at), + COALESCE(SUM(user_protected), 0) + FROM shared_records + WHERE owner_key = ?1 AND archived = 0 + AND (expires_at IS NULL OR expires_at > ?2)", + params![owner.key(), now], + |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?)), + )?; + let (archived_records, archived_logical_bytes): (i64, i64) = conn.query_row( + "SELECT COUNT(*), COALESCE(SUM(logical_bytes), 0) + FROM shared_records + WHERE owner_key = ?1 AND archived = 1 + AND (expires_at IS NULL OR expires_at > ?2)", + params![owner.key(), now], + |row| Ok((row.get(0)?, row.get(1)?)), + )?; + let page_count: i64 = conn.query_row("PRAGMA page_count", [], |row| row.get(0))?; + let page_size: i64 = conn.query_row("PRAGMA page_size", [], |row| row.get(0))?; + Ok(OwnerUsage { + records: records.max(0) as u64, + logical_bytes: logical_bytes.max(0) as u64, + max_bytes: effective_max_bytes(policy), + max_age_seconds: policy.max_age_seconds, + oldest_updated_at, + archived_records: archived_records.max(0) as u64, + archived_logical_bytes: archived_logical_bytes.max(0) as u64, + protected_records: protected_records.max(0) as u64, + physical_bytes_estimate: page_count.max(0) as u64 * page_size.max(0) as u64, + }) +} + +fn usage_excluding( + conn: &Connection, + owner: &OwnerScope, + now: i64, + except: Option<&str>, +) -> Result { + let bytes: i64 = conn.query_row( + "SELECT COALESCE(SUM(logical_bytes), 0) FROM shared_records + WHERE owner_key = ?1 AND archived = 0 + AND (expires_at IS NULL OR expires_at > ?2) + AND (?3 IS NULL OR record_id != ?3)", + params![owner.key(), now, except], + |row| row.get(0), + )?; + Ok(bytes.max(0) as u64) +} + +fn prune_expired( + conn: &Connection, + owner: &OwnerScope, + now: i64, + pruned: &mut PruneProgress, +) -> Result<(), SharedDataError> { + let limit = MAX_PRUNE_ROWS.saturating_sub(pruned.records); + if limit == 0 { + return Ok(()); + } + let victims = victims( + conn, + "SELECT record_id, logical_bytes FROM shared_records + WHERE owner_key = ?1 AND user_protected = 0 AND archived = 0 + AND expires_at IS NOT NULL AND expires_at <= ?2 + ORDER BY expires_at ASC, updated_at ASC, record_id ASC LIMIT ?3", + params![owner.key(), now, limit as i64], + )?; + delete_victims(conn, victims, pruned) +} + +fn prune_aged( + conn: &Connection, + owner: &OwnerScope, + now: i64, + pruned: &mut PruneProgress, +) -> Result<(), SharedDataError> { + let limit = MAX_PRUNE_ROWS.saturating_sub(pruned.records); + if limit == 0 { + return Ok(()); + } + let Some(max_age) = retention_policy(conn, owner)?.max_age_seconds else { + return Ok(()); + }; + let cutoff = now.saturating_sub(max_age.min(i64::MAX as u64) as i64); + let victims = victims( + conn, + "SELECT record_id, logical_bytes FROM shared_records + WHERE owner_key = ?1 AND user_protected = 0 AND archived = 0 AND updated_at <= ?2 + ORDER BY updated_at ASC, received_at ASC, record_id ASC LIMIT ?3", + params![owner.key(), cutoff, limit as i64], + )?; + delete_victims(conn, victims, pruned) +} + +fn oldest_unprotected( + conn: &Connection, + owner: &OwnerScope, + now: i64, + except: Option<&str>, +) -> Result, SharedDataError> { + Ok(conn + .query_row( + "SELECT record_id, logical_bytes FROM shared_records + WHERE owner_key = ?1 AND user_protected = 0 AND archived = 0 + AND (expires_at IS NULL OR expires_at > ?2) + AND (?3 IS NULL OR record_id != ?3) + ORDER BY updated_at ASC, received_at ASC, record_id ASC LIMIT 1", + params![owner.key(), now, except], + |row| { + Ok(Victim { + record_id: row.get(0)?, + size_bytes: row.get::<_, i64>(1)?.max(0) as u64, + }) + }, + ) + .optional()?) +} + +fn prune_owner( + conn: &Connection, + owner: &OwnerScope, + now: i64, +) -> Result<(PruneProgress, bool), SharedDataError> { + let mut pruned = PruneProgress::default(); + prune_expired(conn, owner, now, &mut pruned)?; + prune_aged(conn, owner, now, &mut pruned)?; + let max_bytes = effective_max_bytes(retention_policy(conn, owner)?); + let mut usage = usage_excluding(conn, owner, now, None)?; + while usage > max_bytes && pruned.records < MAX_PRUNE_ROWS { + let Some(victim) = oldest_unprotected(conn, owner, now, None)? else { + break; + }; + delete_record(conn, &victim)?; + pruned.records += 1; + pruned.bytes = pruned.bytes.saturating_add(victim.size_bytes); + usage = usage.saturating_sub(victim.size_bytes); + } + Ok((pruned, pruned.records > 0)) +} + +fn victims( + conn: &Connection, + sql: &str, + params: impl rusqlite::Params, +) -> Result, SharedDataError> { + let mut statement = conn.prepare(sql)?; + let rows = statement.query_map(params, |row| { + Ok(Victim { + record_id: row.get(0)?, + size_bytes: row.get::<_, i64>(1)?.max(0) as u64, + }) + })?; + rows.collect::, _>>().map_err(Into::into) +} + +fn delete_victims( + conn: &Connection, + victims: Vec, + pruned: &mut PruneProgress, +) -> Result<(), SharedDataError> { + for victim in victims { + delete_record(conn, &victim)?; + pruned.records += 1; + pruned.bytes = pruned.bytes.saturating_add(victim.size_bytes); + } + Ok(()) +} + +fn delete_record(conn: &Connection, victim: &Victim) -> Result<(), SharedDataError> { + conn.execute( + "DELETE FROM shared_records WHERE record_id = ?1", + [&victim.record_id], + )?; + Ok(()) +} + +fn current_pool_revision(conn: &Connection) -> Result { + let revision: i64 = conn.query_row( + "SELECT revision FROM shared_state WHERE id = 1", + [], + |row| row.get(0), + )?; + Ok(revision.max(0) as u64) +} + +fn advance_pool(conn: &Connection) -> Result { + conn.execute( + "UPDATE shared_state SET revision = revision + 1 WHERE id = 1", + [], + )?; + current_pool_revision(conn) +} + +fn record_by_id( + conn: &Connection, + owner: &OwnerScope, + record_id: &str, + now: i64, +) -> Result, SharedDataError> { + Ok(conn + .query_row( + &format!( + "SELECT {RECORD_COLUMNS} FROM shared_records + WHERE owner_key = ?1 AND record_id = ?2 AND archived = 0 + AND (expires_at IS NULL OR expires_at > ?3)" + ), + params![owner.key(), record_id, now], + record_from, + ) + .optional()?) +} + +fn metadata_from(record: SharedRecord) -> RecordMetadata { + RecordMetadata { + record_id: record.record_id, + dataset_id: record.dataset_id, + resource_id: record.resource_id, + class: record.class, + schema_id: record.schema_id, + schema_version: record.schema_version, + observed_at: record.observed_at, + received_at: record.received_at, + updated_at: record.updated_at, + expires_at: record.expires_at, + sequence: record.sequence, + size_bytes: record.size_bytes, + user_protected: record.user_protected, + } +} + +fn records_for_owner( + conn: &Connection, + owner: &OwnerScope, + now: i64, +) -> Result, SharedDataError> { + let mut statement = conn.prepare(&format!( + "SELECT {RECORD_COLUMNS} FROM shared_records + WHERE owner_key = ?1 AND archived = 0 + AND (expires_at IS NULL OR expires_at > ?2) + ORDER BY dataset_id ASC, received_at ASC, record_id ASC" + ))?; + let records = statement + .query_map(params![owner.key(), now], record_from)? + .collect::, _>>()?; + Ok(records) +} + +fn resource_exists( + conn: &Connection, + target: &OwnerScope, + record: &SharedRecord, +) -> Result { + let Some(resource_id) = record.resource_id.as_deref() else { + return Ok(false); + }; + Ok(conn.query_row( + "SELECT EXISTS(SELECT 1 FROM shared_records + WHERE owner_key = ?1 AND dataset_id = ?2 AND resource_id = ?3)", + params![target.key(), record.dataset_id, resource_id], + |row| row.get(0), + )?) +} + +/// Inserts one copied record under the new owner with a new host record id, its own initial +/// revision and the original provenance and observation metadata. +fn insert_migrated_record( + conn: &Connection, + target: &OwnerScope, + record_id: &str, + record: &SharedRecord, + pool_revision: u64, + now: i64, +) -> Result<(), SharedDataError> { + conn.execute( + "INSERT INTO shared_records + (record_id, owner_key, dataset_id, resource_id, category, class, + schema_id, schema_version, fields_json, opaque_payload, + source_plugin_id, source_publisher_fingerprint, source_profile_id, + declared_developer, origin, package_version, package_digest, + observed_at, received_at, updated_at, expires_at, sequence, + source_observation_id, revision, pool_revision, logical_bytes, + user_protected, archived) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, + ?17, ?18, ?19, ?19, ?20, ?21, ?22, 1, ?23, ?24, 0, 0)", + params![ + record_id, + target.key(), + record.dataset_id, + record.resource_id, + record.category, + record.class, + record.schema_id, + i64::from(record.schema_version), + record.fields_json, + record.opaque_payload, + record.provenance.source_plugin_id, + record.provenance.source_publisher_fingerprint, + record.provenance.source_profile_id, + record.provenance.declared_developer, + record.provenance.origin, + record.provenance.package_version, + record.provenance.package_digest, + record.observed_at, + now, + record.expires_at, + record.sequence as i64, + record.source_observation_id, + pool_revision as i64, + record.size_bytes as i64, + ], + )?; + Ok(()) +} + +fn record_from(row: &rusqlite::Row<'_>) -> rusqlite::Result { + Ok(SharedRecord { + record_id: row.get(0)?, + dataset_id: row.get(1)?, + category: row.get(2)?, + class: row.get(3)?, + schema_id: row.get(4)?, + schema_version: row.get::<_, i64>(5)?.max(0) as u32, + fields_json: row.get(6)?, + opaque_payload: row.get(7)?, + resource_id: row.get(8)?, + observed_at: row.get(9)?, + received_at: row.get(10)?, + updated_at: row.get(11)?, + expires_at: row.get(12)?, + sequence: row.get::<_, i64>(13)?.max(0) as u64, + source_observation_id: row.get(14)?, + revision: row.get::<_, i64>(15)?.max(0) as u64, + pool_revision: row.get::<_, i64>(16)?.max(0) as u64, + size_bytes: row.get::<_, i64>(17)?.max(0) as u64, + user_protected: row.get::<_, i64>(18)? != 0, + archived: row.get::<_, i64>(26)? != 0, + provenance: RecordProvenance { + source_plugin_id: row.get(19)?, + source_publisher_fingerprint: row.get(20)?, + source_profile_id: row.get(21)?, + declared_developer: row.get(22)?, + origin: row.get(23)?, + package_version: row.get(24)?, + package_digest: row.get(25)?, + }, + }) +} + +#[cfg(test)] +mod tests; diff --git a/crates/platform/src/plugin_shared_data/tests.rs b/crates/platform/src/plugin_shared_data/tests.rs new file mode 100644 index 000000000..d4063eed1 --- /dev/null +++ b/crates/platform/src/plugin_shared_data/tests.rs @@ -0,0 +1,1644 @@ +use super::*; +use rusqlite::Connection; +use tempfile::TempDir; + +fn owner(byte: u8, epoch: u64) -> OwnerScope { + OwnerScope::new([byte; 32], epoch).unwrap() +} + +fn provenance(plugin: &str) -> RecordProvenance { + RecordProvenance { + source_plugin_id: plugin.to_owned(), + source_publisher_fingerprint: format!("publisher-{plugin}"), + source_profile_id: "profile-1".to_owned(), + declared_developer: "Example Developer".to_owned(), + origin: "registry".to_owned(), + package_version: "1.2.3".to_owned(), + package_digest: vec![7; 32], + } +} + +fn record<'a>( + dataset: &'a str, + resource: Option<&'a str>, + fields: &'a str, + provenance: &'a RecordProvenance, + now: i64, +) -> RecordWrite<'a> { + RecordWrite { + dataset_id: dataset, + category: None, + class: "custom", + schema_id: "org.example.catalog.v1", + schema_version: 1, + fields_json: fields, + opaque_payload: &[], + resource_id: resource, + observed_at: now, + sequence: 1, + source_observation_id: "observation-1", + expires_at: None, + now, + provenance, + expected_revision: None, + } +} + +fn publish(store: &mut SharedDataStore, owner: OwnerScope, write: RecordWrite<'_>) -> WriteReceipt { + match store.write(owner, write).unwrap() { + WriteOutcome::Stored(receipt) => *receipt, + other => panic!("unexpected write outcome: {other:?}"), + } +} + +fn schema(conn: &Connection) -> Vec<(String, String, String, String)> { + let mut statement = conn + .prepare( + "SELECT type, name, tbl_name, COALESCE(sql, '') FROM sqlite_master + WHERE name NOT LIKE 'sqlite_%' ORDER BY type, name", + ) + .unwrap(); + statement + .query_map([], |row| { + Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?)) + }) + .unwrap() + .map(Result::unwrap) + .collect() +} + +fn user_version(conn: &Connection) -> i64 { + conn.query_row("PRAGMA user_version", [], |row| row.get(0)) + .unwrap() +} + +#[test] +fn a_legacy_sqlite_pool_is_renamed_to_the_gnpersistence_extension() { + let dir = TempDir::new().unwrap(); + let legacy = dir.path().join(LEGACY_FILE_NAME); + drop(Connection::open(&legacy).unwrap()); + assert!(legacy.is_file()); + + let store = SharedDataStore::open_existing(dir.path()) + .unwrap() + .expect("the legacy pool is migrated and opened"); + assert!(!legacy.exists(), "the legacy file name is not left behind"); + assert!(dir.path().join(FILE_NAME).is_file()); + assert_eq!( + store.pool_revision().unwrap(), + 0, + "the migrated pool keeps its schema state" + ); +} + +#[test] +fn a_fresh_pool_has_the_current_schema_pragmas_and_no_rows() { + let dir = TempDir::new().unwrap(); + let store = SharedDataStore::open(dir.path()).unwrap(); + + assert_eq!(MIGRATIONS.last().unwrap().version, CURRENT_SCHEMA_VERSION); + assert_eq!(user_version(&store.conn), CURRENT_SCHEMA_VERSION as i64); + let journal_mode: String = store + .conn + .query_row("PRAGMA journal_mode", [], |row| row.get(0)) + .unwrap(); + assert_eq!(journal_mode.to_lowercase(), "wal"); + let foreign_keys: i64 = store + .conn + .query_row("PRAGMA foreign_keys", [], |row| row.get(0)) + .unwrap(); + assert_eq!(foreign_keys, 1); + + let tables: Vec = store + .conn + .prepare( + "SELECT name FROM sqlite_master + WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name", + ) + .unwrap() + .query_map([], |row| row.get(0)) + .unwrap() + .map(Result::unwrap) + .collect(); + assert_eq!( + tables, + [ + "shared_owners", + "shared_records", + "shared_retention", + "shared_state" + ] + ); + assert_eq!(store.pool_revision().unwrap(), 0); + let usage = store.usage(&owner(1, 1), 100).unwrap(); + assert_eq!(usage.records, 0); + assert_eq!(usage.logical_bytes, 0); + assert_eq!(usage.max_bytes, MAX_OWNER_LOGICAL_BYTES); + assert_eq!(usage.max_age_seconds, None); +} + +#[test] +fn reading_an_absent_pool_creates_nothing() { + let dir = TempDir::new().unwrap(); + assert!( + SharedDataStore::open_existing(dir.path()) + .unwrap() + .is_none() + ); + assert!(!dir.path().join(FILE_NAME).exists()); +} + +#[test] +fn upgrading_the_first_schema_keeps_records_and_adds_no_session_rows() { + let upgraded_dir = TempDir::new().unwrap(); + { + let version_one = + SharedDataStore::open_with(upgraded_dir.path(), &MIGRATIONS[..1]).unwrap(); + assert_eq!(user_version(&version_one.conn), 1); + version_one + .conn + .execute( + "INSERT INTO shared_owners (owner_key, profile_epoch, updated_at) + VALUES (?1, 1, 100)", + [[9_u8; 32]], + ) + .unwrap(); + version_one + .conn + .execute( + "INSERT INTO shared_records + (record_id, owner_key, dataset_id, resource_id, category, class, + schema_id, schema_version, fields_json, opaque_payload, + source_plugin_id, source_publisher_fingerprint, source_profile_id, + declared_developer, origin, package_version, package_digest, + observed_at, received_at, updated_at, expires_at, sequence, + source_observation_id, revision, pool_revision, logical_bytes) + VALUES ('record-v1', ?1, 'org.example.catalog', NULL, NULL, 'custom', + 'org.example.catalog.v1', 1, '{\"round\":\"trip\"}', X'00', + 'producer', 'publisher-producer', 'profile-1', 'Example Developer', + 'registry', '1.2.3', ?2, 100, 100, 100, NULL, 1, + 'observation-1', 1, 1, 256)", + params![[9_u8; 32], vec![7_u8; 32]], + ) + .unwrap(); + version_one + .conn + .execute("UPDATE shared_state SET revision = 1 WHERE id = 1", []) + .unwrap(); + } + + let store = SharedDataStore::open(upgraded_dir.path()).unwrap(); + assert_eq!(user_version(&store.conn), CURRENT_SCHEMA_VERSION as i64); + let record = store.get(&owner(9, 1), "record-v1", 200).unwrap().unwrap(); + assert_eq!(record.fields_json, r#"{"round":"trip"}"#); + assert_eq!(record.opaque_payload, [0]); + assert_eq!(record.provenance.source_plugin_id, "producer"); + assert_eq!(record.revision, 1); + assert_eq!(record.pool_revision, 1); + assert!(!record.user_protected); + assert!(!record.archived); + assert_eq!(store.pool_revision().unwrap(), 1); + let records: i64 = store + .conn + .query_row("SELECT COUNT(*) FROM shared_records", [], |row| row.get(0)) + .unwrap(); + assert_eq!(records, 1, "upgrade preserves durable rows only"); + let session_tables: i64 = store + .conn + .query_row( + "SELECT COUNT(*) FROM sqlite_master WHERE name LIKE '%session%'", + [], + |row| row.get(0), + ) + .unwrap(); + assert_eq!(session_tables, 0); + + let fresh_dir = TempDir::new().unwrap(); + let fresh = SharedDataStore::open(fresh_dir.path()).unwrap(); + assert_eq!(schema(&store.conn), schema(&fresh.conn)); +} + +#[test] +fn a_newer_or_foreign_file_is_refused_without_writing() { + let newer_dir = TempDir::new().unwrap(); + let newer_path = newer_dir.path().join(FILE_NAME); + { + let conn = Connection::open(&newer_path).unwrap(); + conn.execute_batch( + "CREATE TABLE marker (id INTEGER) STRICT; + INSERT INTO marker VALUES (1); + PRAGMA user_version = 99;", + ) + .unwrap(); + } + let result = SharedDataStore::open(newer_dir.path()).map(|_| ()); + assert!(matches!(result, Err(SharedDataError::NewerVersion))); + let conn = Connection::open(&newer_path).unwrap(); + assert_eq!(user_version(&conn), 99); + let markers: i64 = conn + .query_row("SELECT COUNT(*) FROM marker", [], |row| row.get(0)) + .unwrap(); + assert_eq!(markers, 1); + + let foreign_dir = TempDir::new().unwrap(); + { + let conn = Connection::open(foreign_dir.path().join(FILE_NAME)).unwrap(); + conn.execute_batch("CREATE TABLE foreign_table (id INTEGER) STRICT;") + .unwrap(); + } + let result = SharedDataStore::open(foreign_dir.path()).map(|_| ()); + assert!(matches!(result, Err(SharedDataError::ForeignDatabase))); +} + +#[test] +fn replacing_a_resource_record_keeps_its_id_and_raises_both_revisions() { + let dir = TempDir::new().unwrap(); + let mut store = SharedDataStore::open(dir.path()).unwrap(); + let owner = owner(1, 1); + let provenance = provenance("producer"); + + let first = publish( + &mut store, + owner, + record( + "org.example.catalog", + Some("disc-1"), + r#"{"v":1}"#, + &provenance, + 100, + ), + ); + assert!(!first.replaced); + assert_eq!(first.record.revision, 1); + assert_eq!(first.record.pool_revision, 1); + assert_eq!(first.record.received_at, 100); + + let second = publish( + &mut store, + owner, + record( + "org.example.catalog", + Some("disc-1"), + r#"{"v":2}"#, + &provenance, + 110, + ), + ); + assert!(second.replaced); + assert_eq!(second.record.record_id, first.record.record_id); + assert_eq!(second.record.revision, 2); + assert_eq!(second.record.pool_revision, 2); + assert_eq!(second.record.received_at, 100); + assert_eq!(second.record.updated_at, 110); + assert_eq!(second.record.fields_json, r#"{"v":2}"#); + + let listed = store + .list_dataset(&owner, "org.example.catalog", 200) + .unwrap(); + assert_eq!(listed.records, [second.record]); + assert_eq!(listed.pool_revision, 2); +} + +#[test] +fn appending_without_a_resource_id_creates_distinct_records_in_a_stable_order() { + let dir = TempDir::new().unwrap(); + let mut store = SharedDataStore::open(dir.path()).unwrap(); + let owner = owner(2, 1); + let provenance = provenance("producer"); + + let first = publish( + &mut store, + owner, + record("org.example.notes", None, r#"{"n":1}"#, &provenance, 100), + ); + let second = publish( + &mut store, + owner, + record("org.example.notes", None, r#"{"n":2}"#, &provenance, 100), + ); + let third = publish( + &mut store, + owner, + record("org.example.notes", None, r#"{"n":3}"#, &provenance, 101), + ); + assert_ne!(first.record.record_id, second.record.record_id); + assert_ne!(second.record.record_id, third.record.record_id); + + let listed = store + .list_dataset(&owner, "org.example.notes", 200) + .unwrap(); + assert_eq!( + listed + .records + .iter() + .map(|record| record.record_id.as_str()) + .collect::>(), + [ + first.record.record_id.as_str(), + second.record.record_id.as_str(), + third.record.record_id.as_str() + ] + ); + assert_eq!(listed.pool_revision, 3); + + let replaced = publish( + &mut store, + owner, + record( + "org.example.notes", + Some("resource-1"), + r#"{"n":4}"#, + &provenance, + 105, + ), + ); + let replaced_again = publish( + &mut store, + owner, + record( + "org.example.notes", + Some("resource-1"), + r#"{"n":5}"#, + &provenance, + 110, + ), + ); + assert_eq!(replaced.record.revision, 1); + assert_eq!(replaced_again.record.revision, 2); + assert_eq!(replaced_again.record.received_at, 105); + let listed = store + .list_dataset(&owner, "org.example.notes", 200) + .unwrap(); + assert_eq!( + listed + .records + .iter() + .map(|record| record.record_id.as_str()) + .collect::>(), + [ + first.record.record_id.as_str(), + second.record.record_id.as_str(), + third.record.record_id.as_str(), + replaced.record.record_id.as_str() + ], + "a replacement keeps its position" + ); + assert_eq!(listed.pool_revision, 5); +} + +#[test] +fn another_owner_cannot_read_or_replace_a_record() { + let dir = TempDir::new().unwrap(); + let mut store = SharedDataStore::open(dir.path()).unwrap(); + let first_owner = owner(3, 1); + let second_owner = owner(4, 1); + let first_provenance = provenance("first"); + let second_provenance = provenance("second"); + + let first = publish( + &mut store, + first_owner, + record( + "org.example.catalog", + Some("shared-resource"), + r#"{"owner":"first"}"#, + &first_provenance, + 100, + ), + ); + let second = publish( + &mut store, + second_owner, + record( + "org.example.catalog", + Some("shared-resource"), + r#"{"owner":"second"}"#, + &second_provenance, + 105, + ), + ); + assert_ne!(first.record.record_id, second.record.record_id); + assert_eq!( + store + .get(&first_owner, &second.record.record_id, 200) + .unwrap(), + None + ); + assert_eq!( + store + .get(&second_owner, &first.record.record_id, 200) + .unwrap(), + None + ); + + let replaced = publish( + &mut store, + first_owner, + record( + "org.example.catalog", + Some("shared-resource"), + r#"{"owner":"first-updated"}"#, + &first_provenance, + 110, + ), + ); + assert_eq!(replaced.record.record_id, first.record.record_id); + assert_eq!( + store + .get(&second_owner, &second.record.record_id, 200) + .unwrap(), + Some(second.record) + ); + let first_records = store + .list_dataset(&first_owner, "org.example.catalog", 200) + .unwrap(); + let second_records = store + .list_dataset(&second_owner, "org.example.catalog", 200) + .unwrap(); + assert_eq!(first_records.records.len(), 1); + assert_eq!(second_records.records.len(), 1); + assert_eq!( + second_records.records[0].fields_json, + r#"{"owner":"second"}"# + ); +} + +#[test] +fn cross_owner_reads_share_a_dataset_without_disclosing_another_owners_scope() { + let dir = TempDir::new().unwrap(); + let mut store = SharedDataStore::open(dir.path()).unwrap(); + let first_owner = owner(6, 1); + let second_owner = owner(7, 1); + let first_provenance = provenance("first"); + let second_provenance = provenance("second"); + + let first = publish( + &mut store, + first_owner, + record( + "org.example.catalog", + Some("disc-1"), + r#"{"title":"one"}"#, + &first_provenance, + 100, + ), + ); + let second = publish( + &mut store, + second_owner, + record( + "org.example.catalog", + Some("disc-1"), + r#"{"title":"two"}"#, + &second_provenance, + 101, + ), + ); + assert!(first.record.record_id.starts_with("durable-")); + assert!(second.record.record_id.starts_with("durable-")); + assert_ne!( + first.record.record_id, second.record.record_id, + "each producer keeps its own record id" + ); + + // A cross-owner read by id finds the record that an owner-scoped read hides. + assert_eq!( + store + .get(&second_owner, &first.record.record_id, 200) + .unwrap(), + None + ); + assert_eq!( + store + .get_any(&first.record.record_id, 200) + .unwrap() + .unwrap(), + first.record + ); + + let listed = store.list_dataset_any("org.example.catalog", 200).unwrap(); + assert_eq!( + listed + .iter() + .map(|record| record.record_id.as_str()) + .collect::>(), + [ + first.record.record_id.as_str(), + second.record.record_id.as_str() + ], + "cross-owner lists use the same receipt order as an owner list" + ); + assert!( + store + .list_dataset_any("org.example.other", 200) + .unwrap() + .is_empty() + ); + + // Expired and replaced values follow the same rules across owners. + let mut expiring = record( + "org.example.catalog", + Some("disc-2"), + r#"{"title":"short"}"#, + &first_provenance, + 100, + ); + expiring.expires_at = Some(150); + let expiring = publish(&mut store, first_owner, expiring); + assert_eq!( + store + .list_dataset_any("org.example.catalog", 200) + .unwrap() + .len(), + 2, + "an expired record is not listed" + ); + assert_eq!( + store.get_any(&expiring.record.record_id, 200).unwrap(), + None, + "an expired record cannot be read by id either" + ); + + let replaced = publish( + &mut store, + first_owner, + record( + "org.example.catalog", + Some("disc-1"), + r#"{"title":"one-updated"}"#, + &first_provenance, + 120, + ), + ); + assert_eq!(replaced.record.record_id, first.record.record_id); + let listed = store.list_dataset_any("org.example.catalog", 200).unwrap(); + assert_eq!(listed.len(), 2); + assert_eq!(listed[0].record_id, first.record.record_id); + assert_eq!(listed[0].fields_json, r#"{"title":"one-updated"}"#); + assert_eq!(listed[0].revision, 2); +} + +#[test] +fn a_stale_profile_epoch_fails_closed_for_reads_writes_and_lists() { + let dir = TempDir::new().unwrap(); + let mut store = SharedDataStore::open(dir.path()).unwrap(); + assert!(matches!( + OwnerScope::new([1; 32], 0), + Err(SharedDataError::InvalidOwner) + )); + + let current = owner(5, 10); + let stale = owner(5, 9); + let provenance = provenance("producer"); + let stored = publish( + &mut store, + current, + record( + "org.example.catalog", + Some("resource"), + r#"{"v":1}"#, + &provenance, + 100, + ), + ); + + assert!(matches!( + store.get(&stale, &stored.record.record_id, 100).map(|_| ()), + Err(SharedDataError::StaleProfileEpoch) + )); + assert!(matches!( + store + .list_dataset(&stale, "org.example.catalog", 100) + .map(|_| ()), + Err(SharedDataError::StaleProfileEpoch) + )); + assert!(matches!( + store.write( + stale, + record( + "org.example.catalog", + Some("resource"), + r#"{"v":2}"#, + &provenance, + 110 + ) + ), + Err(SharedDataError::StaleProfileEpoch) + )); + assert_eq!( + store + .get(¤t, &stored.record.record_id, 110) + .unwrap() + .unwrap(), + stored.record + ); + + let newer = owner(5, 11); + let replaced = publish( + &mut store, + newer, + record( + "org.example.catalog", + Some("resource"), + r#"{"v":2}"#, + &provenance, + 120, + ), + ); + assert_eq!(replaced.record.revision, 2); + assert!(matches!( + store + .get(¤t, &stored.record.record_id, 130) + .map(|_| ()), + Err(SharedDataError::StaleProfileEpoch) + )); + assert!( + store + .get(&newer, &stored.record.record_id, 130) + .unwrap() + .is_some() + ); +} + +#[test] +fn revision_conflicts_change_nothing_and_do_not_advance_the_pool() { + let dir = TempDir::new().unwrap(); + let mut store = SharedDataStore::open(dir.path()).unwrap(); + let owner = owner(6, 1); + let provenance = provenance("producer"); + + let stored = publish( + &mut store, + owner, + record( + "org.example.catalog", + Some("resource"), + r#"{"v":1}"#, + &provenance, + 100, + ), + ); + + let mut conflicting = record( + "org.example.catalog", + Some("resource"), + r#"{"v":2}"#, + &provenance, + 110, + ); + conflicting.expected_revision = Some(0); + assert_eq!( + store.write(owner, conflicting).unwrap(), + WriteOutcome::Conflict { + current_revision: 1 + } + ); + assert_eq!( + store + .get(&owner, &stored.record.record_id, 110) + .unwrap() + .unwrap(), + stored.record + ); + assert_eq!(store.pool_revision().unwrap(), 1); + + let mut accepted = record( + "org.example.catalog", + Some("resource"), + r#"{"v":2}"#, + &provenance, + 120, + ); + accepted.expected_revision = Some(1); + let replaced = publish(&mut store, owner, accepted); + assert_eq!(replaced.record.revision, 2); + assert_eq!(replaced.record.pool_revision, 2); + + let mut append_conflict = record("org.example.notes", None, r#"{"v":1}"#, &provenance, 130); + append_conflict.expected_revision = Some(1); + assert_eq!( + store.write(owner, append_conflict).unwrap(), + WriteOutcome::Conflict { + current_revision: 0 + } + ); + + let mut missing_conflict = record( + "org.example.catalog", + Some("missing"), + r#"{"v":1}"#, + &provenance, + 130, + ); + missing_conflict.expected_revision = Some(2); + assert_eq!( + store.write(owner, missing_conflict).unwrap(), + WriteOutcome::Conflict { + current_revision: 0 + } + ); + assert_eq!(store.pool_revision().unwrap(), 2); +} + +#[test] +fn expired_records_disappear_from_reads_and_lists_and_prune_reclaims_them() { + let dir = TempDir::new().unwrap(); + let mut store = SharedDataStore::open(dir.path()).unwrap(); + let owner = owner(7, 1); + let provenance = provenance("producer"); + + let mut expiring = record( + "org.example.catalog", + Some("resource"), + r#"{"v":1}"#, + &provenance, + 100, + ); + expiring.expires_at = Some(110); + let stored = publish(&mut store, owner, expiring); + assert!( + store + .get(&owner, &stored.record.record_id, 109) + .unwrap() + .is_some() + ); + assert_eq!( + store.get(&owner, &stored.record.record_id, 110).unwrap(), + None + ); + let listed = store + .list_dataset(&owner, "org.example.catalog", 110) + .unwrap(); + assert!(listed.records.is_empty()); + assert_eq!(listed.pool_revision, 1); + let usage = store.usage(&owner, 110).unwrap(); + assert_eq!(usage.records, 0); + assert_eq!(usage.logical_bytes, 0); + + let pruned = store.prune(&owner, 110).unwrap(); + assert_eq!( + pruned, + PruneOutcome { + removed_records: 1, + reclaimed_bytes: stored.record.size_bytes, + pool_revision: 2, + } + ); + assert_eq!( + store.get(&owner, &stored.record.record_id, 109).unwrap(), + None + ); +} + +#[test] +fn a_quota_prune_on_write_removes_only_the_owners_oldest_unprotected_record() { + let dir = TempDir::new().unwrap(); + let mut store = SharedDataStore::open(dir.path()).unwrap(); + let pruned_owner = owner(8, 1); + let other_owner = owner(9, 1); + let pruned_provenance = provenance("pruned"); + let other_provenance = provenance("other"); + + let first = publish( + &mut store, + pruned_owner, + record( + "org.example.catalog", + Some("resource-1"), + r#"{"payload":"same-size"}"#, + &pruned_provenance, + 100, + ), + ); + let other = publish( + &mut store, + other_owner, + record( + "org.example.catalog", + Some("resource-1"), + r#"{"payload":"same-size"}"#, + &other_provenance, + 105, + ), + ); + let second = publish( + &mut store, + pruned_owner, + record( + "org.example.catalog", + Some("resource-2"), + r#"{"payload":"same-size"}"#, + &pruned_provenance, + 110, + ), + ); + assert_eq!(first.record.size_bytes, second.record.size_bytes); + assert!( + store + .set_user_protected(&pruned_owner, &first.record.record_id, true, 115) + .unwrap() + ); + let limit = first.record.size_bytes + second.record.size_bytes; + store + .set_retention( + &pruned_owner, + RetentionPolicy { + max_age_seconds: None, + max_bytes: Some(limit), + }, + 115, + ) + .unwrap(); + + let third = publish( + &mut store, + pruned_owner, + record( + "org.example.catalog", + Some("resource-3"), + r#"{"payload":"same-size"}"#, + &pruned_provenance, + 120, + ), + ); + assert_eq!(third.pruned_records, 1); + assert_eq!(third.reclaimed_bytes, second.record.size_bytes); + assert!( + store + .get(&pruned_owner, &second.record.record_id, 130) + .unwrap() + .is_none() + ); + let listed = store + .list_dataset(&pruned_owner, "org.example.catalog", 130) + .unwrap(); + assert_eq!( + listed + .records + .iter() + .map(|record| record.record_id.as_str()) + .collect::>(), + [ + first.record.record_id.as_str(), + third.record.record_id.as_str() + ] + ); + assert!(listed.records[0].user_protected); + assert_eq!( + store.usage(&pruned_owner, 130).unwrap().logical_bytes, + first.record.size_bytes + third.record.size_bytes + ); + + assert_eq!( + store + .get(&other_owner, &other.record.record_id, 130) + .unwrap(), + Some(other.record.clone()) + ); + assert_eq!(store.usage(&other_owner, 130).unwrap().records, 1); + assert_eq!( + store.usage(&other_owner, 130).unwrap().logical_bytes, + other.record.size_bytes + ); +} + +#[test] +fn age_retention_prunes_only_this_owner_and_keeps_protected_rows() { + let dir = TempDir::new().unwrap(); + let mut store = SharedDataStore::open(dir.path()).unwrap(); + let pruned_owner = owner(10, 1); + let other_owner = owner(11, 1); + let pruned_provenance = provenance("pruned"); + let other_provenance = provenance("other"); + + let protected = publish( + &mut store, + pruned_owner, + record( + "org.example.catalog", + Some("protected"), + r#"{"payload":"old"}"#, + &pruned_provenance, + 100, + ), + ); + let stale = publish( + &mut store, + pruned_owner, + record( + "org.example.catalog", + Some("stale"), + r#"{"payload":"old"}"#, + &pruned_provenance, + 105, + ), + ); + let fresh = publish( + &mut store, + pruned_owner, + record( + "org.example.catalog", + Some("fresh"), + r#"{"payload":"old"}"#, + &pruned_provenance, + 195, + ), + ); + let other = publish( + &mut store, + other_owner, + record( + "org.example.catalog", + Some("other"), + r#"{"payload":"old"}"#, + &other_provenance, + 100, + ), + ); + assert!( + store + .set_user_protected(&pruned_owner, &protected.record.record_id, true, 196) + .unwrap() + ); + + let pruned = store + .set_retention( + &pruned_owner, + RetentionPolicy { + max_age_seconds: Some(10), + max_bytes: None, + }, + 200, + ) + .unwrap(); + assert_eq!(pruned.removed_records, 1); + assert_eq!(pruned.reclaimed_bytes, stale.record.size_bytes); + let listed = store + .list_dataset(&pruned_owner, "org.example.catalog", 200) + .unwrap(); + assert_eq!( + listed + .records + .iter() + .map(|record| record.record_id.as_str()) + .collect::>(), + [ + protected.record.record_id.as_str(), + fresh.record.record_id.as_str() + ] + ); + let usage = store.usage(&pruned_owner, 200).unwrap(); + assert_eq!(usage.records, 2); + assert_eq!(usage.max_age_seconds, Some(10)); + assert_eq!( + store + .get(&other_owner, &other.record.record_id, 200) + .unwrap(), + Some(other.record) + ); + assert_eq!(store.usage(&other_owner, 200).unwrap().records, 1); +} + +#[test] +fn usage_reports_count_bytes_and_effective_limits() { + let dir = TempDir::new().unwrap(); + let mut store = SharedDataStore::open(dir.path()).unwrap(); + let owner = owner(12, 1); + let provenance = provenance("producer"); + let stored = publish( + &mut store, + owner, + record( + "org.example.catalog", + Some("resource"), + r#"{"v":1}"#, + &provenance, + 100, + ), + ); + + let usage = store.usage(&owner, 100).unwrap(); + assert_eq!(usage.records, 1); + assert_eq!(usage.logical_bytes, stored.record.size_bytes); + assert_eq!(usage.max_bytes, MAX_OWNER_LOGICAL_BYTES); + assert_eq!(usage.max_age_seconds, None); + assert_eq!(usage.oldest_updated_at, Some(100)); + assert!(usage.physical_bytes_estimate > 0); + assert!(!format!("{usage:?}").contains(dir.path().to_str().unwrap())); + + store + .set_retention( + &owner, + RetentionPolicy { + max_age_seconds: Some(60), + max_bytes: Some(4096), + }, + 110, + ) + .unwrap(); + let usage = store.usage(&owner, 110).unwrap(); + assert_eq!(usage.records, 1); + assert_eq!(usage.max_bytes, 4096); + assert_eq!(usage.max_age_seconds, Some(60)); +} + +#[test] +fn deleting_one_owners_records_reclaims_its_bytes_and_keeps_another_owner() { + let dir = TempDir::new().unwrap(); + let mut store = SharedDataStore::open(dir.path()).unwrap(); + let deleted_owner = owner(14, 1); + let other_owner = owner(15, 1); + let producer_provenance = provenance("producer"); + let other_provenance = provenance("other"); + + let first = publish( + &mut store, + deleted_owner, + record( + "org.example.catalog", + Some("resource-a"), + r#"{"v":1}"#, + &producer_provenance, + 100, + ), + ); + let second = publish( + &mut store, + deleted_owner, + record( + "org.example.catalog", + None, + r#"{"v":2}"#, + &producer_provenance, + 101, + ), + ); + let other = publish( + &mut store, + other_owner, + record( + "org.example.catalog", + Some("resource-b"), + r#"{"other":true}"#, + &other_provenance, + 102, + ), + ); + store + .set_retention( + &deleted_owner, + RetentionPolicy { + max_age_seconds: Some(60), + max_bytes: Some(4096), + }, + 103, + ) + .unwrap(); + store + .set_user_protected(&deleted_owner, &first.record.record_id, true, 103) + .unwrap(); + + let before = store.usage(&deleted_owner, 104).unwrap(); + let other_before = store.usage(&other_owner, 104).unwrap(); + assert_eq!(before.records, 2); + assert_eq!( + before.logical_bytes, + first.record.size_bytes + second.record.size_bytes + ); + + let deleted = store.delete_owner(&deleted_owner, 104).unwrap(); + assert_eq!(deleted.removed_records, 2); + assert_eq!(deleted.reclaimed_bytes, before.logical_bytes); + assert_eq!(deleted.pool_revision, store.pool_revision().unwrap()); + + let after = store.usage(&deleted_owner, 104).unwrap(); + assert_eq!(after.records, 0); + assert_eq!(after.logical_bytes, 0); + assert_eq!(after.max_bytes, 4096, "the retention policy stays"); + assert_eq!(after.max_age_seconds, Some(60)); + assert_eq!( + store + .get(&other_owner, &other.record.record_id, 104) + .unwrap(), + Some(other.record.clone()) + ); + let other_after = store.usage(&other_owner, 104).unwrap(); + assert_eq!(other_after.records, other_before.records); + assert_eq!(other_after.logical_bytes, other_before.logical_bytes); + assert_eq!(other_after.max_bytes, MAX_OWNER_LOGICAL_BYTES); + + let again = store.delete_owner(&deleted_owner, 105).unwrap(); + assert_eq!(again.removed_records, 0); + assert_eq!(again.reclaimed_bytes, 0); + assert_eq!(again.pool_revision, deleted.pool_revision); +} + +#[test] +fn deleting_with_a_stale_profile_epoch_changes_nothing() { + let dir = TempDir::new().unwrap(); + let mut store = SharedDataStore::open(dir.path()).unwrap(); + let stale = owner(16, 1); + let current = owner(16, 2); + let provenance = provenance("producer"); + publish( + &mut store, + current, + record( + "org.example.catalog", + Some("resource"), + r#"{"v":1}"#, + &provenance, + 100, + ), + ); + + assert!(matches!( + store.delete_owner(&stale, 101), + Err(SharedDataError::StaleProfileEpoch) + )); + assert_eq!(store.usage(¤t, 101).unwrap().records, 1); +} + +#[test] +fn archiving_retains_only_the_owners_rows_until_a_reviewed_reuse() { + let dir = TempDir::new().unwrap(); + let mut store = SharedDataStore::open(dir.path()).unwrap(); + let archived_owner = owner(17, 1); + let other_owner = owner(18, 1); + let archived_provenance = provenance("producer"); + let other_provenance = provenance("other"); + + let first = publish( + &mut store, + archived_owner, + record( + "org.example.catalog", + Some("disc-1"), + r#"{"title":"Dolphin"}"#, + &archived_provenance, + 100, + ), + ); + let second = publish( + &mut store, + archived_owner, + record( + "org.example.catalog", + None, + r#"{"title":"Second"}"#, + &archived_provenance, + 101, + ), + ); + let other = publish( + &mut store, + other_owner, + record( + "org.example.catalog", + Some("disc-2"), + r#"{"title":"Other"}"#, + &other_provenance, + 102, + ), + ); + let archived_bytes = first.record.size_bytes + second.record.size_bytes; + let other_bytes = other.record.size_bytes; + let pool_before = store.pool_revision().unwrap(); + + let outcome = store.archive_owner(&archived_owner, 110).unwrap(); + assert_eq!(outcome.records, 2); + assert_eq!(outcome.pool_revision, pool_before + 1); + + // Ordinary owner and cross-owner reads skip archived rows. + assert!( + store + .get(&archived_owner, &first.record.record_id, 110) + .unwrap() + .is_none() + ); + assert!( + store + .get_any(&first.record.record_id, 110) + .unwrap() + .is_none() + ); + assert!( + store + .list_dataset(&archived_owner, "org.example.catalog", 110) + .unwrap() + .records + .is_empty(), + "the archived owner sees no live row" + ); + let any = store.list_dataset_any("org.example.catalog", 110).unwrap(); + assert_eq!(any.len(), 1, "only the other owner's row stays visible"); + assert_eq!(any[0].record_id, other.record.record_id); + assert!(!any[0].archived); + + let usage = store.usage(&archived_owner, 110).unwrap(); + assert_eq!(usage.records, 0); + assert_eq!(usage.logical_bytes, 0); + assert_eq!(usage.archived_records, 2); + assert_eq!(usage.archived_logical_bytes, archived_bytes); + let other_usage = store.usage(&other_owner, 110).unwrap(); + assert_eq!(other_usage.records, 1); + assert_eq!(other_usage.logical_bytes, other_bytes); + assert_eq!(other_usage.archived_records, 0); + + // A reinstall cannot replace the archived resource invisibly, and retention never prunes it. + let mut replacement = record( + "org.example.catalog", + Some("disc-1"), + r#"{"title":"Replacement"}"#, + &archived_provenance, + 120, + ); + replacement.expected_revision = None; + assert!(matches!( + store.write(archived_owner, replacement), + Err(SharedDataError::ArchivedRecordExists) + )); + assert_eq!(store.pool_revision().unwrap(), outcome.pool_revision); + let pruned = store.prune(&archived_owner, 130).unwrap(); + assert_eq!(pruned.removed_records, 0); + assert_eq!( + store.usage(&archived_owner, 130).unwrap().archived_records, + 2 + ); + + // An explicit host review is the only path back to ordinary reads. + let reused = store.reuse_archived_owner(&archived_owner, 140).unwrap(); + assert_eq!(reused.records, 2); + assert_eq!(reused.pool_revision, pruned.pool_revision + 1); + let listed = store + .list_dataset(&archived_owner, "org.example.catalog", 140) + .unwrap(); + assert_eq!(listed.records.len(), 2); + assert!(listed.records.iter().all(|record| !record.archived)); + assert_eq!( + store + .get(&archived_owner, &first.record.record_id, 140) + .unwrap() + .map(|record| record.fields_json), + Some(r#"{"title":"Dolphin"}"#.to_owned()) + ); + let usage = store.usage(&archived_owner, 140).unwrap(); + assert_eq!(usage.records, 2); + assert_eq!(usage.logical_bytes, archived_bytes); + assert_eq!(usage.archived_records, 0); + assert_eq!( + store + .get(&other_owner, &other.record.record_id, 140) + .unwrap(), + Some(other.record.clone()) + ); + assert_eq!(store.usage(&other_owner, 140).unwrap().records, 1); +} + +#[test] +fn archiving_with_a_stale_profile_epoch_changes_nothing() { + let dir = TempDir::new().unwrap(); + let mut store = SharedDataStore::open(dir.path()).unwrap(); + let stale = owner(19, 1); + let current = owner(19, 2); + publish( + &mut store, + current, + record( + "org.example.catalog", + Some("resource"), + r#"{"v":1}"#, + &provenance("producer"), + 100, + ), + ); + + assert!(matches!( + store.archive_owner(&stale, 101), + Err(SharedDataError::StaleProfileEpoch) + )); + assert_eq!(store.usage(¤t, 101).unwrap().records, 1); + assert_eq!(store.usage(¤t, 101).unwrap().archived_records, 0); +} + +#[test] +fn invalid_records_are_rejected_before_anything_is_stored() { + let dir = TempDir::new().unwrap(); + let mut store = SharedDataStore::open(dir.path()).unwrap(); + let owner = owner(13, 1); + let provenance = provenance("producer"); + + let mut empty = record("org.example.catalog", None, "", &provenance, 100); + empty.opaque_payload = &[]; + assert!(matches!( + store.write(owner, empty), + Err(SharedDataError::InvalidRecord) + )); + + let mut both = record("org.example.catalog", None, r#"{"v":1}"#, &provenance, 100); + both.opaque_payload = b"bytes"; + assert!(matches!( + store.write(owner, both), + Err(SharedDataError::InvalidRecord) + )); + + for fields in ["[]", "{}", "not json"] { + let invalid = record("org.example.catalog", None, fields, &provenance, 100); + assert!(matches!( + store.write(owner, invalid), + Err(SharedDataError::InvalidRecord) + )); + } + + let large = format!(r#"{{"value":"{}"}}"#, "x".repeat(MAX_RECORD_BYTES)); + let oversized = record("org.example.catalog", None, &large, &provenance, 100); + assert!(matches!( + store.write(owner, oversized), + Err(SharedDataError::RecordTooLarge) + )); + + let mut long_ttl = record("org.example.catalog", None, r#"{"v":1}"#, &provenance, 100); + long_ttl.expires_at = Some(100 + MAX_TTL_SECONDS as i64 + 1); + assert!(matches!( + store.write(owner, long_ttl), + Err(SharedDataError::InvalidRecord) + )); + + let zero_time = record("org.example.catalog", None, r#"{"v":1}"#, &provenance, 0); + assert!(matches!( + store.write(owner, zero_time), + Err(SharedDataError::InvalidRecord) + )); + + assert_eq!(store.usage(&owner, 100).unwrap().records, 0); + assert_eq!(store.pool_revision().unwrap(), 0); +} + +#[test] +fn a_reviewed_reclaim_removes_only_one_owners_unprotected_archived_rows() { + let dir = TempDir::new().unwrap(); + let mut store = SharedDataStore::open(dir.path()).unwrap(); + let archived_owner = owner(1, 1); + let other_owner = owner(2, 1); + let first_provenance = provenance("org.example.first"); + let second_provenance = provenance("org.example.first"); + let other_provenance = provenance("org.example.other"); + let first = publish( + &mut store, + archived_owner, + record( + "org.example.catalog", + Some("disc-1"), + r#"{"title":"First"}"#, + &first_provenance, + 100, + ), + ); + let second = publish( + &mut store, + archived_owner, + record( + "org.example.catalog", + Some("disc-2"), + r#"{"title":"Second"}"#, + &second_provenance, + 101, + ), + ); + let other = publish( + &mut store, + other_owner, + record( + "org.example.catalog", + Some("disc-3"), + r#"{"title":"Other"}"#, + &other_provenance, + 102, + ), + ); + assert!( + store + .set_user_protected(&archived_owner, &first.record.record_id, true, 105) + .unwrap() + ); + store.archive_owner(&archived_owner, 110).unwrap(); + assert_eq!( + store.usage(&archived_owner, 110).unwrap().archived_records, + 2 + ); + + let pool_before = store.pool_revision().unwrap(); + let reclaimed = store.reclaim_archived_owner(&archived_owner).unwrap(); + assert_eq!(reclaimed.removed_records, 1, "the protected row stays"); + assert_eq!(reclaimed.reclaimed_bytes, second.record.size_bytes); + assert_eq!(reclaimed.pool_revision, pool_before + 1); + let usage = store.usage(&archived_owner, 110).unwrap(); + assert_eq!(usage.archived_records, 1); + assert_eq!(usage.archived_logical_bytes, first.record.size_bytes); + assert_eq!( + store + .list_dataset_any("org.example.catalog", 110) + .unwrap() + .len(), + 1, + "another owner's live row is untouched" + ); + assert_eq!(store.usage(&other_owner, 110).unwrap().records, 1); + assert!(!other.record.archived); +} + +#[test] +fn migration_source_reports_records_without_changing_the_pool() { + let dir = TempDir::new().unwrap(); + let mut store = SharedDataStore::open(dir.path()).unwrap(); + let old = owner(1, 1); + let new = owner(2, 1); + let old_provenance = provenance("old"); + let resource = publish( + &mut store, + old, + record( + "org.example.catalog", + Some("disc-1"), + r#"{"title":"Dolphin"}"#, + &old_provenance, + 100, + ), + ); + publish( + &mut store, + old, + record( + "org.example.notes", + None, + r#"{"text":"hello"}"#, + &old_provenance, + 100, + ), + ); + let revision_before = store.pool_revision().unwrap(); + + let source = store.migration_source(&old, 100).unwrap(); + assert_eq!(source.records.len(), 2); + assert!(source.logical_bytes > 0); + assert_eq!(source.expired_records, 0); + assert_eq!(source.archived_records, 0); + assert_eq!(source.records[0].schema_id, "org.example.catalog.v1"); + assert_eq!(store.pool_revision().unwrap(), revision_before); + assert_eq!(store.usage(&new, 100).unwrap().records, 0); + assert!( + store + .get_any(&resource.record.record_id, 100) + .unwrap() + .is_some() + ); +} + +#[test] +fn migration_copies_records_with_original_provenance_and_keeps_the_source() { + let dir = TempDir::new().unwrap(); + let mut store = SharedDataStore::open(dir.path()).unwrap(); + let old = owner(1, 1); + let new = owner(2, 1); + let old_provenance = provenance("old"); + let first = publish( + &mut store, + old, + record( + "org.example.catalog", + Some("disc-1"), + r#"{"title":"Dolphin"}"#, + &old_provenance, + 100, + ), + ); + publish( + &mut store, + old, + record( + "org.example.notes", + None, + r#"{"text":"hello"}"#, + &old_provenance, + 100, + ), + ); + + let ids = store + .migration_source(&old, 100) + .unwrap() + .records + .into_iter() + .map(|record| record.record_id) + .collect::>(); + let outcome = store.migrate_records(&old, &new, &ids, 100).unwrap(); + assert_eq!(outcome.copied.len(), 2); + assert!(outcome.skipped.is_empty()); + assert_ne!(outcome.copied[0].record_id, first.record.record_id); + + let migrated = store + .list_dataset(&new, "org.example.catalog", 100) + .unwrap(); + assert_eq!(migrated.records.len(), 1); + let copy = &migrated.records[0]; + assert_eq!(copy.fields_json, r#"{"title":"Dolphin"}"#); + assert_eq!( + copy.provenance, old_provenance, + "the original source is preserved" + ); + assert_eq!( + copy.provenance.source_publisher_fingerprint, + "publisher-old" + ); + assert_eq!(copy.revision, 1); + assert_eq!(copy.record_id, outcome.copied[0].record_id); + assert_eq!(store.usage(&new, 100).unwrap().records, 2); + + let original = store + .list_dataset(&old, "org.example.catalog", 100) + .unwrap(); + assert_eq!(original.records.len(), 1, "the source data is untouched"); + assert_eq!(original.records[0].record_id, first.record.record_id); + assert_eq!(store.usage(&old, 100).unwrap().records, 2); + + assert!(matches!( + store.migrate_records(&old, &old, &ids, 100), + Err(SharedDataError::InvalidMigration) + )); +} + +#[test] +fn migration_reports_conflicts_and_rollback_drops_only_unprotected_copies() { + let dir = TempDir::new().unwrap(); + let mut store = SharedDataStore::open(dir.path()).unwrap(); + let old = owner(1, 1); + let new = owner(2, 1); + let old_provenance = provenance("old"); + let new_provenance = provenance("new"); + publish( + &mut store, + old, + record( + "org.example.catalog", + Some("disc-1"), + r#"{"title":"Old"}"#, + &old_provenance, + 100, + ), + ); + publish( + &mut store, + old, + record( + "org.example.notes", + None, + r#"{"text":"old"}"#, + &old_provenance, + 100, + ), + ); + let own = publish( + &mut store, + new, + record( + "org.example.catalog", + Some("disc-1"), + r#"{"title":"New"}"#, + &new_provenance, + 100, + ), + ); + + let ids = store + .migration_source(&old, 100) + .unwrap() + .records + .into_iter() + .map(|record| record.record_id) + .collect::>(); + let outcome = store.migrate_records(&old, &new, &ids, 100).unwrap(); + assert_eq!(outcome.copied.len(), 1, "only the non-conflicting record"); + assert_eq!(outcome.skipped.len(), 1); + assert_eq!(outcome.skipped[0].reason, "conflict"); + let migrated_id = outcome.copied[0].record_id.clone(); + assert!( + store + .set_user_protected(&new, &migrated_id, true, 100) + .unwrap() + ); + + // The protected copy and the new identity's own record stay; the other copy is removed. + let reverted = store + .revert_migrated(&new, "publisher-old", "old", 100) + .unwrap(); + assert_eq!(reverted.removed_records, 0); + assert_eq!(reverted.kept_protected_records, 1); + assert!(store.get(&new, &migrated_id, 100).unwrap().is_some()); + assert!( + store + .get(&new, &own.record.record_id, 100) + .unwrap() + .is_some() + ); + assert_eq!(store.usage(&old, 100).unwrap().records, 2); +} diff --git a/crates/platform/src/plugin_storage.rs b/crates/platform/src/plugin_storage.rs new file mode 100644 index 000000000..a13d4529b --- /dev/null +++ b/crates/platform/src/plugin_storage.rs @@ -0,0 +1,2140 @@ +//! Durable private key/value storage of third-party plugins. +//! +//! Every plugin has one store per GameNode account profile, in its own SQLite file below +//! `plugin-data////`. The host decides the +//! directory from the authenticated identity ([`namespace_dir`]); a plugin never names a path or +//! another namespace, and nothing here returns one. A store is opened on a blocking worker, and +//! each [`DurableStore::put`] is one transaction, so a write that would pass the quota changes +//! nothing and a crash leaves either the old value or the new one. +//! +//! The quota counts the logical bytes (key, value and a fixed per-entry overhead), not the +//! file size. Revisions are handed in by the caller, who keeps them growing across deletions and +//! restarts through [`DurableStore::high_water`]. + +use std::fs; +use std::io; +use std::path::{Path, PathBuf}; + +use rusqlite::{Connection, OptionalExtension, TransactionBehavior, params}; +use sha2::{Digest, Sha256}; + +/// The longest key, in bytes. +pub const MAX_KEY_BYTES: usize = 256; +/// The largest value, in bytes. +pub const MAX_VALUE_BYTES: usize = 1024 * 1024; +/// The logical bytes a plugin may keep durably per profile. +pub const QUOTA_BYTES: u64 = 16 * 1024 * 1024; +/// Charged per entry on top of its key and value, so many tiny entries cannot dodge the quota. +pub const ENTRY_OVERHEAD_BYTES: u64 = 64; +/// The longest an entry may live before it expires (30 days). +pub const MAX_TTL_SECONDS: u64 = 30 * 24 * 60 * 60; + +const SCHEMA_VERSION: i64 = 16; +const STORE_FILE: &str = "storage.sqlite3"; +/// Longest directory name derived from an identity before it is replaced by a digest. +const MAX_COMPONENT_BYTES: usize = 120; + +/// Why the store could not be used. Messages never contain a path. +#[derive(Debug, thiserror::Error)] +pub enum PluginStorageError { + #[error("the plugin storage could not be opened")] + Open(#[source] io::Error), + #[error("the plugin storage failed")] + Database(#[source] rusqlite::Error), + #[error("the plugin storage was written by a newer version of GameNode")] + NewerVersion, + #[error("the entry is protected by the user")] + Protected, + #[error("the entry is archived and needs a reviewed reuse")] + Archived, + #[error("a publisher migration needs two different identities")] + InvalidMigration, +} + +impl From for PluginStorageError { + fn from(error: rusqlite::Error) -> Self { + Self::Database(error) + } +} + +/// What the quota charges for one entry. +pub fn charge(key: &str, value_len: usize) -> u64 { + key.len() as u64 + value_len as u64 + ENTRY_OVERHEAD_BYTES +} + +/// A directory name derived from one identity part: readable characters stay, anything else +/// becomes `%XX`, and a name that would be too long or only dots is replaced by a digest. +fn component(part: &str) -> String { + let mut name = String::with_capacity(part.len()); + for byte in part.bytes() { + if byte.is_ascii_alphanumeric() + || matches!(byte, b'-' | b'_') + || (byte == b'.' && !name.is_empty()) + { + name.push(byte as char); + } else { + name.push_str(&format!("%{byte:02X}")); + } + } + if name.is_empty() || name.len() > MAX_COMPONENT_BYTES || name.ends_with('.') { + let digest = Sha256::digest(part.as_bytes()); + let hex: String = digest[..16].iter().map(|b| format!("{b:02x}")).collect(); + return format!("h-{hex}"); + } + name +} + +/// The directory of one plugin's store in one profile below `root` (`plugin-data`). Pure: it +/// creates nothing. +pub fn namespace_dir(root: &Path, publisher: &str, plugin: &str, profile: &str) -> PathBuf { + root.join(component(publisher)) + .join(component(plugin)) + .join(component(profile)) +} + +/// The SQLite file of one plugin's store in one profile below `root` (`plugin-data`). Pure: it +/// creates nothing. Host-only administration uses this to measure the file; no plugin reply ever +/// carries it. +pub fn namespace_store_file(root: &Path, publisher: &str, plugin: &str, profile: &str) -> PathBuf { + namespace_dir(root, publisher, plugin, profile).join(STORE_FILE) +} + +/// Archives one namespace's live private entries without creating a store. `None` means the +/// namespace never wrote anything durably. Used by bundle uninstall, which has no live +/// [`PluginStorage`] worker at that point. +pub fn archive_namespace( + root: &Path, + publisher: &str, + plugin: &str, + profile: &str, +) -> Result, PluginStorageError> { + let dir = namespace_dir(root, publisher, plugin, profile); + let Some(mut store) = DurableStore::open_existing(&dir)? else { + return Ok(None); + }; + let revision = store.high_water()?.saturating_add(1); + store.archive_entries(revision).map(Some) +} + +/// Reads one namespace's logical usage without creating a store. `None` means the namespace never +/// wrote anything durably. Values and the namespace path are never returned. +pub fn namespace_usage( + root: &Path, + publisher: &str, + plugin: &str, + profile: &str, + now: i64, +) -> Result, PluginStorageError> { + let dir = namespace_dir(root, publisher, plugin, profile); + match DurableStore::open_existing(&dir)? { + Some(store) => store.store_usage(now).map(Some), + None => Ok(None), + } +} + +/// Reads the archived entries of one namespace without creating a store. +pub fn namespace_archived_usage( + root: &Path, + publisher: &str, + plugin: &str, + profile: &str, +) -> Result, PluginStorageError> { + let dir = namespace_dir(root, publisher, plugin, profile); + match DurableStore::open_existing(&dir)? { + Some(store) => store.archived_usage().map(Some), + None => Ok(None), + } +} + +/// One source entry as read for a migration copy. Values never leave this module. +struct ExportEntry { + key: String, + value: Vec, + expires_at: Option, + last_used_at: i64, + user_protected: bool, +} + +fn export_entries(conn: &Connection) -> Result, PluginStorageError> { + let mut statement = conn.prepare( + "SELECT key, value, expires_at, last_used_at, user_protected + FROM entries WHERE archived = 0", + )?; + let rows = statement.query_map([], |row| { + Ok(ExportEntry { + key: row.get(0)?, + value: row.get(1)?, + expires_at: row.get(2)?, + last_used_at: row.get(3)?, + user_protected: row.get::<_, i64>(4)? != 0, + }) + })?; + rows.collect::, _>>().map_err(Into::into) +} + +fn stored_keys(conn: &Connection) -> Result, PluginStorageError> { + let mut statement = conn.prepare("SELECT key FROM entries")?; + let rows = statement.query_map([], |row| row.get::<_, String>(0))?; + rows.collect::, _>>() + .map_err(Into::into) +} + +/// Reviews the private data a re-trusted publisher identity could receive from its predecessor. +/// +/// Only the old identity's live, unexpired entries are candidates. Expired rows and rows retained +/// by an uninstall are reported, never copied: the latter need the separate reviewed reuse. A key +/// the new identity already holds is a conflict. Values and paths are never returned and nothing is +/// created or changed. +#[allow(clippy::too_many_arguments)] // Source and target namespace identities plus the clock. +pub fn migration_preview( + root: &Path, + source_publisher: &str, + source_plugin: &str, + source_profile: &str, + target_publisher: &str, + target_plugin: &str, + target_profile: &str, + now: i64, +) -> Result { + let source_dir = namespace_dir(root, source_publisher, source_plugin, source_profile); + let target_dir = namespace_dir(root, target_publisher, target_plugin, target_profile); + if source_dir == target_dir { + return Err(PluginStorageError::InvalidMigration); + } + let mut preview = PrivateMigrationPreview::default(); + let target_keys = match DurableStore::open_existing(&target_dir)? { + Some(store) => { + let usage = store.store_usage(now)?; + preview.target_records = usage + .categories + .iter() + .map(|category| category.records) + .sum::() + .saturating_add(usage.archived_records); + preview.target_logical_bytes = usage.logical_bytes; + stored_keys(&store.conn)? + } + None => Default::default(), + }; + let Some(source_store) = DurableStore::open_existing(&source_dir)? else { + return Ok(preview); + }; + preview.source_present = true; + preview.archived_records = source_store.archived_usage()?.records; + for entry in export_entries(&source_store.conn)? { + if entry.expires_at.is_some_and(|at| at <= now) { + preview.expired_records += 1; + continue; + } + let size = charge(&entry.key, entry.value.len()); + preview.records += 1; + preview.logical_bytes = preview.logical_bytes.saturating_add(size); + if entry.user_protected { + preview.protected_records += 1; + } + if target_keys.contains(&entry.key) { + preview.conflict_records += 1; + } else { + preview.eligible_records += 1; + preview.eligible_bytes = preview.eligible_bytes.saturating_add(size); + } + } + Ok(preview) +} + +/// Copies one private namespace's live entries to a re-trusted publisher identity in one +/// transaction. +/// +/// Keys the new identity already holds are skipped as conflicts and expired rows are not copied; +/// archived rows stay behind for the separate reuse review. The source keeps every row, and each +/// copy records the old publisher fingerprint so a reviewed rollback removes exactly these copies. +/// Blocking: call this on the storage worker. +#[allow(clippy::too_many_arguments)] // Source and target namespace identities plus the clock. +pub fn migrate_namespace( + root: &Path, + source_publisher: &str, + source_plugin: &str, + source_profile: &str, + target_publisher: &str, + target_plugin: &str, + target_profile: &str, + now: i64, +) -> Result { + let source_dir = namespace_dir(root, source_publisher, source_plugin, source_profile); + let target_dir = namespace_dir(root, target_publisher, target_plugin, target_profile); + if source_dir == target_dir { + return Err(PluginStorageError::InvalidMigration); + } + let Some(source_store) = DurableStore::open_existing(&source_dir)? else { + return Ok(PrivateMigrationOutcome::default()); + }; + let entries = export_entries(&source_store.conn)?; + let archived_records = source_store.archived_usage()?.records; + let mut target = DurableStore::open(&target_dir)?; + let mut revision = target.high_water()?; + let mut outcome = PrivateMigrationOutcome { + source_present: true, + archived_records, + ..PrivateMigrationOutcome::default() + }; + let tx = target + .conn + .transaction_with_behavior(TransactionBehavior::Immediate)?; + let mut keys = stored_keys(&tx)?; + for entry in entries { + if entry.expires_at.is_some_and(|at| at <= now) { + outcome.expired_records += 1; + continue; + } + if keys.contains(&entry.key) { + outcome.conflict_records += 1; + continue; + } + revision = revision.saturating_add(1); + let size = charge(&entry.key, entry.value.len()); + tx.execute( + "INSERT INTO entries + (key, value, revision, expires_at, last_used_at, user_protected, migrated_from) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)", + params![ + entry.key.as_str(), + entry.value.as_slice(), + revision as i64, + entry.expires_at, + entry.last_used_at, + i64::from(entry.user_protected), + source_publisher, + ], + )?; + keys.insert(entry.key); + outcome.copied_records += 1; + outcome.copied_bytes = outcome.copied_bytes.saturating_add(size); + } + if outcome.copied_records > 0 { + tx.execute( + "UPDATE meta SET revision = MAX(revision, ?1) WHERE id = 1", + [revision as i64], + )?; + } + tx.commit()?; + Ok(outcome) +} + +/// Removes one migration's copies from the new publisher identity after a reviewed rollback. +/// +/// Only entries tagged with the old fingerprint are removed, and a copy the user protected since +/// the migration stays. The old identity's original namespace is never touched. `None` means the +/// new identity never wrote a durable store. Blocking: call this on the storage worker. +pub fn revert_migrated_namespace( + root: &Path, + target_publisher: &str, + target_plugin: &str, + target_profile: &str, + source_publisher: &str, +) -> Result, PluginStorageError> { + let dir = namespace_dir(root, target_publisher, target_plugin, target_profile); + let Some(mut store) = DurableStore::open_existing(&dir)? else { + return Ok(None); + }; + let revision = store.high_water()?.saturating_add(1); + let tx = store + .conn + .transaction_with_behavior(TransactionBehavior::Immediate)?; + let (records, bytes): (i64, i64) = tx.query_row( + "SELECT COUNT(*), COALESCE(SUM(length(CAST(key AS BLOB)) + length(value) + ?2), 0) + FROM entries WHERE migrated_from = ?1 AND user_protected = 0", + params![source_publisher, ENTRY_OVERHEAD_BYTES as i64], + |row| Ok((row.get(0)?, row.get(1)?)), + )?; + let removed = tx.execute( + "DELETE FROM entries WHERE migrated_from = ?1 AND user_protected = 0", + [source_publisher], + )? as u64; + let kept: i64 = tx.query_row( + "SELECT COUNT(*) FROM entries WHERE migrated_from = ?1 AND user_protected = 1", + [source_publisher], + |row| row.get(0), + )?; + if removed > 0 { + tx.execute( + "UPDATE meta SET revision = MAX(revision, ?1) WHERE id = 1", + [revision as i64], + )?; + } + tx.commit()?; + Ok(Some(PrivateMigrationRevert { + removed_records: records.max(0) as u64, + reclaimed_bytes: bytes.max(0) as u64, + kept_protected_records: kept.max(0) as u64, + })) +} + +/// Removes one plugin/profile private namespace directory. Only that profile directory is +/// removed; the publisher/plugin directories and every other profile stay. A symlink or a +/// non-directory is refused instead of followed. Returns whether there was a directory. +pub fn remove_namespace( + root: &Path, + publisher: &str, + plugin: &str, + profile: &str, +) -> io::Result { + let dir = namespace_dir(root, publisher, plugin, profile); + if !dir.starts_with(root) { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "private data path escapes the plugin-data root", + )); + } + remove_namespace_at(&dir) +} + +/// Removes one already-resolved private namespace directory with the same symlink refusal. +pub fn remove_namespace_at(dir: &Path) -> io::Result { + let metadata = match fs::symlink_metadata(dir) { + Ok(metadata) => metadata, + Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(false), + Err(error) => return Err(error), + }; + if metadata.file_type().is_symlink() || !metadata.is_dir() { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "private data is not a regular directory", + )); + } + fs::remove_dir_all(dir)?; + Ok(true) +} + +/// A stored value as read back. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Stored { + pub value: Vec, + pub revision: u64, + /// Unix seconds, `None` when the entry does not expire. + pub expires_at: Option, +} + +/// Logical metadata for one durable private key; never includes value bytes or a filesystem path. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct PersistenceEntry { + pub key: String, + pub size_bytes: u64, + pub last_used_at: i64, + /// Set only by host administration. A plugin can neither set nor clear it. + pub user_protected: bool, +} + +/// Logical usage of one persistence category; never includes a value or a filesystem path. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct CategoryUsage { + pub category: String, + pub records: u64, + pub logical_bytes: u64, + /// Records in this category the user protected from plugin and retention deletion. + pub protected_records: u64, +} + +/// Logical accounting of one plugin's durable private store. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct StoreUsage { + /// The persistence categories the store currently exposes. Only the `private` category + /// counts against the plugin quota; the list is shaped for future categories. + pub categories: Vec, + /// The quota-charged logical bytes: the sum of `categories`. + pub logical_bytes: u64, + /// SQLite page allocation for the complete namespace database. SQLite metadata and free + /// pages are shared across categories, so this is never a per-category physical figure. + pub physical_bytes_estimate: u64, + /// Entries archived by uninstall Keep. They are inert and excluded from `categories`. + pub archived_records: u64, + /// Logical bytes of the archived entries, not charged against the live quota. + pub archived_logical_bytes: u64, + /// The oldest last-use time among live entries (Unix seconds), if any. + pub oldest_used_at: Option, + /// The stored retention policy of the `private` category, if the user set one. + pub retention: Option, +} + +/// The result of archiving or restoring one owner's private entries. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct PrivateArchiveOutcome { + pub records: u64, + pub logical_bytes: u64, +} + +/// The result of a host cleanup of expired and policy-exceeding records. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct CleanupOutcome { + pub removed_records: u64, + pub reclaimed_bytes: u64, +} + +/// User-approved retention limits for a logical storage category. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct RetentionPolicy { + pub max_age_seconds: u64, + pub max_bytes: u64, +} + +/// Logical metadata of one live private entry for a reviewed publisher migration. It never +/// carries a value or a filesystem path. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct PrivateMigrationEntry { + pub key: String, + pub size_bytes: u64, + pub expires_at: Option, + pub last_used_at: i64, + pub user_protected: bool, +} + +/// What one private namespace of a re-trusted publisher holds for a migration preview. Values and +/// paths are never part of it. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct PrivateMigrationPreview { + /// Whether the old identity ever wrote a durable private store. + pub source_present: bool, + /// Live, unexpired entries of the old identity. + pub records: u64, + pub logical_bytes: u64, + /// Entries that can be copied: live, unexpired and absent from the new identity. + pub eligible_records: u64, + pub eligible_bytes: u64, + /// Keys the new identity already holds (live or archived), so copying would overwrite them. + pub conflict_records: u64, + pub expired_records: u64, + /// Rows retained by an uninstall; they need the separate reviewed reuse before migration. + pub archived_records: u64, + pub protected_records: u64, + /// What the new identity already holds, for context. Never a physical size. + pub target_records: u64, + pub target_logical_bytes: u64, +} + +/// The measured result of copying one private namespace to a re-trusted publisher identity. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct PrivateMigrationOutcome { + pub source_present: bool, + pub copied_records: u64, + pub copied_bytes: u64, + pub conflict_records: u64, + pub expired_records: u64, + pub archived_records: u64, +} + +/// The measured result of removing one migration's copies from the new identity. The old +/// identity's original entries are never touched. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct PrivateMigrationRevert { + pub removed_records: u64, + pub reclaimed_bytes: u64, + /// Migrated entries the user protected since the migration; rollback keeps them. + pub kept_protected_records: u64, +} + +/// The result of a write that did not fail. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PutResult { + /// Stored. `usage` is the logical bytes the namespace now holds. + Stored { usage: u64 }, + /// Nothing changed: the namespace would exceed the quota. `usage` is what it holds. + OverQuota { usage: u64 }, +} + +/// One plugin's durable store in one profile. +pub struct DurableStore { + conn: Connection, +} + +impl DurableStore { + /// Opens the store in `dir`, or `None` when this namespace never stored anything durably. + /// Reading never creates files. + pub fn open_existing(dir: &Path) -> Result, PluginStorageError> { + if !dir.join(STORE_FILE).is_file() { + return Ok(None); + } + Self::open(dir).map(Some) + } + + /// Opens the store in `dir`, creating the directories and the file. + pub fn open(dir: &Path) -> Result { + fs::create_dir_all(dir).map_err(PluginStorageError::Open)?; + let conn = Connection::open(dir.join(STORE_FILE))?; + conn.busy_timeout(std::time::Duration::from_secs(5))?; + let version: i64 = conn.query_row("PRAGMA user_version", [], |row| row.get(0))?; + if version > SCHEMA_VERSION { + return Err(PluginStorageError::NewerVersion); + } + if version < 1 { + conn.execute_batch( + "BEGIN; + CREATE TABLE IF NOT EXISTS meta ( + id INTEGER PRIMARY KEY CHECK (id = 1), + revision INTEGER NOT NULL CHECK (revision >= 0) + ) STRICT; + INSERT OR IGNORE INTO meta (id, revision) VALUES (1, 0); + CREATE TABLE IF NOT EXISTS entries ( + key TEXT PRIMARY KEY, + value BLOB NOT NULL, + revision INTEGER NOT NULL CHECK (revision >= 1), + expires_at INTEGER + ) STRICT; + PRAGMA user_version = 1; + COMMIT;", + )?; + } + if version < 2 { + conn.execute_batch( + "BEGIN; + CREATE TABLE IF NOT EXISTS file_roots ( + id TEXT NOT NULL UNIQUE, + installation_id TEXT NOT NULL, + game_id TEXT NOT NULL, + kind TEXT NOT NULL, + root TEXT NOT NULL, + root_volume INTEGER NOT NULL, + root_node INTEGER NOT NULL, + operations INTEGER NOT NULL CHECK (operations BETWEEN 1 AND 7), + affected TEXT NOT NULL, + approved_at INTEGER NOT NULL, + revoked_at INTEGER, + PRIMARY KEY (installation_id, kind) + ) STRICT; + PRAGMA user_version = 2; + COMMIT;", + )?; + } + if version < 3 { + // How the approved folder was chosen: `user` for a folder the user picked or the + // host suggested, `declared` for one the plugin suggested and the user took. + conn.execute_batch( + "BEGIN; + ALTER TABLE file_roots ADD COLUMN origin TEXT NOT NULL DEFAULT 'user'; + PRAGMA user_version = 3; + COMMIT;", + )?; + } + if version < 4 { + // Confirmations the user asked to remember (launch or install of one game by this + // plugin). The row is the approval: revoking deletes it. + conn.execute_batch( + "BEGIN; + CREATE TABLE IF NOT EXISTS intent_approvals ( + id TEXT NOT NULL UNIQUE, + game_id TEXT NOT NULL, + installation_id TEXT NOT NULL, + operation TEXT NOT NULL CHECK (operation IN ('launch', 'install')), + target_revision INTEGER NOT NULL CHECK (target_revision >= 0), + game_name TEXT NOT NULL, + approved_at INTEGER NOT NULL, + PRIMARY KEY (installation_id, operation) + ) STRICT; + PRAGMA user_version = 4; + COMMIT;", + )?; + } + if version < 5 { + // Save profiles this plugin contributed: where a game's saves live for one runtime. + // They reference folder approvals of the same namespace by id, never a path. + conn.execute_batch( + "BEGIN; + CREATE TABLE IF NOT EXISTS save_profiles ( + id TEXT PRIMARY KEY, + installation_id TEXT NOT NULL, + game_id TEXT NOT NULL, + name TEXT NOT NULL, + name_key TEXT NOT NULL, + runtime_id TEXT NOT NULL, + format_id TEXT NOT NULL, + format_version INTEGER NOT NULL CHECK (format_version >= 0), + metadata TEXT NOT NULL, + directories TEXT NOT NULL, + revision INTEGER NOT NULL CHECK (revision >= 1), + created_at INTEGER NOT NULL, + UNIQUE (installation_id, name_key) + ) STRICT; + PRAGMA user_version = 5; + COMMIT;", + )?; + } + if version < 6 { + conn.execute_batch("BEGIN IMMEDIATE; ALTER TABLE file_roots ADD COLUMN volume_token TEXT NOT NULL DEFAULT ''; PRAGMA user_version = 6; COMMIT;")?; + } + if version < 7 { + conn.execute_batch("BEGIN IMMEDIATE; CREATE TABLE IF NOT EXISTS plugin_libraries (id TEXT PRIMARY KEY, payload TEXT NOT NULL) STRICT; PRAGMA user_version = 7; COMMIT;")?; + } + if version < 8 { + conn.execute_batch("BEGIN IMMEDIATE; CREATE TABLE IF NOT EXISTS backup_sources (profile_id TEXT NOT NULL, destination TEXT NOT NULL, PRIMARY KEY(profile_id,destination)) STRICT; PRAGMA user_version = 8; COMMIT;")?; + } + if version < 9 { + // Custom launch consent is scoped to the exact persisted recipe revision. Existing + // remembered launch/install consent has no recipe, so it migrates with revision 0. + conn.execute_batch( + "BEGIN IMMEDIATE; + ALTER TABLE intent_approvals RENAME TO intent_approvals_v8; + CREATE TABLE intent_approvals ( + id TEXT NOT NULL UNIQUE, + game_id TEXT NOT NULL, + installation_id TEXT NOT NULL, + operation TEXT NOT NULL CHECK (operation IN ('launch', 'custom_launch', 'install')), + target_revision INTEGER NOT NULL CHECK (target_revision >= 0), + recipe_id TEXT NOT NULL, + recipe_revision INTEGER NOT NULL CHECK (recipe_revision >= 0), + game_name TEXT NOT NULL, + approved_at INTEGER NOT NULL, + PRIMARY KEY (installation_id, operation) + ) STRICT; + INSERT INTO intent_approvals + (id, game_id, installation_id, operation, target_revision, + recipe_id, recipe_revision, game_name, approved_at) + SELECT id, game_id, installation_id, operation, target_revision, + '', 0, game_name, approved_at + FROM intent_approvals_v8; + DROP TABLE intent_approvals_v8; + PRAGMA user_version = 9; + COMMIT;", + )?; + } + if version < 10 { + conn.execute_batch("BEGIN IMMEDIATE; ALTER TABLE intent_approvals ADD COLUMN plan_fingerprint TEXT NOT NULL DEFAULT ''; PRAGMA user_version = 10; COMMIT;")?; + } + if version < 11 { + // A store whose version was set back for an upgrade test already has the column. + let has_last_used_at = conn + .prepare("PRAGMA table_info(entries)")? + .query_map([], |row| row.get::<_, String>(1))? + .collect::, _>>()? + .iter() + .any(|name| name == "last_used_at"); + let add_column = if has_last_used_at { + "" + } else { + "ALTER TABLE entries ADD COLUMN last_used_at INTEGER NOT NULL DEFAULT 0;" + }; + conn.execute_batch(&format!( + "BEGIN IMMEDIATE; + {add_column} + CREATE TABLE IF NOT EXISTS retention_policies ( + category TEXT PRIMARY KEY, + max_age_seconds INTEGER NOT NULL CHECK (max_age_seconds >= 0), + max_bytes INTEGER NOT NULL CHECK (max_bytes >= 0) + ) STRICT; + PRAGMA user_version = 11; + COMMIT;" + ))?; + } + if version < 12 { + // Shared emulator resources are declarations beside a profile's folders. Consent is + // stored separately so a changed declaration or scope becomes stale without losing + // the audit trail of what the user last reviewed. + let has_shared_resources = conn + .prepare("PRAGMA table_info(save_profiles)")? + .query_map([], |row| row.get::<_, String>(1))? + .collect::, _>>()? + .iter() + .any(|name| name == "shared_resources"); + let add_column = if has_shared_resources { + "" + } else { + "ALTER TABLE save_profiles ADD COLUMN shared_resources TEXT NOT NULL DEFAULT '[]';" + }; + conn.execute_batch(&format!( + "BEGIN IMMEDIATE; + {add_column} + CREATE TABLE IF NOT EXISTS shared_resource_consents ( + profile_id TEXT NOT NULL, + resource_id TEXT NOT NULL, + declaration TEXT NOT NULL, + scope TEXT NOT NULL, + profile_revision INTEGER NOT NULL CHECK (profile_revision >= 0), + approved_at INTEGER NOT NULL, + PRIMARY KEY (profile_id, resource_id) + ) STRICT; + PRAGMA user_version = 12; + COMMIT;" + ))?; + } + if version < 13 { + // Host-only user protection. Plugins can neither set nor clear it, and retention, + // explicit deletion and cleanup must keep a protected record. + let has_user_protected = conn + .prepare("PRAGMA table_info(entries)")? + .query_map([], |row| row.get::<_, String>(1))? + .collect::, _>>()? + .iter() + .any(|name| name == "user_protected"); + let add_column = if has_user_protected { + "" + } else { + "ALTER TABLE entries ADD COLUMN user_protected INTEGER NOT NULL DEFAULT 0 CHECK (user_protected IN (0, 1));" + }; + conn.execute_batch(&format!( + "BEGIN IMMEDIATE; + {add_column} + PRAGMA user_version = 13; + COMMIT;" + ))?; + } + if version < 14 { + // Host-only uninstall retention. An archived entry is inert: reads, lists, usage, + // retention and cleanup skip it, and a plugin cannot silently replace it. Only the + // reviewed host reuse clears the flag. + let has_archived = conn + .prepare("PRAGMA table_info(entries)")? + .query_map([], |row| row.get::<_, String>(1))? + .collect::, _>>()? + .iter() + .any(|name| name == "archived"); + let add_column = if has_archived { + "" + } else { + "ALTER TABLE entries ADD COLUMN archived INTEGER NOT NULL DEFAULT 0 CHECK (archived IN (0, 1));" + }; + conn.execute_batch(&format!( + "BEGIN IMMEDIATE; + {add_column} + PRAGMA user_version = 14; + COMMIT;" + ))?; + } + if version < 15 { + // Host-only publisher migration. A copied entry names the old publisher fingerprint so + // a reviewed rollback can remove exactly the copies without touching the original + // namespace or a value the old identity never held. A plugin can neither set nor read + // this marker. + let has_migrated_from = conn + .prepare("PRAGMA table_info(entries)")? + .query_map([], |row| row.get::<_, String>(1))? + .collect::, _>>()? + .iter() + .any(|name| name == "migrated_from"); + let add_column = if has_migrated_from { + "" + } else { + "ALTER TABLE entries ADD COLUMN migrated_from TEXT;" + }; + conn.execute_batch(&format!( + "BEGIN IMMEDIATE; + {add_column} + PRAGMA user_version = 15; + COMMIT;" + ))?; + } + if version < 16 { + // One exact executable the user approved for an owned runtime. The path and digest are + // host-only; a plugin sees only the runtime record that references this row. + conn.execute_batch( + "BEGIN IMMEDIATE; + CREATE TABLE IF NOT EXISTS runtime_approvals ( + id TEXT NOT NULL UNIQUE, + runtime_id TEXT PRIMARY KEY, + path TEXT NOT NULL, + volume INTEGER NOT NULL, + node INTEGER NOT NULL, + size INTEGER NOT NULL CHECK (size >= 0), + digest TEXT NOT NULL, + approved_at INTEGER NOT NULL, + revoked_at INTEGER + ) STRICT; + PRAGMA user_version = 16; + COMMIT;", + )?; + } + Ok(Self { conn }) + } + + /// The highest revision this store ever recorded, deletions included. + pub fn high_water(&self) -> Result { + let revision: i64 = + self.conn + .query_row("SELECT revision FROM meta WHERE id = 1", [], |row| { + row.get(0) + })?; + Ok(revision as u64) + } + + /// The entry under `key`, unless it expired at `now` (Unix seconds). An archived entry is + /// invisible until a reviewed host reuse restores it. + pub fn get(&self, key: &str, now: i64) -> Result, PluginStorageError> { + let found = self + .conn + .query_row( + "SELECT value, revision, expires_at FROM entries + WHERE key = ?1 AND archived = 0", + [key], + |row| { + Ok(Stored { + value: row.get(0)?, + revision: row.get::<_, i64>(1)? as u64, + expires_at: row.get(2)?, + }) + }, + ) + .optional()?; + let found = found.filter(|stored| stored.expires_at.is_none_or(|at| at > now)); + if found.is_some() { + self.conn.execute( + "UPDATE entries SET last_used_at = ?2 WHERE key = ?1", + params![key, now], + )?; + } + Ok(found) + } + + /// Lists persistent logical entries in key order without loading their values. + pub fn persistence_entries( + &self, + now: i64, + ) -> Result, PluginStorageError> { + let mut statement = self.conn.prepare( + "SELECT key, length(value), last_used_at, user_protected FROM entries + WHERE archived = 0 AND (expires_at IS NULL OR expires_at > ?1) ORDER BY key", + )?; + let rows = statement.query_map([now], |row| { + Ok(PersistenceEntry { + key: row.get(0)?, + size_bytes: row.get::<_, i64>(1)? as u64, + last_used_at: row.get(2)?, + user_protected: row.get::<_, i64>(3)? != 0, + }) + })?; + rows.collect::, _>>().map_err(Into::into) + } + + /// The retained limits for one logical category. + pub fn retention_policy( + &self, + category: &str, + ) -> Result, PluginStorageError> { + self.conn + .query_row( + "SELECT max_age_seconds, max_bytes FROM retention_policies WHERE category = ?1", + [category], + |row| { + Ok(RetentionPolicy { + max_age_seconds: row.get::<_, i64>(0)? as u64, + max_bytes: row.get::<_, i64>(1)? as u64, + }) + }, + ) + .optional() + .map_err(Into::into) + } + + /// Updates one logical category's retention limits and immediately removes entries that + /// exceed the newly selected age/size bounds. `revision` is the namespace high-water mark. + pub fn set_retention_policy( + &mut self, + category: &str, + policy: RetentionPolicy, + now: i64, + revision: u64, + ) -> Result { + let tx = self + .conn + .transaction_with_behavior(TransactionBehavior::Immediate)?; + tx.execute( + "INSERT INTO retention_policies (category, max_age_seconds, max_bytes) + VALUES (?1, ?2, ?3) + ON CONFLICT(category) DO UPDATE SET + max_age_seconds = excluded.max_age_seconds, + max_bytes = excluded.max_bytes", + params![ + category, + policy.max_age_seconds as i64, + policy.max_bytes as i64 + ], + )?; + let reclaimed = prune_to_policy(&tx, category, policy, now, None)?; + tx.execute( + "UPDATE meta SET revision = MAX(revision, ?1) WHERE id = 1", + [revision as i64], + )?; + tx.commit()?; + Ok(reclaimed) + } + + /// Deletes selected logical keys in one transaction and advances the namespace revision. + /// A user-protected key refuses the set, so a plugin cannot delete protected data by naming + /// it in a bulk deletion. + pub fn delete_persistence_entries( + &mut self, + keys: &[String], + now: i64, + revision: u64, + ) -> Result { + let tx = self + .conn + .transaction_with_behavior(TransactionBehavior::Immediate)?; + for key in keys { + let protected: Option = tx + .query_row( + "SELECT user_protected FROM entries WHERE key = ?1 AND archived = 0 + AND (expires_at IS NULL OR expires_at > ?2)", + params![key, now], + |row| row.get(0), + ) + .optional()?; + if protected == Some(1) { + return Err(PluginStorageError::Protected); + } + } + let mut reclaimed = 0_u64; + for key in keys { + let size: Option = tx + .query_row( + "SELECT length(value) FROM entries WHERE key = ?1 AND archived = 0 + AND (expires_at IS NULL OR expires_at > ?2)", + params![key, now], + |row| row.get(0), + ) + .optional()?; + if let Some(size) = size { + reclaimed = reclaimed.saturating_add(charge(key, size as usize)); + tx.execute("DELETE FROM entries WHERE key = ?1 AND archived = 0", [key])?; + } + } + tx.execute( + "UPDATE meta SET revision = MAX(revision, ?1) WHERE id = 1", + [revision as i64], + )?; + tx.commit()?; + Ok(reclaimed) + } + + /// Approximate database page allocation without disclosing its path. Metadata and free pages + /// are shared by every category in the same file. + pub fn physical_bytes(&self) -> Result { + let page_count: i64 = self + .conn + .query_row("PRAGMA page_count", [], |row| row.get(0))?; + let page_size: i64 = self + .conn + .query_row("PRAGMA page_size", [], |row| row.get(0))?; + Ok(page_count.max(0) as u64 * page_size.max(0) as u64) + } + + /// The logical bytes held at `now`, expired entries not counted. + pub fn usage(&self, now: i64) -> Result { + usage_of(&self.conn, now, None) + } + + /// Per-category logical accounting plus the namespace-wide physical estimate. Values and + /// paths never leave the store. + pub fn store_usage(&self, now: i64) -> Result { + let (records, logical_bytes, protected_records, oldest_used_at): ( + i64, + i64, + i64, + Option, + ) = self.conn.query_row( + "SELECT COUNT(*), + COALESCE(SUM(length(CAST(key AS BLOB)) + length(value) + ?1), 0), + COALESCE(SUM(user_protected), 0), + MIN(last_used_at) + FROM entries + WHERE archived = 0 AND (expires_at IS NULL OR expires_at > ?2)", + params![ENTRY_OVERHEAD_BYTES as i64, now], + |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?)), + )?; + let (archived_records, archived_logical_bytes): (i64, i64) = self.conn.query_row( + "SELECT COUNT(*), + COALESCE(SUM(length(CAST(key AS BLOB)) + length(value) + ?1), 0) + FROM entries WHERE archived = 1", + [ENTRY_OVERHEAD_BYTES as i64], + |row| Ok((row.get(0)?, row.get(1)?)), + )?; + let category = CategoryUsage { + category: "private".to_owned(), + records: records.max(0) as u64, + logical_bytes: logical_bytes.max(0) as u64, + protected_records: protected_records.max(0) as u64, + }; + Ok(StoreUsage { + logical_bytes: category.logical_bytes, + categories: vec![category], + physical_bytes_estimate: self.physical_bytes()?, + archived_records: archived_records.max(0) as u64, + archived_logical_bytes: archived_logical_bytes.max(0) as u64, + oldest_used_at, + retention: self.retention_policy("private")?, + }) + } + + /// Applies the host-only user protection decision. A plugin RPC has no way to reach this. + pub fn set_user_protected( + &mut self, + key: &str, + protected: bool, + ) -> Result { + let changed = self.conn.execute( + "UPDATE entries SET user_protected = ?2 WHERE key = ?1 AND archived = 0", + params![key, i64::from(protected as u8)], + )?; + Ok(changed != 0) + } + + /// Makes every live entry of this namespace inert for uninstall Keep. The rows stay on disk + /// with their revisions; only the host reviewed reuse restores them. + pub fn archive_entries( + &mut self, + revision: u64, + ) -> Result { + let tx = self + .conn + .transaction_with_behavior(TransactionBehavior::Immediate)?; + let archived = tx.execute("UPDATE entries SET archived = 1 WHERE archived = 0", [])? as u64; + let (_, logical_bytes): (i64, i64) = tx.query_row( + "SELECT COUNT(*), COALESCE(SUM(length(CAST(key AS BLOB)) + length(value) + ?1), 0) + FROM entries WHERE archived = 1", + [ENTRY_OVERHEAD_BYTES as i64], + |row| Ok((row.get(0)?, row.get(1)?)), + )?; + tx.execute( + "UPDATE meta SET revision = MAX(revision, ?1) WHERE id = 1", + [revision as i64], + )?; + tx.commit()?; + Ok(PrivateArchiveOutcome { + records: archived, + logical_bytes: logical_bytes.max(0) as u64, + }) + } + + /// Restores this owner's archived entries after an explicit host review. Expired archived + /// rows are discarded instead of being restored as visible-but-expired entries. + pub fn reuse_archived_entries( + &mut self, + now: i64, + revision: u64, + ) -> Result { + let tx = self + .conn + .transaction_with_behavior(TransactionBehavior::Immediate)?; + tx.execute( + "DELETE FROM entries WHERE archived = 1 + AND expires_at IS NOT NULL AND expires_at <= ?1", + [now], + )?; + let restored = tx.execute("UPDATE entries SET archived = 0 WHERE archived = 1", [])? as u64; + let (_, logical_bytes): (i64, i64) = tx.query_row( + "SELECT COUNT(*), COALESCE(SUM(length(CAST(key AS BLOB)) + length(value) + ?1), 0) + FROM entries WHERE archived = 0 + AND (expires_at IS NULL OR expires_at > ?2)", + params![ENTRY_OVERHEAD_BYTES as i64, now], + |row| Ok((row.get(0)?, row.get(1)?)), + )?; + tx.execute( + "UPDATE meta SET revision = MAX(revision, ?1) WHERE id = 1", + [revision as i64], + )?; + tx.commit()?; + Ok(PrivateArchiveOutcome { + records: restored, + logical_bytes: logical_bytes.max(0) as u64, + }) + } + + /// The archived entries of this owner, without their values or a path. Used by the host + /// review of retained data; a plugin RPC cannot reach it. + pub fn archived_usage(&self) -> Result { + let (records, logical_bytes): (i64, i64) = self.conn.query_row( + "SELECT COUNT(*), COALESCE(SUM(length(CAST(key AS BLOB)) + length(value) + ?1), 0) + FROM entries WHERE archived = 1", + [ENTRY_OVERHEAD_BYTES as i64], + |row| Ok((row.get(0)?, row.get(1)?)), + )?; + Ok(PrivateArchiveOutcome { + records: records.max(0) as u64, + logical_bytes: logical_bytes.max(0) as u64, + }) + } + + /// Reclaims this owner's archived, unprotected entries in a reviewed host cleanup. A + /// protected archived entry stays until the user lifts its protection. Advances the + /// namespace revision so cursors cannot resume across the change. + pub fn reclaim_archived( + &mut self, + revision: u64, + ) -> Result { + let tx = self + .conn + .transaction_with_behavior(TransactionBehavior::Immediate)?; + let (records, logical_bytes): (i64, i64) = tx.query_row( + "SELECT COUNT(*), COALESCE(SUM(length(CAST(key AS BLOB)) + length(value) + ?1), 0) + FROM entries WHERE archived = 1 AND user_protected = 0", + [ENTRY_OVERHEAD_BYTES as i64], + |row| Ok((row.get(0)?, row.get(1)?)), + )?; + tx.execute( + "DELETE FROM entries WHERE archived = 1 AND user_protected = 0", + [], + )?; + tx.execute( + "UPDATE meta SET revision = MAX(revision, ?1) WHERE id = 1", + [revision as i64], + )?; + tx.commit()?; + Ok(PrivateArchiveOutcome { + records: records.max(0) as u64, + logical_bytes: logical_bytes.max(0) as u64, + }) + } + + /// Removes expired records and applies the stored retention policy while keeping every + /// user-protected record. This is a host cleanup, separate from a plugin mutation. + pub fn cleanup(&mut self, now: i64) -> Result { + let tx = self + .conn + .transaction_with_behavior(TransactionBehavior::Immediate)?; + let before_records: i64 = tx.query_row( + "SELECT COUNT(*) FROM entries WHERE archived = 0", + [], + |row| row.get(0), + )?; + let before_bytes = usage_of(&tx, i64::MIN, None)?; + tx.execute( + "DELETE FROM entries WHERE archived = 0 AND user_protected = 0 + AND expires_at IS NOT NULL AND expires_at <= ?1", + [now], + )?; + let policy = tx + .query_row( + "SELECT max_age_seconds, max_bytes FROM retention_policies WHERE category = 'private'", + [], + |row| { + Ok(RetentionPolicy { + max_age_seconds: row.get::<_, i64>(0)? as u64, + max_bytes: row.get::<_, i64>(1)? as u64, + }) + }, + ) + .optional()? + .unwrap_or_default(); + prune_to_policy(&tx, "private", policy, now, None)?; + let after_records: i64 = tx.query_row( + "SELECT COUNT(*) FROM entries WHERE archived = 0", + [], + |row| row.get(0), + )?; + let after_bytes = usage_of(&tx, i64::MIN, None)?; + tx.commit()?; + Ok(CleanupOutcome { + removed_records: before_records.saturating_sub(after_records).max(0) as u64, + reclaimed_bytes: before_bytes.saturating_sub(after_bytes), + }) + } + + /// Stores `value` under `key` with `revision`, replacing any entry, unless the namespace + /// would hold more than `quota` bytes afterwards. Expired entries are dropped in the same + /// transaction. The caller has already checked the expected revision. + pub fn put( + &mut self, + key: &str, + value: &[u8], + revision: u64, + expires_at: Option, + now: i64, + quota: u64, + ) -> Result { + let tx = self + .conn + .transaction_with_behavior(TransactionBehavior::Immediate)?; + tx.execute( + "DELETE FROM entries WHERE archived = 0 AND user_protected = 0 + AND expires_at IS NOT NULL AND expires_at <= ?1", + [now], + )?; + let archived: bool = tx.query_row( + "SELECT EXISTS(SELECT 1 FROM entries WHERE key = ?1 AND archived = 1)", + [key], + |row| row.get(0), + )?; + if archived { + return Err(PluginStorageError::Archived); + } + let protected: Option = tx + .query_row( + "SELECT user_protected FROM entries WHERE key = ?1", + [key], + |row| row.get(0), + ) + .optional()?; + if protected == Some(1) { + return Err(PluginStorageError::Protected); + } + let policy = tx + .query_row( + "SELECT max_age_seconds, max_bytes FROM retention_policies WHERE category = 'private'", + [], + |row| { + Ok(RetentionPolicy { + max_age_seconds: row.get::<_, i64>(0)? as u64, + max_bytes: row.get::<_, i64>(1)? as u64, + }) + }, + ) + .optional()? + .unwrap_or_default(); + prune_to_policy(&tx, "private", policy, now, Some(key))?; + let others = usage_of(&tx, now, Some(key))?; + let current = usage_of(&tx, now, None)?; + if others.saturating_add(charge(key, value.len())) > quota { + return Ok(PutResult::OverQuota { usage: current }); + } + tx.execute( + "INSERT INTO entries (key, value, revision, expires_at, last_used_at) VALUES (?1, ?2, ?3, ?4, ?5) + ON CONFLICT(key) DO UPDATE SET + value = excluded.value, + revision = excluded.revision, + expires_at = excluded.expires_at, + last_used_at = excluded.last_used_at", + params![key, value, revision as i64, expires_at, now], + )?; + tx.execute( + "UPDATE meta SET revision = MAX(revision, ?1) WHERE id = 1", + [revision as i64], + )?; + tx.commit()?; + Ok(PutResult::Stored { + usage: others + charge(key, value.len()), + }) + } + + /// Deletes `key`. Returns the revision it had, or `None` when there was no such entry. A + /// user-protected key is refused. + pub fn remove(&mut self, key: &str) -> Result, PluginStorageError> { + let tx = self + .conn + .transaction_with_behavior(TransactionBehavior::Immediate)?; + let entry: Option<(i64, i64)> = tx + .query_row( + "SELECT revision, user_protected FROM entries WHERE key = ?1 AND archived = 0", + [key], + |row| Ok((row.get(0)?, row.get(1)?)), + ) + .optional()?; + let Some((revision, protected)) = entry else { + return Ok(None); + }; + if protected != 0 { + return Err(PluginStorageError::Protected); + } + tx.execute("DELETE FROM entries WHERE key = ?1 AND archived = 0", [key])?; + tx.commit()?; + Ok(Some(revision as u64)) + } +} + +fn prune_to_policy( + tx: &rusqlite::Transaction<'_>, + category: &str, + policy: RetentionPolicy, + now: i64, + keep_key: Option<&str>, +) -> Result { + if category != "private" { + return Ok(0); + } + let mut reclaimed = 0_u64; + if policy.max_age_seconds > 0 { + let cutoff = now.saturating_sub(policy.max_age_seconds.min(i64::MAX as u64) as i64); + let mut statement = tx.prepare( + "SELECT key, length(value) FROM entries WHERE archived = 0 AND user_protected = 0 + AND last_used_at <= ?1 AND (?2 IS NULL OR key != ?2)", + )?; + let old = statement + .query_map(params![cutoff, keep_key], |row| { + Ok((row.get::<_, String>(0)?, row.get::<_, i64>(1)? as usize)) + })? + .collect::, _>>()?; + drop(statement); + for (key, size) in old { + tx.execute( + "DELETE FROM entries WHERE key = ?1 AND archived = 0", + [&key], + )?; + reclaimed = reclaimed.saturating_add(charge(&key, size)); + } + } + if policy.max_bytes > 0 { + let mut usage = usage_of(tx, now, None)?; + while usage > policy.max_bytes { + let oldest = tx + .query_row( + "SELECT key, length(value) FROM entries + WHERE archived = 0 AND user_protected = 0 + AND (?1 IS NULL OR key != ?1) + AND (expires_at IS NULL OR expires_at > ?2) + ORDER BY last_used_at ASC, key ASC LIMIT 1", + params![keep_key, now], + |row| Ok((row.get::<_, String>(0)?, row.get::<_, i64>(1)? as usize)), + ) + .optional()?; + let Some((key, size)) = oldest else { + break; + }; + let bytes = charge(&key, size); + tx.execute( + "DELETE FROM entries WHERE key = ?1 AND archived = 0", + [&key], + )?; + usage = usage.saturating_sub(bytes); + reclaimed = reclaimed.saturating_add(bytes); + } + } + Ok(reclaimed) +} + +/// The file operations a root approval allows. +pub mod operation { + pub const READ: u8 = 1; + pub const WRITE: u8 = 2; + pub const DELETE: u8 = 4; +} + +/// A folder the user approved for one plugin and one installation of a game. +/// +/// It is kept per plugin and account profile, apart from the plugin's key/value data and not +/// charged to its quota. The plugin never sees `root`; it only receives handles issued for the +/// approval while it is current. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct FileApproval { + /// Opaque random id; a new approval of the same installation and kind gets a new one. + pub id: String, + pub installation_id: String, + /// The GameNode game the installation was matched to when approved (empty if none). + pub game_id: String, + /// What the folder is: `installation`, `save` or `prefix`. + pub kind: String, + /// The canonical location, valid Unicode. + pub root: String, + pub volume_token: String, + pub root_volume: u64, + pub root_node: u64, + /// A combination of [`operation`] bits. + pub operations: u8, + /// The library entries that overlapped the folder when the user approved it, sorted. The + /// approval holds only while this is still the complete set. + pub affected: Vec, + /// Unix seconds. + pub approved_at: i64, + /// Unix seconds; a revoked approval opens nothing. + pub revoked_at: Option, + /// How the folder was chosen: [`ORIGIN_USER`] or [`ORIGIN_DECLARED`]. + pub origin: String, +} + +/// The user picked the folder, or took the one the host suggested. +pub const ORIGIN_USER: &str = "user"; +/// The user took a folder the plugin had suggested (declared, not verified by the host). +pub const ORIGIN_DECLARED: &str = "declared"; + +fn approval_from(row: &rusqlite::Row<'_>) -> rusqlite::Result { + let affected: String = row.get(8)?; + Ok(FileApproval { + id: row.get(0)?, + installation_id: row.get(1)?, + game_id: row.get(2)?, + kind: row.get(3)?, + root: row.get(4)?, + root_volume: row.get::<_, i64>(5)? as u64, + root_node: row.get::<_, i64>(6)? as u64, + operations: row.get::<_, i64>(7)? as u8, + affected: serde_json::from_str(&affected).unwrap_or_default(), + approved_at: row.get(9)?, + revoked_at: row.get(10)?, + origin: row.get(11)?, + volume_token: row.get(12)?, + }) +} + +/// Where the user's chosen executable is and what it was when approved. +/// +/// It is kept per plugin and account profile, apart from the plugin's key/value data and not +/// charged to its quota. The plugin never sees `path`: the runtime record points at this approval, +/// and the host resolves the path only after checking the identity and digest before a launch. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct RuntimeApproval { + /// Opaque random id in the runtime's durable file reference; a reapproval gets a new one. + pub id: String, + /// The owned runtime this approval belongs to. + pub runtime_id: String, + /// The canonical executable location, valid Unicode. + pub path: String, + /// The volume and node identity of the approved file. + pub volume: u64, + pub node: u64, + pub size: u64, + /// Lowercase hexadecimal SHA-256 of the approved file. + pub digest: String, + /// Unix seconds. + pub approved_at: i64, + /// Unix seconds; a revoked approval launches nothing. + pub revoked_at: Option, +} + +fn runtime_approval_from(row: &rusqlite::Row<'_>) -> rusqlite::Result { + Ok(RuntimeApproval { + id: row.get(0)?, + runtime_id: row.get(1)?, + path: row.get(2)?, + volume: row.get::<_, i64>(3)? as u64, + node: row.get::<_, i64>(4)? as u64, + size: row.get::<_, i64>(5)? as u64, + digest: row.get(6)?, + approved_at: row.get(7)?, + revoked_at: row.get(8)?, + }) +} + +const RUNTIME_APPROVAL_COLUMNS: &str = + "id, runtime_id, path, volume, node, size, digest, approved_at, revoked_at"; + +impl DurableStore { + /// Records `approval`, replacing the earlier approval of the same runtime. + pub fn save_runtime_approval( + &mut self, + approval: &RuntimeApproval, + ) -> Result<(), PluginStorageError> { + self.conn.execute( + "INSERT INTO runtime_approvals + (id, runtime_id, path, volume, node, size, digest, approved_at, revoked_at) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9) + ON CONFLICT(runtime_id) DO UPDATE SET + id = excluded.id, + path = excluded.path, + volume = excluded.volume, + node = excluded.node, + size = excluded.size, + digest = excluded.digest, + approved_at = excluded.approved_at, + revoked_at = excluded.revoked_at", + rusqlite::params![ + approval.id, + approval.runtime_id, + approval.path, + approval.volume as i64, + approval.node as i64, + approval.size as i64, + approval.digest, + approval.approved_at, + approval.revoked_at, + ], + )?; + Ok(()) + } + + /// The approval for `runtime_id`, revoked or active. + pub fn runtime_approval_for( + &self, + runtime_id: &str, + ) -> Result, PluginStorageError> { + Ok(self + .conn + .query_row( + &format!( + "SELECT {RUNTIME_APPROVAL_COLUMNS} FROM runtime_approvals + WHERE runtime_id = ?1" + ), + [runtime_id], + runtime_approval_from, + ) + .optional()?) + } + + /// The approval with this id, revoked or active. + pub fn runtime_approval_by_id( + &self, + id: &str, + ) -> Result, PluginStorageError> { + Ok(self + .conn + .query_row( + &format!( + "SELECT {RUNTIME_APPROVAL_COLUMNS} FROM runtime_approvals + WHERE id = ?1" + ), + [id], + runtime_approval_from, + ) + .optional()?) + } + + /// Every runtime approval in this namespace, revoked or active. + pub fn runtime_approvals(&self) -> Result, PluginStorageError> { + let mut statement = self.conn.prepare(&format!( + "SELECT {RUNTIME_APPROVAL_COLUMNS} FROM runtime_approvals ORDER BY approved_at, id" + ))?; + let rows = statement.query_map([], runtime_approval_from)?; + Ok(rows.collect::, _>>()?) + } + + /// Revokes the approval of `runtime_id`; a missing or already revoked approval is not an error. + pub fn revoke_runtime_approval( + &mut self, + runtime_id: &str, + at: i64, + ) -> Result { + let changed = self.conn.execute( + "UPDATE runtime_approvals SET revoked_at = ?2 + WHERE runtime_id = ?1 AND revoked_at IS NULL", + rusqlite::params![runtime_id, at], + )?; + Ok(changed > 0) + } +} + +const APPROVAL_COLUMNS: &str = "id, installation_id, game_id, kind, root, root_volume, root_node, \ + operations, affected, approved_at, revoked_at, origin, volume_token"; + +impl DurableStore { + /// Records `approval`, replacing the earlier approval of the same installation and kind. + pub fn save_approval(&mut self, approval: &FileApproval) -> Result<(), PluginStorageError> { + let affected = serde_json::to_string(&approval.affected).unwrap_or_else(|_| "[]".into()); + self.conn.execute( + "INSERT INTO file_roots (id, installation_id, game_id, kind, root, root_volume, + root_node, operations, affected, approved_at, revoked_at, origin, volume_token) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13) + ON CONFLICT(installation_id, kind) DO UPDATE SET + id = excluded.id, game_id = excluded.game_id, root = excluded.root, + root_volume = excluded.root_volume, root_node = excluded.root_node, + operations = excluded.operations, affected = excluded.affected, + approved_at = excluded.approved_at, revoked_at = excluded.revoked_at, + origin = excluded.origin, volume_token = excluded.volume_token", + params![ + approval.id, + approval.installation_id, + approval.game_id, + approval.kind, + approval.root, + approval.root_volume as i64, + approval.root_node as i64, + i64::from(approval.operations), + affected, + approval.approved_at, + approval.revoked_at, + approval.origin, + approval.volume_token, + ], + )?; + Ok(()) + } + + /// The approval of `installation_id` for `kind`, revoked or not. + pub fn approval_for( + &self, + installation_id: &str, + kind: &str, + ) -> Result, PluginStorageError> { + Ok(self + .conn + .query_row( + &format!( + "SELECT {APPROVAL_COLUMNS} FROM file_roots + WHERE installation_id = ?1 AND kind = ?2" + ), + params![installation_id, kind], + approval_from, + ) + .optional()?) + } + + /// The approval with this id, revoked or not. + pub fn approval(&self, id: &str) -> Result, PluginStorageError> { + Ok(self + .conn + .query_row( + &format!("SELECT {APPROVAL_COLUMNS} FROM file_roots WHERE id = ?1"), + [id], + approval_from, + ) + .optional()?) + } + + /// Every approval, in a stable order. + pub fn approvals(&self) -> Result, PluginStorageError> { + let mut statement = self.conn.prepare(&format!( + "SELECT {APPROVAL_COLUMNS} FROM file_roots ORDER BY installation_id, kind" + ))?; + let rows = statement.query_map([], approval_from)?; + Ok(rows.collect::, _>>()?) + } + + /// Revokes an approval; its handles stop working at once. Returns whether it was active. + pub fn revoke_approval(&mut self, id: &str, now: i64) -> Result { + let changed = self.conn.execute( + "UPDATE file_roots SET revoked_at = ?2 WHERE id = ?1 AND revoked_at IS NULL", + params![id, now], + )?; + Ok(changed > 0) + } +} + +/// A confirmation the user asked the host to remember: this plugin may launch (or install) this +/// game without asking again, while the game's detected target is the one approved. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct IntentApproval { + /// Opaque random id the settings list uses to revoke it. + pub id: String, + pub game_id: String, + pub installation_id: String, + /// `launch`, `custom_launch`, or `install`. + pub operation: String, + /// The detected-target revision approved (0 for an install, which has none). + pub target_revision: u64, + /// The custom recipe id approved (empty for normal launch and install). + pub recipe_id: String, + /// The custom recipe revision approved (0 for normal launch and install). + pub recipe_revision: u64, + /// Canonical launch-plan approval fingerprint; empty on legacy approvals that must reconfirm. + pub plan_fingerprint: String, + /// The game's name when approved, for the list; plain text. + pub game_name: String, + pub approved_at: i64, +} + +const INTENT_COLUMNS: &str = "id, game_id, installation_id, operation, target_revision, recipe_id, recipe_revision, game_name, approved_at, plan_fingerprint"; + +fn intent_from(row: &rusqlite::Row<'_>) -> rusqlite::Result { + Ok(IntentApproval { + id: row.get(0)?, + game_id: row.get(1)?, + installation_id: row.get(2)?, + operation: row.get(3)?, + target_revision: row.get::<_, i64>(4)? as u64, + recipe_id: row.get(5)?, + recipe_revision: row.get::<_, i64>(6)? as u64, + game_name: row.get(7)?, + approved_at: row.get(8)?, + plan_fingerprint: row.get(9)?, + }) +} + +impl DurableStore { + /// Remembers `approval`, replacing the earlier one for the same installation and operation. + pub fn save_intent_approval( + &mut self, + approval: &IntentApproval, + ) -> Result<(), PluginStorageError> { + self.conn.execute( + "INSERT INTO intent_approvals (id, game_id, installation_id, operation, + target_revision, recipe_id, recipe_revision, game_name, approved_at, plan_fingerprint) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10) + ON CONFLICT(installation_id, operation) DO UPDATE SET + id = excluded.id, game_id = excluded.game_id, + target_revision = excluded.target_revision, + recipe_id = excluded.recipe_id, + recipe_revision = excluded.recipe_revision, game_name = excluded.game_name, + approved_at = excluded.approved_at, plan_fingerprint = excluded.plan_fingerprint", + params![ + approval.id, + approval.game_id, + approval.installation_id, + approval.operation, + approval.target_revision as i64, + approval.recipe_id, + approval.recipe_revision as i64, + approval.game_name, + approval.approved_at, + approval.plan_fingerprint, + ], + )?; + Ok(()) + } + + /// The remembered approval of `installation_id` for `operation`. + pub fn intent_approval( + &self, + installation_id: &str, + operation: &str, + ) -> Result, PluginStorageError> { + Ok(self + .conn + .query_row( + &format!( + "SELECT {INTENT_COLUMNS} FROM intent_approvals + WHERE installation_id = ?1 AND operation = ?2" + ), + params![installation_id, operation], + intent_from, + ) + .optional()?) + } + + /// Every remembered approval, in a stable order. + pub fn intent_approvals(&self) -> Result, PluginStorageError> { + let mut statement = self.conn.prepare(&format!( + "SELECT {INTENT_COLUMNS} FROM intent_approvals ORDER BY installation_id, operation" + ))?; + let rows = statement.query_map([], intent_from)?; + Ok(rows.collect::, _>>()?) + } + + /// Forgets an approval; the next request asks the user again. Returns whether it existed. + pub fn revoke_intent_approval(&mut self, id: &str) -> Result { + let changed = self + .conn + .execute("DELETE FROM intent_approvals WHERE id = ?1", [id])?; + Ok(changed > 0) + } +} + +/// A save profile a plugin contributed, as stored. `directories` and `metadata` are JSON the host +/// wrote and validated; the store only keeps them. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct SaveProfileRow { + pub id: String, + pub installation_id: String, + /// The GameNode game the installation was matched to when created (empty if none). A later + /// rematch does not change it. + pub game_id: String, + pub name: String, + pub runtime_id: String, + pub format_id: String, + pub format_version: u32, + pub metadata: String, + pub directories: String, + /// Host-resolved shared emulator resource declarations, as JSON. The store only keeps them. + pub shared_resources: String, + pub revision: u64, + pub created_at: i64, +} + +/// How writing a profile ended. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ProfileSaved { + Saved, + /// The installation already has a profile with this name (compared without case). + NameTaken, +} + +const PROFILE_COLUMNS: &str = "id, installation_id, game_id, name, runtime_id, format_id, \ + format_version, metadata, directories, shared_resources, revision, created_at"; + +fn profile_from(row: &rusqlite::Row<'_>) -> rusqlite::Result { + Ok(SaveProfileRow { + id: row.get(0)?, + installation_id: row.get(1)?, + game_id: row.get(2)?, + name: row.get(3)?, + runtime_id: row.get(4)?, + format_id: row.get(5)?, + format_version: row.get::<_, i64>(6)? as u32, + metadata: row.get(7)?, + directories: row.get(8)?, + shared_resources: row.get(9)?, + revision: row.get::<_, i64>(10)? as u64, + created_at: row.get(11)?, + }) +} + +impl DurableStore { + /// Inserts or replaces the profile with `row.id`, and raises the store's revision high-water + /// mark to `row.revision` so no revision is ever handed out twice. + pub fn save_profile( + &mut self, + row: &SaveProfileRow, + ) -> Result { + let tx = self.conn.transaction()?; + let name_key = row.name.to_lowercase(); + let written = tx.execute( + "INSERT INTO save_profiles (id, installation_id, game_id, name, name_key, runtime_id, + format_id, format_version, metadata, directories, shared_resources, revision, + created_at) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13) + ON CONFLICT(id) DO UPDATE SET + name = excluded.name, name_key = excluded.name_key, + runtime_id = excluded.runtime_id, format_id = excluded.format_id, + format_version = excluded.format_version, metadata = excluded.metadata, + directories = excluded.directories, + shared_resources = excluded.shared_resources, revision = excluded.revision", + params![ + row.id, + row.installation_id, + row.game_id, + row.name, + name_key, + row.runtime_id, + row.format_id, + i64::from(row.format_version), + row.metadata, + row.directories, + row.shared_resources, + row.revision as i64, + row.created_at, + ], + ); + match written { + Ok(_) => {} + Err(rusqlite::Error::SqliteFailure(error, _)) + if error.code == rusqlite::ErrorCode::ConstraintViolation => + { + return Ok(ProfileSaved::NameTaken); + } + Err(other) => return Err(other.into()), + } + tx.execute( + "UPDATE meta SET revision = MAX(revision, ?1) WHERE id = 1", + [row.revision as i64], + )?; + tx.commit()?; + Ok(ProfileSaved::Saved) + } + + /// The profile with this id. + pub fn save_profile_row(&self, id: &str) -> Result, PluginStorageError> { + Ok(self + .conn + .query_row( + &format!("SELECT {PROFILE_COLUMNS} FROM save_profiles WHERE id = ?1"), + [id], + profile_from, + ) + .optional()?) + } + + /// Every profile, ordered by installation and id. + pub fn save_profile_rows(&self) -> Result, PluginStorageError> { + let mut statement = self.conn.prepare(&format!( + "SELECT {PROFILE_COLUMNS} FROM save_profiles ORDER BY installation_id, id" + ))?; + let rows = statement.query_map([], profile_from)?; + Ok(rows.collect::, _>>()?) + } + + /// Removes the profile, raising the revision high-water mark to `revision` (the removal's own + /// revision). Returns whether it existed. + pub fn delete_save_profile( + &mut self, + id: &str, + revision: u64, + ) -> Result { + let tx = self.conn.transaction()?; + let removed = tx.execute("DELETE FROM save_profiles WHERE id = ?1", [id])?; + tx.execute( + "DELETE FROM shared_resource_consents WHERE profile_id = ?1", + [id], + )?; + tx.execute( + "UPDATE meta SET revision = MAX(revision, ?1) WHERE id = 1", + [revision as i64], + )?; + tx.commit()?; + Ok(removed > 0) + } +} + +/// A persisted user decision about one declared shared resource. `declaration` and `scope` are +/// canonical host fingerprints, never plugin-supplied text. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct SharedResourceConsentRow { + pub profile_id: String, + pub resource_id: String, + pub declaration: String, + pub scope: String, + pub profile_revision: u64, + pub approved_at: i64, +} + +impl DurableStore { + /// Records or replaces the user's decision for one declaration. + pub fn save_shared_resource_consent( + &mut self, + row: &SharedResourceConsentRow, + ) -> Result<(), PluginStorageError> { + self.conn.execute( + "INSERT INTO shared_resource_consents + (profile_id, resource_id, declaration, scope, profile_revision, approved_at) + VALUES (?1, ?2, ?3, ?4, ?5, ?6) + ON CONFLICT(profile_id, resource_id) DO UPDATE SET + declaration = excluded.declaration, scope = excluded.scope, + profile_revision = excluded.profile_revision, + approved_at = excluded.approved_at", + params![ + row.profile_id, + row.resource_id, + row.declaration, + row.scope, + row.profile_revision as i64, + row.approved_at, + ], + )?; + Ok(()) + } + + /// The decision for one declaration, if the user made one. + pub fn shared_resource_consent( + &self, + profile_id: &str, + resource_id: &str, + ) -> Result, PluginStorageError> { + Ok(self + .conn + .query_row( + "SELECT profile_id, resource_id, declaration, scope, profile_revision, approved_at + FROM shared_resource_consents WHERE profile_id = ?1 AND resource_id = ?2", + params![profile_id, resource_id], + |row| { + Ok(SharedResourceConsentRow { + profile_id: row.get(0)?, + resource_id: row.get(1)?, + declaration: row.get(2)?, + scope: row.get(3)?, + profile_revision: row.get::<_, i64>(4)? as u64, + approved_at: row.get(5)?, + }) + }, + ) + .optional()?) + } + + /// Every decision kept for a profile. + pub fn shared_resource_consents( + &self, + profile_id: &str, + ) -> Result, PluginStorageError> { + let mut statement = self.conn.prepare( + "SELECT profile_id, resource_id, declaration, scope, profile_revision, approved_at + FROM shared_resource_consents WHERE profile_id = ?1 ORDER BY resource_id", + )?; + let rows = statement.query_map([profile_id], |row| { + Ok(SharedResourceConsentRow { + profile_id: row.get(0)?, + resource_id: row.get(1)?, + declaration: row.get(2)?, + scope: row.get(3)?, + profile_revision: row.get::<_, i64>(4)? as u64, + approved_at: row.get(5)?, + }) + })?; + rows.collect::, _>>().map_err(Into::into) + } + + /// Forgets the decision, so the next use asks the user again. + pub fn revoke_shared_resource_consent( + &mut self, + profile_id: &str, + resource_id: &str, + ) -> Result { + Ok(self.conn.execute( + "DELETE FROM shared_resource_consents WHERE profile_id = ?1 AND resource_id = ?2", + params![profile_id, resource_id], + )? > 0) + } +} + +/// The charged bytes of the live entries, optionally leaving out one key. +fn usage_of(conn: &Connection, now: i64, except: Option<&str>) -> Result { + let total: i64 = conn.query_row( + "SELECT COALESCE(SUM(length(CAST(key AS BLOB)) + length(value) + ?1), 0) + FROM entries + WHERE archived = 0 + AND (expires_at IS NULL OR expires_at > ?2) AND (?3 IS NULL OR key != ?3)", + params![ENTRY_OVERHEAD_BYTES as i64, now, except], + |row| row.get(0), + )?; + Ok(total as u64) +} + +#[cfg(test)] +mod tests; + +pub const MAX_PLUGIN_LIBRARIES: usize = 128; +pub const MAX_PLUGIN_LIBRARY_ROOTS: usize = 128; + +/// Host-owned logical library data. Kept outside the plugin's private key/value API. +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub struct PluginLibraryRow { + pub id: String, + pub name: String, + pub description: String, + pub revision: u64, + pub removed: bool, + pub roots: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub struct PluginLibraryRoot { + pub id: String, + pub name: String, + pub path: String, + pub volume: u64, + pub node: u64, + pub volume_token: String, + pub declared: bool, + pub watching: bool, +} + +impl DurableStore { + pub fn plugin_libraries(&self) -> Result, PluginStorageError> { + let mut statement = self + .conn + .prepare("SELECT payload FROM plugin_libraries ORDER BY id")?; + let rows = statement.query_map([], |row| row.get::<_, String>(0))?; + rows.map(|row| { + let text = row?; + serde_json::from_str(&text).map_err(|error| { + PluginStorageError::Database(rusqlite::Error::FromSqlConversionFailure( + 0, + rusqlite::types::Type::Text, + Box::new(error), + )) + }) + }) + .collect() + } + + pub fn put_plugin_library(&mut self, row: &PluginLibraryRow) -> Result<(), PluginStorageError> { + let payload = serde_json::to_string(row).expect("library records serialize"); + let tx = self.conn.transaction()?; + tx.execute("INSERT INTO plugin_libraries(id,payload) VALUES (?1,?2) ON CONFLICT(id) DO UPDATE SET payload=excluded.payload", params![row.id,payload])?; + tx.execute( + "UPDATE meta SET revision=MAX(revision,?1) WHERE id=1", + [row.revision as i64], + )?; + tx.commit()?; + Ok(()) + } +} + +impl PluginLibraryRoot { + /// Session handles bind to the approved folder revision, not just the logical root id. + pub fn handle_id(&self) -> String { + use sha2::{Digest, Sha256}; + let mut hash = Sha256::new(); + for part in [ + &self.path, + &self.volume_token, + &self.volume.to_string(), + &self.node.to_string(), + ] { + hash.update((part.len() as u64).to_be_bytes()); + hash.update(part.as_bytes()); + } + format!("{}:{:x}", self.id, hash.finalize()) + } +} + +// Backup archives are host-owned game data, separate from plugin key/value quotas and cleanup. +impl DurableStore { + pub fn backup_sources(&self, profile: &str) -> Result, PluginStorageError> { + self.conn + .prepare( + "SELECT destination FROM backup_sources WHERE profile_id=?1 ORDER BY destination", + )? + .query_map([profile], |r| r.get(0))? + .collect::, _>>() + .map_err(Into::into) + } + pub fn remember_backup_source( + &self, + profile: &str, + destination: &str, + ) -> Result<(), PluginStorageError> { + self.conn.execute( + "INSERT OR IGNORE INTO backup_sources(profile_id,destination) VALUES (?1,?2)", + params![profile, destination], + )?; + Ok(()) + } +} diff --git a/crates/platform/src/plugin_storage/tests.rs b/crates/platform/src/plugin_storage/tests.rs new file mode 100644 index 000000000..3e6cdd432 --- /dev/null +++ b/crates/platform/src/plugin_storage/tests.rs @@ -0,0 +1,1589 @@ +use super::*; + +fn store(dir: &Path) -> DurableStore { + DurableStore::open(dir).unwrap() +} + +#[test] +fn a_namespace_that_never_stored_anything_has_no_file() { + let temp = tempfile::tempdir().unwrap(); + let dir = namespace_dir(temp.path(), "pub", "org.example", "profile"); + assert!(DurableStore::open_existing(&dir).unwrap().is_none()); + assert!(!dir.exists(), "reading must not create the namespace"); + store(&dir); + assert!(DurableStore::open_existing(&dir).unwrap().is_some()); +} + +#[test] +fn values_round_trip_and_survive_reopening() { + let temp = tempfile::tempdir().unwrap(); + let dir = namespace_dir(temp.path(), "pub", "org.example", "profile"); + let mut first = store(&dir); + assert_eq!( + first.put("k", b"value", 3, None, 100, QUOTA_BYTES).unwrap(), + PutResult::Stored { + usage: charge("k", 5) + } + ); + drop(first); + let second = store(&dir); + let stored = second.get("k", 100).unwrap().unwrap(); + assert_eq!(stored.value, b"value"); + assert_eq!(stored.revision, 3); + assert_eq!(second.high_water().unwrap(), 3); +} + +#[test] +fn replacing_a_value_charges_only_the_difference() { + let temp = tempfile::tempdir().unwrap(); + let mut store = store(temp.path()); + store.put("k", &[0; 1000], 1, None, 0, 5000).unwrap(); + // Replacing in place fits although old + new would not. + assert_eq!( + store.put("k", &[0; 3000], 2, None, 0, 5000).unwrap(), + PutResult::Stored { + usage: charge("k", 3000) + } + ); + assert_eq!(store.get("k", 0).unwrap().unwrap().revision, 2); +} + +#[test] +fn a_write_over_the_quota_changes_nothing() { + let temp = tempfile::tempdir().unwrap(); + let mut store = store(temp.path()); + let quota = charge("a", 100) + charge("b", 100); + store.put("a", &[1; 100], 1, None, 0, quota).unwrap(); + store.put("b", &[2; 100], 2, None, 0, quota).unwrap(); + let before = store.usage(0).unwrap(); + + // A new key and a larger replacement both fail whole. + assert_eq!( + store.put("c", &[3; 1], 3, None, 0, quota).unwrap(), + PutResult::OverQuota { usage: before } + ); + assert_eq!( + store.put("a", &[9; 200], 4, None, 0, quota).unwrap(), + PutResult::OverQuota { usage: before } + ); + assert!(store.get("c", 0).unwrap().is_none()); + let a = store.get("a", 0).unwrap().unwrap(); + assert_eq!((a.value, a.revision), (vec![1; 100], 1)); + assert_eq!(store.usage(0).unwrap(), before); + // The refused writes did not burn revisions. + assert_eq!(store.high_water().unwrap(), 2); +} + +#[test] +fn tiny_entries_are_charged_an_overhead() { + assert_eq!(charge("k", 0), 1 + ENTRY_OVERHEAD_BYTES); + let temp = tempfile::tempdir().unwrap(); + let mut store = store(temp.path()); + let quota = 3 * charge("k0", 0); + for index in 0..3 { + let key = format!("k{index}"); + assert!(matches!( + store.put(&key, b"", index + 1, None, 0, quota).unwrap(), + PutResult::Stored { .. } + )); + } + assert!(matches!( + store.put("k3", b"", 4, None, 0, quota).unwrap(), + PutResult::OverQuota { .. } + )); +} + +#[test] +fn expired_entries_are_gone_and_free_their_space() { + let temp = tempfile::tempdir().unwrap(); + let mut store = store(temp.path()); + store.put("k", b"v", 1, Some(100), 0, QUOTA_BYTES).unwrap(); + assert!(store.get("k", 99).unwrap().is_some()); + assert!(store.get("k", 100).unwrap().is_none()); + assert_eq!(store.usage(100).unwrap(), 0); + // The next write sweeps the expired row away. + store.put("other", b"v", 2, None, 100, QUOTA_BYTES).unwrap(); + assert_eq!(store.usage(0).unwrap(), charge("other", 1)); +} + +#[test] +fn persistence_entries_are_logical_ordered_and_track_last_use() { + let temp = tempfile::tempdir().unwrap(); + let mut store = store(temp.path()); + store + .put("beta", b"two", 1, None, 100, QUOTA_BYTES) + .unwrap(); + store + .put("alpha", b"one", 2, Some(200), 150, QUOTA_BYTES) + .unwrap(); + store + .put("expired", b"gone", 3, Some(50), 50, QUOTA_BYTES) + .unwrap(); + assert!(store.get("beta", 160).unwrap().is_some()); + + let entries = store.persistence_entries(180).unwrap(); + assert_eq!( + entries, + [ + PersistenceEntry { + key: "alpha".into(), + size_bytes: 3, + last_used_at: 150, + user_protected: false, + }, + PersistenceEntry { + key: "beta".into(), + size_bytes: 3, + last_used_at: 160, + user_protected: false, + }, + ] + ); + let remaining = store.persistence_entries(200).unwrap(); + assert_eq!(remaining.len(), 1); + assert_eq!(remaining[0].key, "beta"); + assert!(store.physical_bytes().unwrap() > 0); +} + +#[test] +fn retention_policy_prunes_by_age_and_size_without_touching_the_newest_entry() { + let temp = tempfile::tempdir().unwrap(); + let mut store = store(temp.path()); + for (index, key) in ["old", "middle", "new"].iter().enumerate() { + let at = 100 + index as i64 * 100; + store + .put(key, b"value", index as u64 + 1, None, at, QUOTA_BYTES) + .unwrap(); + } + let policy = RetentionPolicy { + max_age_seconds: 150, + max_bytes: 0, + }; + assert_eq!( + store + .set_retention_policy("private", policy, 300, 4) + .unwrap(), + charge("old", 5) + ); + assert_eq!( + store + .persistence_entries(300) + .unwrap() + .into_iter() + .map(|entry| entry.key) + .collect::>(), + ["middle", "new"] + ); + assert_eq!(store.retention_policy("private").unwrap(), Some(policy)); + + // A smaller byte bound removes the oldest remaining entry first. + let policy = RetentionPolicy { + max_age_seconds: 0, + max_bytes: charge("new", 5), + }; + store + .set_retention_policy("private", policy, 300, 5) + .unwrap(); + assert!(store.get("middle", 300).unwrap().is_none()); + assert!(store.get("new", 300).unwrap().is_some()); + // A write does not prune itself; it remains bounded by the next policy or quota check. + assert_eq!( + store + .put("newest", b"value", 6, None, 300, QUOTA_BYTES) + .unwrap(), + PutResult::Stored { + usage: charge("new", 5) + charge("newest", 5) + } + ); + assert!(store.get("newest", 300).unwrap().is_some()); +} + +#[test] +fn usage_reports_category_records_and_a_namespace_wide_page_estimate() { + let temp = tempfile::tempdir().unwrap(); + let mut store = store(temp.path()); + store + .put("alpha", b"one", 1, None, 100, QUOTA_BYTES) + .unwrap(); + store + .put("beta", b"two", 2, None, 100, QUOTA_BYTES) + .unwrap(); + store + .put("expired", b"gone", 3, Some(150), 100, QUOTA_BYTES) + .unwrap(); + assert!(store.set_user_protected("beta", true).unwrap()); + + let usage = store.store_usage(200).unwrap(); + let expected = charge("alpha", 3) + charge("beta", 3); + assert_eq!(usage.logical_bytes, expected); + assert_eq!(usage.categories.len(), 1); + assert_eq!( + usage.categories[0], + CategoryUsage { + category: "private".into(), + records: 2, + logical_bytes: expected, + protected_records: 1, + } + ); + // The physical estimate covers the whole namespace file, not one category. + assert_eq!( + usage.physical_bytes_estimate, + store.physical_bytes().unwrap() + ); + assert!(usage.physical_bytes_estimate > 0); +} + +#[test] +fn protected_records_survive_plugin_deletion_retention_and_cleanup() { + let temp = tempfile::tempdir().unwrap(); + let mut store = store(temp.path()); + store + .put("protected", b"keep", 1, None, 100, QUOTA_BYTES) + .unwrap(); + store + .put("unprotected", b"old", 2, None, 100, QUOTA_BYTES) + .unwrap(); + assert!(store.set_user_protected("protected", true).unwrap()); + + // A plugin cannot overwrite, remove, or bulk-delete a protected record. + assert!(matches!( + store.put("protected", b"new", 3, None, 100, QUOTA_BYTES), + Err(PluginStorageError::Protected) + )); + assert!(matches!( + store.remove("protected"), + Err(PluginStorageError::Protected) + )); + assert!(matches!( + store.delete_persistence_entries(&["protected".to_owned()], 100, 3), + Err(PluginStorageError::Protected) + )); + assert_eq!(store.get("protected", 100).unwrap().unwrap().value, b"keep"); + + // Age retention removes the old unprotected record and leaves the protected one. + store + .set_retention_policy( + "private", + RetentionPolicy { + max_age_seconds: 50, + max_bytes: 0, + }, + 200, + 4, + ) + .unwrap(); + assert!(store.get("unprotected", 200).unwrap().is_none()); + assert!(store.get("protected", 200).unwrap().is_some()); + + // Cleanup reclaims the unprotected, expired record only. + store + .put("expiring", b"x", 5, Some(210), 200, QUOTA_BYTES) + .unwrap(); + let cleanup = store.cleanup(220).unwrap(); + assert_eq!(cleanup.removed_records, 1); + assert_eq!(cleanup.reclaimed_bytes, charge("expiring", 1)); + assert!(store.get("expiring", 220).unwrap().is_none()); + assert!(store.get("protected", 220).unwrap().is_some()); + + // Only the host can lift protection; then the normal delete path works again. + assert!(store.set_user_protected("protected", false).unwrap()); + assert_eq!(store.remove("protected").unwrap(), Some(1)); +} + +#[test] +fn a_version_twelve_store_gains_host_only_user_protection() { + let temp = tempfile::tempdir().unwrap(); + let dir = temp.path().join("ns"); + fs::create_dir_all(&dir).unwrap(); + let conn = Connection::open(dir.join(STORE_FILE)).unwrap(); + conn.execute_batch( + "CREATE TABLE meta (id INTEGER PRIMARY KEY CHECK (id = 1), revision INTEGER NOT NULL) STRICT; + INSERT INTO meta (id, revision) VALUES (1, 7); + CREATE TABLE entries ( + key TEXT PRIMARY KEY, + value BLOB NOT NULL, + revision INTEGER NOT NULL CHECK (revision >= 1), + expires_at INTEGER, + last_used_at INTEGER NOT NULL DEFAULT 0 + ) STRICT; + INSERT INTO entries (key, value, revision, expires_at, last_used_at) + VALUES ('legacy', X'00', 7, NULL, 50); + PRAGMA user_version = 12;", + ) + .unwrap(); + drop(conn); + + let mut upgraded = store(&dir); + let entry = &upgraded.persistence_entries(100).unwrap()[0]; + assert_eq!(entry.key, "legacy"); + assert!(!entry.user_protected); + assert!(upgraded.set_user_protected("legacy", true).unwrap()); + drop(upgraded); + + let reopened = store(&dir); + assert!(reopened.persistence_entries(100).unwrap()[0].user_protected); +} + +#[test] +fn a_version_eleven_store_gains_shared_resources_and_consent() { + let temp = tempfile::tempdir().unwrap(); + let dir = temp.path().join("ns"); + let mut current = store(&dir); + current + .save_profile(&profile("a", "inst", "Card", 1)) + .unwrap(); + drop(current); + + let conn = Connection::open(dir.join(STORE_FILE)).unwrap(); + conn.execute_batch( + "DROP TABLE shared_resource_consents; + ALTER TABLE save_profiles DROP COLUMN shared_resources; + PRAGMA user_version = 11;", + ) + .unwrap(); + drop(conn); + + let mut upgraded = store(&dir); + assert_eq!( + upgraded + .save_profile_row("a") + .unwrap() + .unwrap() + .shared_resources, + "[]" + ); + let consent = SharedResourceConsentRow { + profile_id: "a".into(), + resource_id: "memory-card".into(), + declaration: "declaration".into(), + scope: "scope".into(), + profile_revision: 1, + approved_at: 100, + }; + upgraded.save_shared_resource_consent(&consent).unwrap(); + assert_eq!( + upgraded + .shared_resource_consent("a", "memory-card") + .unwrap(), + Some(consent.clone()) + ); + assert!( + upgraded + .revoke_shared_resource_consent("a", "memory-card") + .unwrap() + ); + assert_eq!( + upgraded + .shared_resource_consent("a", "memory-card") + .unwrap(), + None + ); + // Removing the profile also removes its remaining decisions. + upgraded.save_shared_resource_consent(&consent).unwrap(); + upgraded.delete_save_profile("a", 2).unwrap(); + assert!(upgraded.shared_resource_consents("a").unwrap().is_empty()); +} + +#[test] +fn deleting_persistence_entries_is_selected_and_advances_the_revision() { + let temp = tempfile::tempdir().unwrap(); + let mut store = store(temp.path()); + store.put("keep", b"k", 1, None, 0, QUOTA_BYTES).unwrap(); + store + .put("drop", b"value", 2, None, 0, QUOTA_BYTES) + .unwrap(); + assert_eq!( + store + .delete_persistence_entries(&["drop".into()], 0, 3) + .unwrap(), + charge("drop", 5) + ); + assert_eq!(store.high_water().unwrap(), 3); + assert!(store.get("keep", 0).unwrap().is_some()); + assert!(store.get("drop", 0).unwrap().is_none()); + // A missing key is not an error when the caller already validated the set. + assert_eq!( + store + .delete_persistence_entries(&["missing".into()], 0, 4) + .unwrap(), + 0 + ); +} + +#[test] +fn a_version_ten_store_gains_last_use_and_retention_tables() { + let temp = tempfile::tempdir().unwrap(); + let dir = temp.path().join("ns"); + let mut current = store(&dir); + current.put("old", b"v", 1, None, 100, QUOTA_BYTES).unwrap(); + drop(current); + + let conn = Connection::open(dir.join(STORE_FILE)).unwrap(); + conn.execute_batch( + "DROP TABLE retention_policies; + ALTER TABLE entries DROP COLUMN last_used_at; + PRAGMA user_version = 10;", + ) + .unwrap(); + drop(conn); + + let mut upgraded = store(&dir); + assert_eq!( + upgraded + .persistence_entries(100) + .unwrap() + .into_iter() + .map(|entry| entry.key) + .collect::>(), + ["old"] + ); + assert_eq!(upgraded.retention_policy("private").unwrap(), None); + upgraded + .set_retention_policy("private", RetentionPolicy::default(), 100, 2) + .unwrap(); + assert_eq!( + upgraded.retention_policy("private").unwrap(), + Some(RetentionPolicy::default()) + ); +} + +#[test] +fn remove_reports_the_revision_it_deleted_and_keeps_the_high_water() { + let temp = tempfile::tempdir().unwrap(); + let mut store = store(temp.path()); + store.put("k", b"v", 7, None, 0, QUOTA_BYTES).unwrap(); + assert_eq!(store.remove("k").unwrap(), Some(7)); + assert_eq!(store.remove("k").unwrap(), None); + assert!(store.get("k", 0).unwrap().is_none()); + assert_eq!(store.high_water().unwrap(), 7); +} + +#[test] +fn keys_are_measured_in_bytes_not_characters() { + let temp = tempfile::tempdir().unwrap(); + let mut store = store(temp.path()); + let key = "ação"; + assert_eq!(key.len(), 6); + assert_eq!( + store.put(key, b"v", 1, None, 0, QUOTA_BYTES).unwrap(), + PutResult::Stored { + usage: charge(key, 1) + } + ); + assert_eq!(store.usage(0).unwrap(), charge(key, 1)); +} + +#[test] +fn a_store_from_a_newer_version_is_refused_untouched() { + let temp = tempfile::tempdir().unwrap(); + let dir = temp.path().join("ns"); + store(&dir); + Connection::open(dir.join(STORE_FILE)) + .unwrap() + .execute_batch("PRAGMA user_version = 99;") + .unwrap(); + assert!(matches!( + DurableStore::open(&dir), + Err(PluginStorageError::NewerVersion) + )); +} + +#[test] +fn a_damaged_file_is_an_error_and_is_not_replaced() { + let temp = tempfile::tempdir().unwrap(); + let dir = temp.path().join("ns"); + fs::create_dir_all(&dir).unwrap(); + fs::write( + dir.join(STORE_FILE), + b"this is not a database at all, really", + ) + .unwrap(); + assert!(DurableStore::open(&dir).is_err()); + assert_eq!( + fs::read(dir.join(STORE_FILE)).unwrap(), + b"this is not a database at all, really" + ); +} + +#[test] +fn directories_never_escape_the_root_and_depend_on_the_identity() { + let root = Path::new("/data/plugin-data"); + for hostile in ["..", ".", "../..", "a/b", "a\\b", "", "C:\\x", "x\0y", "."] { + let dir = namespace_dir(root, hostile, hostile, hostile); + assert!(dir.starts_with(root), "{hostile:?} -> {dir:?}"); + for part in dir.strip_prefix(root).unwrap().components() { + assert!( + matches!(part, std::path::Component::Normal(_)), + "{hostile:?} -> {dir:?}" + ); + } + } + let base = namespace_dir(root, "pub-a", "org.example", "p1"); + assert_eq!(base, root.join("pub-a").join("org.example").join("p1")); + assert_ne!(base, namespace_dir(root, "pub-b", "org.example", "p1")); + assert_ne!(base, namespace_dir(root, "pub-a", "org.other", "p1")); + assert_ne!(base, namespace_dir(root, "pub-a", "org.example", "p2")); + // Different identities that would collapse after cleaning stay different. + assert_ne!( + namespace_dir(root, "a/b", "x", "p"), + namespace_dir(root, "a%2Fb", "x", "p") + ); + let long = "x".repeat(300); + let dir = namespace_dir(root, &long, &long, "p"); + assert!(dir.file_name().is_some()); + for part in dir.strip_prefix(root).unwrap().components() { + assert!(part.as_os_str().len() <= 255); + } +} + +fn approval(id: &str, installation: &str, kind: &str) -> FileApproval { + FileApproval { + id: id.into(), + installation_id: installation.into(), + game_id: "40".into(), + kind: kind.into(), + root: "/games/portal".into(), + volume_token: "opaque-volume-token".into(), + root_volume: u64::MAX, + root_node: 12345, + operations: operation::READ | operation::WRITE, + affected: vec!["steam:620".into(), "steam:621".into()], + approved_at: 100, + revoked_at: None, + origin: ORIGIN_USER.into(), + } +} + +#[test] +fn approvals_round_trip_survive_reopening_and_are_not_charged_to_the_quota() { + let temp = tempfile::tempdir().unwrap(); + let dir = namespace_dir(temp.path(), "pub", "org.example", "profile"); + let mut first = store(&dir); + let saved = approval("a1", "inst-1", "installation"); + first.save_approval(&saved).unwrap(); + first.put("k", b"v", 1, None, 0, QUOTA_BYTES).unwrap(); + drop(first); + + let second = store(&dir); + assert_eq!(second.approval("a1").unwrap(), Some(saved.clone())); + assert_eq!( + second.approval_for("inst-1", "installation").unwrap(), + Some(saved.clone()) + ); + assert_eq!(second.approval_for("inst-1", "save").unwrap(), None); + assert_eq!(second.approval("nope").unwrap(), None); + assert_eq!(second.approvals().unwrap(), vec![saved]); + assert_eq!( + second.usage(0).unwrap(), + charge("k", 1), + "only entries are charged" + ); +} + +#[test] +fn a_new_approval_replaces_the_old_one_for_the_same_installation_and_kind() { + let temp = tempfile::tempdir().unwrap(); + let mut store = store(temp.path()); + store + .save_approval(&approval("old", "inst-1", "save")) + .unwrap(); + store + .save_approval(&approval("other", "inst-2", "save")) + .unwrap(); + let mut wider = approval("new", "inst-1", "save"); + wider.operations = operation::READ | operation::WRITE | operation::DELETE; + store.save_approval(&wider).unwrap(); + + assert_eq!( + store.approval("old").unwrap(), + None, + "the replaced id opens nothing" + ); + assert_eq!(store.approval("new").unwrap(), Some(wider)); + assert_eq!(store.approvals().unwrap().len(), 2); +} + +#[test] +fn a_revoked_approval_stays_visible_as_revoked_and_revokes_once() { + let temp = tempfile::tempdir().unwrap(); + let mut store = store(temp.path()); + store + .save_approval(&approval("a1", "inst-1", "installation")) + .unwrap(); + assert!(store.revoke_approval("a1", 500).unwrap()); + assert!(!store.revoke_approval("a1", 600).unwrap()); + assert!(!store.revoke_approval("missing", 600).unwrap()); + assert_eq!(store.approval("a1").unwrap().unwrap().revoked_at, Some(500)); + // Approving again makes a fresh, active record. + store + .save_approval(&approval("a2", "inst-1", "installation")) + .unwrap(); + assert_eq!( + store + .approval_for("inst-1", "installation") + .unwrap() + .unwrap() + .revoked_at, + None + ); +} + +#[test] +fn runtime_approvals_round_trip_survive_reopening_and_revoke_once() { + let temp = tempfile::tempdir().unwrap(); + let dir = namespace_dir(temp.path(), "pub", "org.example", "profile"); + let approval = RuntimeApproval { + id: "runtime-approval".into(), + runtime_id: "runtime-1".into(), + path: "/usr/bin/dolphin-emu".into(), + volume: 7, + node: 9, + size: 21_731_776, + digest: "ab".repeat(32), + approved_at: 100, + revoked_at: None, + }; + { + let mut first = store(&dir); + first.save_runtime_approval(&approval).unwrap(); + } + let mut reopened = store(&dir); + assert_eq!( + reopened.runtime_approval_for("runtime-1").unwrap(), + Some(approval.clone()) + ); + assert_eq!( + reopened.runtime_approval_by_id("runtime-approval").unwrap(), + Some(approval.clone()) + ); + assert_eq!( + reopened.runtime_approvals().unwrap(), + vec![approval.clone()] + ); + assert!(reopened.revoke_runtime_approval("runtime-1", 500).unwrap()); + assert!(!reopened.revoke_runtime_approval("runtime-1", 600).unwrap()); + assert_eq!( + reopened + .runtime_approval_for("runtime-1") + .unwrap() + .unwrap() + .revoked_at, + Some(500) + ); + + // A reapproval replaces the row for the same runtime and keeps one id. + let mut replacement = approval; + replacement.id = "runtime-approval-2".into(); + replacement.digest = "cd".repeat(32); + replacement.revoked_at = None; + reopened.save_runtime_approval(&replacement).unwrap(); + assert_eq!( + reopened.runtime_approval_by_id("runtime-approval").unwrap(), + None + ); + assert_eq!( + reopened.runtime_approval_for("runtime-1").unwrap(), + Some(replacement) + ); + assert_eq!(reopened.runtime_approvals().unwrap().len(), 1); +} + +#[test] +fn a_version_1_store_gains_the_approvals_table_and_keeps_its_values() { + let temp = tempfile::tempdir().unwrap(); + let dir = temp.path().join("ns"); + fs::create_dir_all(&dir).unwrap(); + { + let conn = Connection::open(dir.join(STORE_FILE)).unwrap(); + conn.execute_batch( + "CREATE TABLE meta (id INTEGER PRIMARY KEY CHECK (id = 1), revision INTEGER NOT NULL) STRICT; + INSERT INTO meta (id, revision) VALUES (1, 4); + CREATE TABLE entries (key TEXT PRIMARY KEY, value BLOB NOT NULL, + revision INTEGER NOT NULL, expires_at INTEGER) STRICT; + INSERT INTO entries VALUES ('old', x'01', 4, NULL); + PRAGMA user_version = 1;", + ) + .unwrap(); + } + let mut upgraded = store(&dir); + assert_eq!(upgraded.get("old", 0).unwrap().unwrap().revision, 4); + assert_eq!(upgraded.high_water().unwrap(), 4); + upgraded + .save_approval(&approval("a1", "inst-1", "installation")) + .unwrap(); + assert!(upgraded.approval("a1").unwrap().is_some()); +} + +#[test] +fn a_version_2_store_gains_the_origin_column_and_old_approvals_count_as_the_users() { + let temp = tempfile::tempdir().unwrap(); + let dir = temp.path().join("ns"); + fs::create_dir_all(&dir).unwrap(); + { + let conn = Connection::open(dir.join(STORE_FILE)).unwrap(); + conn.execute_batch( + "CREATE TABLE meta (id INTEGER PRIMARY KEY CHECK (id = 1), revision INTEGER NOT NULL) STRICT; + INSERT INTO meta (id, revision) VALUES (1, 0); + CREATE TABLE entries (key TEXT PRIMARY KEY, value BLOB NOT NULL, + revision INTEGER NOT NULL, expires_at INTEGER) STRICT; + CREATE TABLE file_roots ( + id TEXT NOT NULL UNIQUE, installation_id TEXT NOT NULL, game_id TEXT NOT NULL, + kind TEXT NOT NULL, root TEXT NOT NULL, root_volume INTEGER NOT NULL, + root_node INTEGER NOT NULL, operations INTEGER NOT NULL, affected TEXT NOT NULL, + approved_at INTEGER NOT NULL, revoked_at INTEGER, + PRIMARY KEY (installation_id, kind)) STRICT; + INSERT INTO file_roots VALUES ('old', 'inst', '', 'save', '/g', 1, 2, 1, '[]', 5, NULL); + PRAGMA user_version = 2;", + ) + .unwrap(); + } + let mut upgraded = store(&dir); + let old = upgraded.approval("old").unwrap().unwrap(); + assert_eq!(old.origin, ORIGIN_USER); + assert!( + old.volume_token.is_empty(), + "migration must never invent identity approval" + ); + let mut declared = approval("new", "inst-2", "save"); + declared.origin = ORIGIN_DECLARED.into(); + upgraded.save_approval(&declared).unwrap(); + assert_eq!( + upgraded.approval("new").unwrap().unwrap().origin, + ORIGIN_DECLARED + ); +} + +fn remembered(id: &str, installation: &str, operation: &str) -> IntentApproval { + IntentApproval { + id: id.into(), + game_id: "42".into(), + installation_id: installation.into(), + operation: operation.into(), + target_revision: 7, + recipe_id: String::new(), + recipe_revision: 0, + plan_fingerprint: "v1:approval-plan".into(), + game_name: "Game".into(), + approved_at: 100, + } +} + +#[test] +fn remembered_confirmations_are_kept_per_installation_and_operation_and_can_be_revoked() { + let temp = tempfile::tempdir().unwrap(); + let dir = temp.path().join("ns"); + let mut first = store(&dir); + first + .save_intent_approval(&remembered("a", "inst-1", "launch")) + .unwrap(); + first + .save_intent_approval(&remembered("b", "inst-1", "install")) + .unwrap(); + // The same installation and operation again replaces the earlier approval. + let mut newer = remembered("c", "inst-1", "launch"); + newer.target_revision = 9; + first.save_intent_approval(&newer).unwrap(); + drop(first); + + let mut second = store(&dir); + assert_eq!( + second + .intent_approval("inst-1", "launch") + .unwrap() + .map(|a| (a.id, a.target_revision)), + Some(("c".into(), 9)) + ); + assert!( + second + .intent_approval("inst-2", "launch") + .unwrap() + .is_none() + ); + assert_eq!(second.intent_approvals().unwrap().len(), 2); + assert!(!second.revoke_intent_approval("nothing").unwrap()); + assert!(second.revoke_intent_approval("c").unwrap()); + assert!( + second + .intent_approval("inst-1", "launch") + .unwrap() + .is_none() + ); + assert!( + second + .intent_approval("inst-1", "install") + .unwrap() + .is_some() + ); +} + +#[test] +fn custom_launch_approval_persists_recipe_identity_and_revision() { + let temp = tempfile::tempdir().unwrap(); + let mut store = store(&temp.path().join("ns")); + let mut approval = remembered("custom", "inst", "custom_launch"); + approval.recipe_id = "recipe-one".into(); + approval.recipe_revision = 4; + store.save_intent_approval(&approval).unwrap(); + assert_eq!( + store.intent_approval("inst", "custom_launch").unwrap(), + Some(approval) + ); +} + +#[test] +fn schema_eight_approvals_upgrade_without_losing_their_target_revision() { + let temp = tempfile::tempdir().unwrap(); + let dir = temp.path().join("ns"); + let mut current = store(&dir); + current + .save_intent_approval(&remembered("old", "inst", "launch")) + .unwrap(); + drop(current); + + let conn = Connection::open(dir.join(STORE_FILE)).unwrap(); + conn.execute_batch( + "ALTER TABLE intent_approvals RENAME TO intent_approvals_v9; + CREATE TABLE intent_approvals ( + id TEXT NOT NULL UNIQUE, + game_id TEXT NOT NULL, + installation_id TEXT NOT NULL, + operation TEXT NOT NULL CHECK (operation IN ('launch', 'install')), + target_revision INTEGER NOT NULL CHECK (target_revision >= 0), + game_name TEXT NOT NULL, + approved_at INTEGER NOT NULL, + PRIMARY KEY (installation_id, operation) + ) STRICT; + INSERT INTO intent_approvals + (id, game_id, installation_id, operation, target_revision, game_name, approved_at) + SELECT id, game_id, installation_id, operation, target_revision, game_name, approved_at + FROM intent_approvals_v9; + DROP TABLE intent_approvals_v9; + PRAGMA user_version = 8;", + ) + .unwrap(); + drop(conn); + + let mut upgraded = store(&dir); + let old = upgraded.intent_approval("inst", "launch").unwrap().unwrap(); + assert_eq!(old.target_revision, 7); + assert_eq!(old.recipe_id, ""); + assert_eq!(old.recipe_revision, 0); + assert!( + old.plan_fingerprint.is_empty(), + "legacy approvals must reconfirm" + ); + let mut custom = remembered("new", "inst", "custom_launch"); + custom.recipe_id = "custom-recipe".into(); + custom.recipe_revision = 3; + upgraded.save_intent_approval(&custom).unwrap(); + assert_eq!( + upgraded + .intent_approval("inst", "custom_launch") + .unwrap() + .unwrap(), + custom + ); +} + +#[test] +fn only_launch_custom_launch_and_install_can_be_remembered() { + let temp = tempfile::tempdir().unwrap(); + let mut store = store(&temp.path().join("ns")); + assert!( + store + .save_intent_approval(&remembered("a", "inst", "restore")) + .is_err() + ); +} + +#[test] +fn a_version_3_store_gains_the_remembered_confirmations_table() { + let temp = tempfile::tempdir().unwrap(); + let dir = temp.path().join("ns"); + { + let first = store(&dir); + drop(first); + let conn = Connection::open(dir.join(STORE_FILE)).unwrap(); + conn.execute_batch("DROP TABLE intent_approvals; ALTER TABLE file_roots DROP COLUMN volume_token; PRAGMA user_version = 3;") + .unwrap(); + } + let mut upgraded = store(&dir); + upgraded + .save_intent_approval(&remembered("a", "inst", "launch")) + .unwrap(); + assert_eq!(upgraded.intent_approvals().unwrap().len(), 1); +} + +fn profile(id: &str, installation: &str, name: &str, revision: u64) -> SaveProfileRow { + SaveProfileRow { + id: id.into(), + installation_id: installation.into(), + game_id: "42".into(), + name: name.into(), + runtime_id: "dolphin".into(), + format_id: String::new(), + format_version: 0, + metadata: "{}".into(), + directories: "[]".into(), + shared_resources: "[]".into(), + revision, + created_at: 100, + } +} + +#[test] +fn save_profiles_round_trip_replace_and_keep_the_revision_high_water() { + let temp = tempfile::tempdir().unwrap(); + let dir = temp.path().join("ns"); + let mut first = store(&dir); + assert_eq!( + first + .save_profile(&profile("a", "inst", "Card A", 3)) + .unwrap(), + ProfileSaved::Saved + ); + let mut renamed = profile("a", "inst", "Card A2", 9); + renamed.created_at = 999; // the creation time is never rewritten + first.save_profile(&renamed).unwrap(); + assert_eq!(first.high_water().unwrap(), 9); + drop(first); + + let mut second = store(&dir); + let kept = second.save_profile_row("a").unwrap().unwrap(); + assert_eq!( + (kept.name.as_str(), kept.revision, kept.created_at), + ("Card A2", 9, 100) + ); + // Removing keeps the high-water mark, so a recreated profile never repeats a revision. + assert!(second.delete_save_profile("a", 12).unwrap()); + assert!(!second.delete_save_profile("a", 13).unwrap()); + assert_eq!(second.high_water().unwrap(), 13); + assert!(second.save_profile_row("a").unwrap().is_none()); +} + +#[test] +fn a_profile_name_is_unique_per_installation_without_regard_to_case() { + let temp = tempfile::tempdir().unwrap(); + let mut store = store(&temp.path().join("ns")); + store + .save_profile(&profile("a", "inst", "Card A", 1)) + .unwrap(); + assert_eq!( + store + .save_profile(&profile("b", "inst", "card a", 2)) + .unwrap(), + ProfileSaved::NameTaken + ); + // Nothing of the refused write was kept, high-water mark included. + assert!(store.save_profile_row("b").unwrap().is_none()); + assert_eq!(store.high_water().unwrap(), 1); + // Another installation may use the name; a profile may keep its own name. + assert_eq!( + store + .save_profile(&profile("c", "other", "Card A", 3)) + .unwrap(), + ProfileSaved::Saved + ); + assert_eq!( + store + .save_profile(&profile("a", "inst", "Card A", 4)) + .unwrap(), + ProfileSaved::Saved + ); + let ids: Vec<_> = store + .save_profile_rows() + .unwrap() + .into_iter() + .map(|row| row.id) + .collect(); + assert_eq!(ids, ["a", "c"]); +} + +#[test] +fn a_version_4_store_gains_the_save_profiles_table() { + let temp = tempfile::tempdir().unwrap(); + let dir = temp.path().join("ns"); + { + let first = store(&dir); + drop(first); + let conn = Connection::open(dir.join(STORE_FILE)).unwrap(); + conn.execute_batch("DROP TABLE save_profiles; ALTER TABLE file_roots DROP COLUMN volume_token; PRAGMA user_version = 4;") + .unwrap(); + } + let mut upgraded = store(&dir); + upgraded + .save_profile(&profile("a", "inst", "Card", 1)) + .unwrap(); + assert_eq!(upgraded.save_profile_rows().unwrap().len(), 1); +} + +#[test] +fn upgrading_schema_seven_preserves_values_and_keeps_backup_destinations_separate_from_private_quota() + { + let temp = tempfile::tempdir().unwrap(); + let dir = temp.path(); + let mut original = store(dir); + original + .put("key", b"keep", 4, None, 0, QUOTA_BYTES) + .unwrap(); + drop(original); + let conn = Connection::open(dir.join(STORE_FILE)).unwrap(); + conn.execute_batch("DROP TABLE backup_sources; PRAGMA user_version=7;") + .unwrap(); + drop(conn); + let upgraded = store(dir); + let usage = upgraded.usage(0).unwrap(); + upgraded + .remember_backup_source("profile-a", "old-destination") + .unwrap(); + upgraded + .remember_backup_source("profile-a", "new-destination") + .unwrap(); + upgraded + .remember_backup_source("profile-a", "old-destination") + .unwrap(); + assert_eq!(upgraded.get("key", 0).unwrap().unwrap().value, b"keep"); + assert_eq!(upgraded.usage(0).unwrap(), usage); + assert!(upgraded.backup_sources("profile-b").unwrap().is_empty()); + drop(upgraded); + assert_eq!( + store(dir).backup_sources("profile-a").unwrap(), + ["new-destination", "old-destination"] + ); +} + +#[test] +fn archived_entries_are_inert_and_need_a_reviewed_reuse() { + let temp = tempfile::tempdir().unwrap(); + let mut store = store(temp.path()); + store + .put("kept", b"old", 1, None, 100, QUOTA_BYTES) + .unwrap(); + store + .put("expiring", b"gone", 2, Some(180), 100, QUOTA_BYTES) + .unwrap(); + store + .put("other", b"live", 3, None, 100, QUOTA_BYTES) + .unwrap(); + assert!(store.set_user_protected("kept", true).unwrap()); + + let archived = store.archive_entries(4).unwrap(); + assert_eq!(archived.records, 3); + assert_eq!( + archived.logical_bytes, + charge("kept", 3) + charge("expiring", 4) + charge("other", 4) + ); + let usage = store.store_usage(100).unwrap(); + assert_eq!(usage.logical_bytes, 0); + assert_eq!(usage.categories[0].records, 0); + assert_eq!(usage.archived_records, 3); + assert_eq!(usage.archived_logical_bytes, archived.logical_bytes); + assert_eq!(store.archived_usage().unwrap(), archived); + + // Ordinary reads, lists, deletion and cleanup ignore archived rows. + for key in ["kept", "expiring", "other"] { + assert!(store.get(key, 100).unwrap().is_none()); + } + assert!(store.persistence_entries(100).unwrap().is_empty()); + assert_eq!(store.remove("other").unwrap(), None); + assert_eq!(store.cleanup(10_000).unwrap().removed_records, 0); + assert!(matches!( + store.put("kept", b"new", 4, None, 100, QUOTA_BYTES), + Err(PluginStorageError::Archived) + )); + + // Retention and the quota count only live rows; a new key may still be written. + assert!(matches!( + store.put("fresh", b"value", 5, None, 100, QUOTA_BYTES), + Ok(PutResult::Stored { .. }) + )); + store + .set_retention_policy( + "private", + RetentionPolicy { + max_age_seconds: 1, + max_bytes: 0, + }, + 10_000, + 6, + ) + .unwrap(); + assert_eq!(store.archived_usage().unwrap().records, 3); + + // The host reviewed reuse restores the unexpired rows only; the expired archived row is + // discarded and the protected flag survives. + let reused = store.reuse_archived_entries(10_000, 8).unwrap(); + assert_eq!(reused.records, 2); + assert_eq!(store.store_usage(10_000).unwrap().archived_records, 0); + assert!(store.get("kept", 10_000).unwrap().is_some()); + assert!(store.get("other", 10_000).unwrap().is_some()); + assert!(store.get("expiring", 10_000).unwrap().is_none()); + assert!(matches!( + store.put("kept", b"new", 7, None, 10_000, QUOTA_BYTES), + Err(PluginStorageError::Protected) + )); +} + +#[test] +fn a_version_thirteen_store_gains_host_only_archiving() { + let temp = tempfile::tempdir().unwrap(); + let dir = temp.path().join("ns"); + fs::create_dir_all(&dir).unwrap(); + let conn = Connection::open(dir.join(STORE_FILE)).unwrap(); + conn.execute_batch( + "CREATE TABLE meta (id INTEGER PRIMARY KEY CHECK (id = 1), revision INTEGER NOT NULL) STRICT; + INSERT INTO meta (id, revision) VALUES (1, 7); + CREATE TABLE entries ( + key TEXT PRIMARY KEY, + value BLOB NOT NULL, + revision INTEGER NOT NULL CHECK (revision >= 1), + expires_at INTEGER, + last_used_at INTEGER NOT NULL DEFAULT 0, + user_protected INTEGER NOT NULL DEFAULT 0 + ) STRICT; + INSERT INTO entries (key, value, revision, expires_at, last_used_at, user_protected) + VALUES ('legacy', X'00', 7, NULL, 50, 0); + PRAGMA user_version = 13;", + ) + .unwrap(); + drop(conn); + + let mut upgraded = store(&dir); + assert_eq!(upgraded.get("legacy", 100).unwrap().unwrap().revision, 7); + let outcome = upgraded.archive_entries(8).unwrap(); + assert_eq!(outcome.records, 1); + assert!(upgraded.get("legacy", 100).unwrap().is_none()); + drop(upgraded); + + let reopened = store(&dir); + assert!(reopened.get("legacy", 100).unwrap().is_none()); + assert_eq!(reopened.archived_usage().unwrap().records, 1); +} + +#[test] +fn namespace_helpers_archive_and_remove_only_one_profile() { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path(); + let kept = namespace_dir(root, "publisher-a", "org.example", "profile-1"); + let other = namespace_dir(root, "publisher-a", "org.example", "profile-2"); + let mut first = store(&kept); + first + .put("key", b"value", 1, None, 100, QUOTA_BYTES) + .unwrap(); + drop(first); + let mut second = store(&other); + second + .put("key", b"other", 1, None, 100, QUOTA_BYTES) + .unwrap(); + drop(second); + + assert_eq!( + namespace_usage(root, "publisher-a", "org.example", "profile-1", 100) + .unwrap() + .unwrap() + .logical_bytes, + charge("key", 5) + ); + let archived = archive_namespace(root, "publisher-a", "org.example", "profile-1") + .unwrap() + .unwrap(); + assert_eq!(archived.records, 1); + assert_eq!( + namespace_archived_usage(root, "publisher-a", "org.example", "profile-1") + .unwrap() + .unwrap(), + archived + ); + assert_eq!( + namespace_usage(root, "publisher-a", "org.example", "profile-2", 100) + .unwrap() + .unwrap() + .logical_bytes, + charge("key", 5) + ); + + assert!(remove_namespace(root, "publisher-a", "org.example", "profile-1").unwrap()); + assert!(!kept.exists()); + assert!(other.exists(), "another profile is untouched"); + assert!(!remove_namespace(root, "publisher-a", "org.example", "profile-1").unwrap()); + assert_eq!( + namespace_usage(root, "publisher-a", "org.example", "profile-2", 100) + .unwrap() + .unwrap() + .logical_bytes, + charge("key", 5) + ); +} + +#[test] +fn a_reviewed_reclaim_drops_archived_unprotected_entries_only() { + let temp = tempfile::tempdir().unwrap(); + let mut store = store(temp.path()); + store + .put("protected", b"keep", 1, None, 100, QUOTA_BYTES) + .unwrap(); + store + .put("plain", b"drop", 2, None, 100, QUOTA_BYTES) + .unwrap(); + assert!(store.set_user_protected("protected", true).unwrap()); + store.archive_entries(3).unwrap(); + + let reclaimed = store.reclaim_archived(4).unwrap(); + assert_eq!(reclaimed.records, 1); + assert_eq!(reclaimed.logical_bytes, charge("plain", 4)); + assert_eq!(store.archived_usage().unwrap().records, 1); + assert_eq!(store.high_water().unwrap(), 4); + assert!( + store.reuse_archived_entries(100, 5).unwrap().records == 1, + "the protected archived row is still restorable" + ); + assert!(store.get("protected", 100).unwrap().is_some()); +} + +#[test] +fn a_version_fourteen_store_gains_the_host_only_migration_marker() { + let temp = tempfile::tempdir().unwrap(); + let dir = temp.path().join("ns"); + fs::create_dir_all(&dir).unwrap(); + let conn = Connection::open(dir.join(STORE_FILE)).unwrap(); + conn.execute_batch( + "CREATE TABLE meta (id INTEGER PRIMARY KEY CHECK (id = 1), revision INTEGER NOT NULL) STRICT; + INSERT INTO meta (id, revision) VALUES (1, 7); + CREATE TABLE entries ( + key TEXT PRIMARY KEY, + value BLOB NOT NULL, + revision INTEGER NOT NULL CHECK (revision >= 1), + expires_at INTEGER, + last_used_at INTEGER NOT NULL DEFAULT 0, + user_protected INTEGER NOT NULL DEFAULT 0, + archived INTEGER NOT NULL DEFAULT 0 + ) STRICT; + INSERT INTO entries + (key, value, revision, expires_at, last_used_at, user_protected, archived) + VALUES ('legacy', X'00', 7, NULL, 50, 0, 0); + PRAGMA user_version = 14;", + ) + .unwrap(); + drop(conn); + + let upgraded = store(&dir); + assert_eq!(upgraded.get("legacy", 100).unwrap().unwrap().revision, 7); + assert!(upgraded.high_water().unwrap() >= 7); + drop(upgraded); + + let reopened = store(&dir); + assert!(reopened.get("legacy", 100).unwrap().is_some()); + let marker: i64 = reopened + .conn + .query_row( + "SELECT COUNT(*) FROM pragma_table_info('entries') WHERE name = 'migrated_from'", + [], + |row| row.get(0), + ) + .unwrap(); + assert_eq!(marker, 1); +} + +#[test] +fn migration_preview_counts_candidates_without_writing_or_creating_a_store() { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path(); + let mut source = DurableStore::open(&namespace_dir( + root, + "publisher-old", + "org.example", + "profile-1", + )) + .unwrap(); + source + .put("shared", b"old", 1, None, 100, QUOTA_BYTES) + .unwrap(); + source + .put("conflict", b"old", 2, None, 100, QUOTA_BYTES) + .unwrap(); + source + .put("expiring", b"soon", 3, Some(150), 100, QUOTA_BYTES) + .unwrap(); + source + .put("expired", b"gone", 4, Some(50), 40, QUOTA_BYTES) + .unwrap(); + drop(source); + let target_dir = namespace_dir(root, "publisher-new", "org.example", "profile-1"); + let mut target = DurableStore::open(&target_dir).unwrap(); + target + .put("conflict", b"new", 1, None, 100, QUOTA_BYTES) + .unwrap(); + drop(target); + + // Archived rows of another profile of the same plugin are reported for that profile only. + let mut archived = DurableStore::open(&namespace_dir( + root, + "publisher-old", + "org.example", + "profile-2", + )) + .unwrap(); + archived + .put("kept", b"kept", 1, None, 100, QUOTA_BYTES) + .unwrap(); + archived.archive_entries(2).unwrap(); + drop(archived); + + let preview = migration_preview( + root, + "publisher-old", + "org.example", + "profile-1", + "publisher-new", + "org.example", + "profile-1", + 100, + ) + .unwrap(); + assert!(preview.source_present); + assert_eq!(preview.records, 3); + assert_eq!(preview.eligible_records, 2, "`shared` and `expiring`"); + assert_eq!( + preview.eligible_bytes, + charge("shared", 3) + charge("expiring", 4) + ); + assert_eq!(preview.conflict_records, 1); + assert_eq!( + preview.expired_records, 1, + "the expired pending row is not eligible" + ); + assert_eq!( + preview.logical_bytes, + charge("shared", 3) + charge("conflict", 3) + charge("expiring", 4) + ); + assert_eq!(preview.target_records, 1); + assert_eq!(preview.target_logical_bytes, charge("conflict", 3)); + let unchanged = DurableStore::open(&target_dir).unwrap(); + assert_eq!(unchanged.high_water().unwrap(), 1, "a preview never writes"); + assert_eq!(unchanged.persistence_entries(100).unwrap().len(), 1); + + let archived_preview = migration_preview( + root, + "publisher-old", + "org.example", + "profile-2", + "publisher-new", + "org.example", + "profile-2", + 100, + ) + .unwrap(); + assert!(archived_preview.source_present); + assert_eq!(archived_preview.records, 0); + assert_eq!(archived_preview.archived_records, 1); + assert_eq!(archived_preview.eligible_records, 0); + + let empty = migration_preview( + root, + "publisher-old", + "org.example", + "profile-3", + "publisher-new", + "org.example", + "profile-3", + 100, + ) + .unwrap(); + assert!(!empty.source_present); + assert!(!namespace_dir(root, "publisher-new", "org.example", "profile-3").exists()); +} + +#[test] +fn migration_copies_live_entries_and_keeps_source_expired_and_conflicts() { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path(); + let mut source_store = DurableStore::open(&namespace_dir( + root, + "publisher-old", + "org.example", + "profile-1", + )) + .unwrap(); + source_store + .put("copy", b"value", 1, None, 100, QUOTA_BYTES) + .unwrap(); + source_store + .put("conflict", b"old", 2, None, 100, QUOTA_BYTES) + .unwrap(); + source_store + .put("protected", b"keep", 4, None, 100, QUOTA_BYTES) + .unwrap(); + source_store.set_user_protected("protected", true).unwrap(); + // Written last so no later write's expiry sweep removes it before the migration runs. + source_store + .put("expired", b"gone", 3, Some(90), 80, QUOTA_BYTES) + .unwrap(); + let mut target_store = DurableStore::open(&namespace_dir( + root, + "publisher-new", + "org.example", + "profile-1", + )) + .unwrap(); + target_store + .put("conflict", b"new", 1, None, 100, QUOTA_BYTES) + .unwrap(); + drop(target_store); + + let outcome = migrate_namespace( + root, + "publisher-old", + "org.example", + "profile-1", + "publisher-new", + "org.example", + "profile-1", + 100, + ) + .unwrap(); + assert!(outcome.source_present); + assert_eq!(outcome.copied_records, 2); + assert_eq!(outcome.conflict_records, 1); + assert_eq!(outcome.expired_records, 1); + assert_eq!( + outcome.copied_bytes, + charge("copy", 5) + charge("protected", 4) + ); + + let target = DurableStore::open(&namespace_dir( + root, + "publisher-new", + "org.example", + "profile-1", + )) + .unwrap(); + assert_eq!(target.get("copy", 100).unwrap().unwrap().value, b"value"); + assert_eq!( + target.get("protected", 100).unwrap().unwrap().value, + b"keep" + ); + assert_eq!( + target.get("conflict", 100).unwrap().unwrap().value, + b"new", + "an existing key is never overwritten" + ); + assert!(target.get("expired", 100).unwrap().is_none()); + assert!( + target + .persistence_entries(100) + .unwrap() + .iter() + .any(|entry| entry.key == "protected" && entry.user_protected), + "protection follows the copied entry" + ); + + // The old namespace and another profile stay exactly as they were. + let source = DurableStore::open(&namespace_dir( + root, + "publisher-old", + "org.example", + "profile-1", + )) + .unwrap(); + assert_eq!(source.get("copy", 100).unwrap().unwrap().value, b"value"); + assert_eq!(source.get("conflict", 100).unwrap().unwrap().value, b"old"); + assert!(source.get("expired", 100).unwrap().is_none()); + assert!( + !namespace_dir(root, "publisher-new", "org.example", "profile-2").exists(), + "another profile is never crossed" + ); + + assert!(matches!( + migrate_namespace( + root, + "publisher-old", + "org.example", + "profile-1", + "publisher-old", + "org.example", + "profile-1", + 100, + ), + Err(PluginStorageError::InvalidMigration) + )); +} + +#[test] +fn rollback_removes_only_tagged_unprotected_copies() { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path(); + let mut source_store = DurableStore::open(&namespace_dir( + root, + "publisher-old", + "org.example", + "profile-1", + )) + .unwrap(); + source_store + .put("plain", b"old", 1, None, 100, QUOTA_BYTES) + .unwrap(); + source_store + .put("protected", b"old", 2, None, 100, QUOTA_BYTES) + .unwrap(); + drop(source_store); + migrate_namespace( + root, + "publisher-old", + "org.example", + "profile-1", + "publisher-new", + "org.example", + "profile-1", + 100, + ) + .unwrap(); + + // A key the new identity wrote itself must survive a rollback, and a migrated key the user + // protects since then must stay too. + let target_dir = namespace_dir(root, "publisher-new", "org.example", "profile-1"); + let mut target = DurableStore::open(&target_dir).unwrap(); + target + .put("own", b"new", 10, None, 100, QUOTA_BYTES) + .unwrap(); + assert!(target.set_user_protected("protected", true).unwrap()); + drop(target); + + let reverted = revert_migrated_namespace( + root, + "publisher-new", + "org.example", + "profile-1", + "publisher-old", + ) + .unwrap() + .unwrap(); + assert_eq!(reverted.removed_records, 1); + assert_eq!(reverted.reclaimed_bytes, charge("plain", 3)); + assert_eq!(reverted.kept_protected_records, 1); + + let target = DurableStore::open(&target_dir).unwrap(); + assert!(target.get("plain", 100).unwrap().is_none()); + assert!(target.get("protected", 100).unwrap().is_some()); + assert!(target.get("own", 100).unwrap().is_some()); + let source = DurableStore::open(&namespace_dir( + root, + "publisher-old", + "org.example", + "profile-1", + )) + .unwrap(); + assert!(source.get("plain", 100).unwrap().is_some()); + assert!(source.get("protected", 100).unwrap().is_some()); + assert!( + revert_migrated_namespace( + root, + "publisher-new", + "org.example", + "profile-2", + "publisher-old", + ) + .unwrap() + .is_none() + ); +} diff --git a/crates/platform/src/plugin_telemetry.rs b/crates/platform/src/plugin_telemetry.rs new file mode 100644 index 000000000..e7f19765b --- /dev/null +++ b/crates/platform/src/plugin_telemetry.rs @@ -0,0 +1,898 @@ +//! Bounded persistence for plugin-produced hardware, diagnostic, presence, and +//! performance records. +//! +//! This module is a storage boundary, not a collector: it never launches a +//! benchmark, SMART utility, game process, or instrumentation hook. The host +//! must construct [`TelemetryOwner`] from the authenticated plugin session and +//! perform consent, field projection, and schema validation before publishing +//! or returning a record. All methods are synchronous SQLite operations and +//! must be called from a blocking worker. + +use std::fs; +use std::path::Path; +use std::sync::{Mutex, MutexGuard}; + +use rusqlite::{Connection, OptionalExtension, TransactionBehavior, params}; +use serde::{Deserialize, Serialize}; +use sha2::Digest; + +/// Maximum serialized payload size accepted for an individual telemetry record. +pub const MAX_RECORD_BYTES: usize = 1024 * 1024; +/// Maximum retained logical payload bytes for one plugin/profile owner. +pub const OWNER_QUOTA_BYTES: u64 = 16 * 1024 * 1024; +/// Maximum retained record count per authenticated plugin/profile owner. +pub const OWNER_QUOTA_RECORDS: u64 = 16_384; +/// Maximum number of records returned from one page. +pub const MAX_PAGE_SIZE: usize = 256; + +const SCHEMA_VERSION: i64 = 2; + +/// Host-authenticated attribution for a producer. Construct this from the +/// resolved package/session identity; never copy it from a plugin payload. +#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] +pub struct TelemetryOwner { + /// Authenticated producer/source plugin id. + pub plugin_id: String, + /// Developer/name declared in the integrity-signed package manifest. + pub developer: String, + /// Origin declared in package metadata (or a host-defined local-import origin). + pub origin: String, + /// Host-known installation path, such as manual import or signed update feed. + pub install_source: String, + pub publisher_fingerprint: String, + pub package_version: String, + /// SHA-256 digest of the exact installed package payload. + pub package_digest: String, + pub profile_id: String, +} + +impl TelemetryOwner { + fn validate(&self) -> Result<(), TelemetryError> { + for (name, value, limit) in [ + ("plugin id", self.plugin_id.as_str(), 256), + ("developer", self.developer.as_str(), 256), + ("origin", self.origin.as_str(), 2048), + ("install source", self.install_source.as_str(), 128), + ( + "publisher fingerprint", + self.publisher_fingerprint.as_str(), + 256, + ), + ("package version", self.package_version.as_str(), 128), + ("package digest", self.package_digest.as_str(), 64), + ("profile id", self.profile_id.as_str(), 256), + ] { + if value.is_empty() || value.len() > limit || value.chars().any(char::is_control) { + return Err(TelemetryError::InvalidIdentity(name)); + } + } + if self.package_digest.len() != 64 + || !self + .package_digest + .bytes() + .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)) + { + return Err(TelemetryError::InvalidIdentity("package digest")); + } + Ok(()) + } +} + +/// A persisted producer family. The family and all attribution fields are +/// separate from the extension payload and cannot be shadowed by it. +#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum TelemetryFamily { + StorageDiagnostic, + Computer, + GamePresence, + GamePerformance, +} + +impl TelemetryFamily { + fn as_str(self) -> &'static str { + match self { + Self::StorageDiagnostic => "storage_diagnostic", + Self::Computer => "computer", + Self::GamePresence => "game_presence", + Self::GamePerformance => "game_performance", + } + } +} + +/// One host-attributed record. `resource_id` identifies the volume, computer, +/// game/session, or performance series according to `family`; its meaning is +/// interpreted by the host API layer. `sequence` is optional for families that +/// do not publish ordered batches. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct TelemetryRecord { + pub family: TelemetryFamily, + pub resource_id: String, + pub schema_id: String, + pub schema_version: u32, + pub observed_at: i64, + pub expires_at: Option, + pub sequence: Option, + pub payload: serde_json::Value, +} + +/// A record after loading from the host-owned store. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct StoredTelemetryRecord { + /// Host-generated, globally namespaced record identifier. + pub record_id: String, + pub record: TelemetryRecord, + pub owner: TelemetryOwner, + /// Host receipt time in Unix seconds. + pub received_at: i64, + pub revision: u64, + pub payload_bytes: u64, +} + +#[derive(Debug, thiserror::Error)] +pub enum TelemetryError { + #[error("invalid telemetry identity: {0}")] + InvalidIdentity(&'static str), + #[error("invalid telemetry record: {0}")] + InvalidRecord(&'static str), + #[error("telemetry record exceeds the per-record size limit")] + RecordTooLarge, + #[error("telemetry owner quota is exhausted")] + QuotaExceeded, + #[error("telemetry sequence is duplicate or out of order")] + SequenceConflict, + #[error("telemetry record does not exist")] + NotFound, + #[error("telemetry database failed")] + Database(#[from] rusqlite::Error), + #[error("telemetry database could not be opened")] + Open(#[source] std::io::Error), + #[error("telemetry database was created by a newer version of GameNode")] + NewerVersion, + #[error("telemetry record encoding failed")] + Encoding(#[from] serde_json::Error), +} + +/// SQLite-backed records produced by third-party plugins. +/// +/// The database owns only plugin-published data. Callers remain responsible +/// for authorizing the producer and each consumer before calling these methods. +pub struct PluginTelemetryStore { + connection: Mutex, +} + +impl PluginTelemetryStore { + /// Opens or creates a store at `path`. Filesystem and SQLite work are + /// blocking and should be invoked from `spawn_blocking` or the host's + /// equivalent worker. + pub fn open(path: &Path) -> Result { + if let Some(parent) = path.parent() { + fs::create_dir_all(parent).map_err(TelemetryError::Open)?; + } + let connection = Connection::open(path)?; + connection.busy_timeout(std::time::Duration::from_secs(5))?; + let version: i64 = connection.query_row("PRAGMA user_version", [], |row| row.get(0))?; + if version > SCHEMA_VERSION { + return Err(TelemetryError::NewerVersion); + } + if version < 1 { + connection.execute_batch( + "BEGIN; + CREATE TABLE telemetry_records ( + record_id TEXT PRIMARY KEY, + family TEXT NOT NULL, + resource_id TEXT NOT NULL, + plugin_id TEXT NOT NULL, + developer TEXT NOT NULL, + origin TEXT NOT NULL, + install_source TEXT NOT NULL, + publisher_fingerprint TEXT NOT NULL, + package_version TEXT NOT NULL, + package_digest TEXT NOT NULL, + profile_id TEXT NOT NULL, + schema_id TEXT NOT NULL, + schema_version INTEGER NOT NULL CHECK (schema_version >= 0), + observed_at INTEGER NOT NULL, + expires_at INTEGER, + sequence INTEGER, + revision INTEGER NOT NULL CHECK (revision >= 1), + received_at INTEGER NOT NULL, + payload BLOB NOT NULL, + payload_bytes INTEGER NOT NULL CHECK (payload_bytes >= 0), + CHECK (expires_at IS NULL OR expires_at > observed_at) + ) STRICT; + CREATE INDEX telemetry_owner_records + ON telemetry_records(plugin_id, publisher_fingerprint, profile_id, revision); + CREATE INDEX telemetry_family_resource + ON telemetry_records(family, resource_id, revision); + CREATE UNIQUE INDEX telemetry_sequence + ON telemetry_records(plugin_id, publisher_fingerprint, profile_id, + family, resource_id, sequence) + WHERE sequence IS NOT NULL; + CREATE TABLE telemetry_revisions ( + plugin_id TEXT NOT NULL, + publisher_fingerprint TEXT NOT NULL, + profile_id TEXT NOT NULL, + revision INTEGER NOT NULL CHECK (revision >= 0), + PRIMARY KEY (plugin_id, publisher_fingerprint, profile_id) + ) STRICT; + CREATE TABLE telemetry_sequences ( + plugin_id TEXT NOT NULL, + publisher_fingerprint TEXT NOT NULL, + profile_id TEXT NOT NULL, + family TEXT NOT NULL, + resource_id TEXT NOT NULL, + sequence INTEGER NOT NULL CHECK (sequence >= 0), + PRIMARY KEY (plugin_id, publisher_fingerprint, profile_id, + family, resource_id) + ) STRICT; + PRAGMA user_version = 2; + COMMIT;", + )?; + } else if version < 2 { + connection.execute_batch( + "BEGIN IMMEDIATE; + ALTER TABLE telemetry_records ADD COLUMN developer TEXT NOT NULL DEFAULT ''; + ALTER TABLE telemetry_records ADD COLUMN origin TEXT NOT NULL DEFAULT ''; + ALTER TABLE telemetry_records ADD COLUMN install_source TEXT NOT NULL DEFAULT ''; + ALTER TABLE telemetry_records ADD COLUMN package_digest TEXT NOT NULL DEFAULT ''; + ALTER TABLE telemetry_records ADD COLUMN received_at INTEGER NOT NULL DEFAULT 0; + CREATE TABLE telemetry_sequences ( + plugin_id TEXT NOT NULL, + publisher_fingerprint TEXT NOT NULL, + profile_id TEXT NOT NULL, + family TEXT NOT NULL, + resource_id TEXT NOT NULL, + sequence INTEGER NOT NULL CHECK (sequence >= 0), + PRIMARY KEY (plugin_id, publisher_fingerprint, profile_id, + family, resource_id) + ) STRICT; + INSERT INTO telemetry_sequences + (plugin_id, publisher_fingerprint, profile_id, family, resource_id, sequence) + SELECT plugin_id, publisher_fingerprint, profile_id, family, resource_id, + MAX(sequence) + FROM telemetry_records WHERE sequence IS NOT NULL + GROUP BY plugin_id, publisher_fingerprint, profile_id, family, resource_id; + PRAGMA user_version = 2; + COMMIT;", + )?; + } + Ok(Self { + connection: Mutex::new(connection), + }) + } + + /// Saves a host-attributed record, assigning its monotonically increasing + /// revision within the producer's plugin/publisher/profile namespace. + /// Expired records are reclaimed before quota accounting. Publication is + /// append-only; callers use a new host-generated record ID for each update. + pub fn publish( + &self, + owner: &TelemetryOwner, + record: &TelemetryRecord, + now: i64, + ) -> Result { + owner.validate()?; + validate_record(record, now)?; + let payload = serde_json::to_vec(&record.payload)?; + if payload.len() > MAX_RECORD_BYTES { + return Err(TelemetryError::RecordTooLarge); + } + let mut connection = self.lock(); + let transaction = connection.transaction_with_behavior(TransactionBehavior::Immediate)?; + transaction.execute( + "DELETE FROM telemetry_records WHERE expires_at IS NOT NULL AND expires_at <= ?1", + [now], + )?; + let used: i64 = transaction.query_row( + "SELECT COALESCE(SUM(payload_bytes), 0) FROM telemetry_records + WHERE plugin_id = ?1 AND publisher_fingerprint = ?2 AND profile_id = ?3", + params![ + owner.plugin_id, + owner.publisher_fingerprint, + owner.profile_id + ], + |row| row.get(0), + )?; + let used = + u64::try_from(used).map_err(|_| TelemetryError::InvalidRecord("stored byte count"))?; + let count: i64 = transaction.query_row( + "SELECT COUNT(*) FROM telemetry_records + WHERE plugin_id = ?1 AND publisher_fingerprint = ?2 AND profile_id = ?3", + params![ + owner.plugin_id, + owner.publisher_fingerprint, + owner.profile_id + ], + |row| row.get(0), + )?; + if u64::try_from(count).map_err(|_| TelemetryError::InvalidRecord("stored record count"))? + >= OWNER_QUOTA_RECORDS + { + return Err(TelemetryError::QuotaExceeded); + } + let payload_bytes = + i64::try_from(payload.len()).map_err(|_| TelemetryError::RecordTooLarge)?; + let projected = used.saturating_add(payload.len() as u64); + if projected > OWNER_QUOTA_BYTES { + return Err(TelemetryError::QuotaExceeded); + } + if let Some(sequence) = record.sequence { + let latest: Option = transaction + .query_row( + "SELECT sequence FROM telemetry_sequences + WHERE plugin_id = ?1 AND publisher_fingerprint = ?2 AND profile_id = ?3 + AND family = ?4 AND resource_id = ?5", + params![ + owner.plugin_id, + owner.publisher_fingerprint, + owner.profile_id, + record.family.as_str(), + record.resource_id + ], + |row| row.get(0), + ) + .optional()?; + if latest + .map(u64::try_from) + .transpose() + .map_err(|_| TelemetryError::InvalidRecord("stored sequence"))? + .is_some_and(|current| sequence <= current) + { + return Err(TelemetryError::SequenceConflict); + } + } + let revision = next_revision(&transaction, owner)?; + let record_id = host_record_id(owner, revision); + transaction.execute( + "INSERT INTO telemetry_records + (record_id, family, resource_id, plugin_id, developer, origin, install_source, + publisher_fingerprint, package_version, package_digest, profile_id, schema_id, + schema_version, observed_at, expires_at, sequence, revision, received_at, + payload, payload_bytes) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, + ?15, ?16, ?17, ?18, ?19, ?20)", + params![ + record_id, + record.family.as_str(), + record.resource_id, + owner.plugin_id, + owner.developer, + owner.origin, + owner.install_source, + owner.publisher_fingerprint, + owner.package_version, + owner.package_digest, + owner.profile_id, + record.schema_id, + i64::from(record.schema_version), + record.observed_at, + record.expires_at, + record + .sequence + .map(i64::try_from) + .transpose() + .map_err(|_| TelemetryError::InvalidRecord("sequence exceeds SQLite range"))?, + i64::try_from(revision) + .map_err(|_| TelemetryError::InvalidRecord("revision exceeds SQLite range"))?, + now, + payload, + payload_bytes, + ], + )?; + if let Some(sequence) = record.sequence { + transaction.execute( + "INSERT INTO telemetry_sequences + (plugin_id, publisher_fingerprint, profile_id, family, resource_id, sequence) + VALUES (?1, ?2, ?3, ?4, ?5, ?6) + ON CONFLICT(plugin_id, publisher_fingerprint, profile_id, family, resource_id) + DO UPDATE SET sequence = excluded.sequence", + params![ + owner.plugin_id, + owner.publisher_fingerprint, + owner.profile_id, + record.family.as_str(), + record.resource_id, + i64::try_from(sequence).map_err(|_| { + TelemetryError::InvalidRecord("sequence exceeds SQLite range") + })?, + ], + )?; + } + transaction.commit()?; + Ok(StoredTelemetryRecord { + record_id, + record: record.clone(), + owner: owner.clone(), + received_at: now, + revision, + payload_bytes: payload.len() as u64, + }) + } + + /// Loads one record by its host-assigned ID. The caller must still apply + /// consumer authorization and projections before returning it. + pub fn get( + &self, + record_id: &str, + now: i64, + ) -> Result, TelemetryError> { + if record_id.is_empty() || record_id.len() > 256 { + return Err(TelemetryError::InvalidRecord("record id")); + } + let connection = self.lock(); + let row = connection + .query_row( + "SELECT record_id, family, resource_id, plugin_id, publisher_fingerprint, + package_version, profile_id, schema_id, schema_version, observed_at, + expires_at, sequence, revision, payload, payload_bytes, developer, origin, + install_source, package_digest, received_at + FROM telemetry_records WHERE record_id = ?1 + AND (expires_at IS NULL OR expires_at > ?2)", + params![record_id, now], + stored_record_from_row, + ) + .optional()?; + Ok(row) + } + + /// Lists a bounded page for a family and optional resource. `owner` is an + /// optional host-resolved source filter; `None` means all sources and must + /// only be used after the host has established a matching read grant. + pub fn list( + &self, + family: TelemetryFamily, + resource_id: Option<&str>, + owner: Option<&TelemetryOwner>, + after_revision: u64, + page_size: usize, + now: i64, + ) -> Result, TelemetryError> { + if let Some(owner) = owner { + owner.validate()?; + } + if resource_id.is_some_and(|id| id.len() > 256 || id.chars().any(char::is_control)) { + return Err(TelemetryError::InvalidRecord("resource id")); + } + let page_size = page_size.clamp(1, MAX_PAGE_SIZE); + let connection = self.lock(); + let mut statement = connection.prepare( + "SELECT record_id, family, resource_id, plugin_id, publisher_fingerprint, + package_version, profile_id, schema_id, schema_version, observed_at, + expires_at, sequence, revision, payload, payload_bytes, developer, origin, + install_source, package_digest, received_at + FROM telemetry_records + WHERE family = ?1 AND revision > ?2 + AND (?3 IS NULL OR resource_id = ?3) + AND (?4 IS NULL OR plugin_id = ?4) + AND (?5 IS NULL OR publisher_fingerprint = ?5) + AND (?6 IS NULL OR profile_id = ?6) + AND (expires_at IS NULL OR expires_at > ?7) + ORDER BY revision ASC LIMIT ?8", + )?; + let rows = statement.query_map( + params![ + family.as_str(), + i64::try_from(after_revision) + .map_err(|_| TelemetryError::InvalidRecord("cursor exceeds SQLite range"))?, + resource_id, + owner.map(|value| value.plugin_id.as_str()), + owner.map(|value| value.publisher_fingerprint.as_str()), + owner.map(|value| value.profile_id.as_str()), + now, + i64::try_from(page_size) + .map_err(|_| TelemetryError::InvalidRecord("page size exceeds SQLite range"))?, + ], + stored_record_from_row, + )?; + Ok(rows.collect::, _>>()?) + } + + /// Removes expired records and returns the number of rows reclaimed. + pub fn expire(&self, now: i64) -> Result { + let connection = self.lock(); + let count = connection.execute( + "DELETE FROM telemetry_records WHERE expires_at IS NOT NULL AND expires_at <= ?1", + [now], + )?; + Ok(count as u64) + } + + fn lock(&self) -> MutexGuard<'_, Connection> { + self.connection + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + } +} + +fn validate_record(record: &TelemetryRecord, now: i64) -> Result<(), TelemetryError> { + for (name, value, limit) in [ + ("resource id", record.resource_id.as_str(), 256), + ("schema id", record.schema_id.as_str(), 256), + ] { + if value.is_empty() || value.len() > limit || value.chars().any(char::is_control) { + return Err(TelemetryError::InvalidRecord(name)); + } + } + if record.observed_at <= 0 || record.observed_at > now.saturating_add(300) { + return Err(TelemetryError::InvalidRecord("observation time")); + } + if record.schema_version == 0 { + return Err(TelemetryError::InvalidRecord("schema version")); + } + if record.sequence == Some(0) { + return Err(TelemetryError::InvalidRecord("sequence")); + } + if record.family == TelemetryFamily::GamePresence && record.expires_at.is_none() { + return Err(TelemetryError::InvalidRecord( + "presence records require an expiry", + )); + } + if record + .expires_at + .is_some_and(|expiry| expiry <= now || expiry <= record.observed_at) + { + return Err(TelemetryError::InvalidRecord("expiry")); + } + if !record.payload.is_object() { + return Err(TelemetryError::InvalidRecord("payload must be an object")); + } + const RESERVED_FIELDS: &[&str] = &[ + "source", + "developer", + "origin", + "plugin_id", + "owner_plugin_id", + "publisher", + "publisher_fingerprint", + "version", + "package", + "package_version", + "package_digest", + "install_source", + "profile_id", + "provenance", + "record_id", + "schema_id", + "schema_version", + "resource_id", + "observed_at", + "received_at", + "expires_at", + "sequence", + ]; + if record + .payload + .as_object() + .is_some_and(|fields| RESERVED_FIELDS.iter().any(|key| fields.contains_key(*key))) + { + return Err(TelemetryError::InvalidRecord( + "payload contains a host-owned attribution or envelope field", + )); + } + Ok(()) +} + +fn host_record_id(owner: &TelemetryOwner, revision: u64) -> String { + let mut identity = sha2::Sha256::new(); + identity.update(b"gamenode.telemetry-record.v1\0"); + for part in [ + owner.plugin_id.as_bytes(), + owner.publisher_fingerprint.as_bytes(), + owner.profile_id.as_bytes(), + ] { + identity.update((part.len() as u64).to_be_bytes()); + identity.update(part); + } + let namespace = identity.finalize(); + let namespace = namespace + .iter() + .map(|byte| format!("{byte:02x}")) + .collect::(); + format!("telemetry-{namespace}-{revision}") +} + +fn next_revision( + transaction: &rusqlite::Transaction<'_>, + owner: &TelemetryOwner, +) -> Result { + transaction.execute( + "INSERT OR IGNORE INTO telemetry_revisions + (plugin_id, publisher_fingerprint, profile_id, revision) VALUES (?1, ?2, ?3, 0)", + params![ + owner.plugin_id, + owner.publisher_fingerprint, + owner.profile_id + ], + )?; + transaction.execute( + "UPDATE telemetry_revisions SET revision = revision + 1 + WHERE plugin_id = ?1 AND publisher_fingerprint = ?2 AND profile_id = ?3", + params![ + owner.plugin_id, + owner.publisher_fingerprint, + owner.profile_id + ], + )?; + let revision: i64 = transaction.query_row( + "SELECT revision FROM telemetry_revisions + WHERE plugin_id = ?1 AND publisher_fingerprint = ?2 AND profile_id = ?3", + params![ + owner.plugin_id, + owner.publisher_fingerprint, + owner.profile_id + ], + |row| row.get(0), + )?; + u64::try_from(revision).map_err(|_| TelemetryError::InvalidRecord("stored revision")) +} + +fn stored_record_from_row(row: &rusqlite::Row<'_>) -> rusqlite::Result { + let family: String = row.get(1)?; + let family = match family.as_str() { + "storage_diagnostic" => TelemetryFamily::StorageDiagnostic, + "computer" => TelemetryFamily::Computer, + "game_presence" => TelemetryFamily::GamePresence, + "game_performance" => TelemetryFamily::GamePerformance, + _ => return Err(rusqlite::Error::InvalidQuery), + }; + let payload: Vec = row.get(13)?; + let payload = serde_json::from_slice(&payload).map_err(|error| { + rusqlite::Error::FromSqlConversionFailure(13, rusqlite::types::Type::Blob, Box::new(error)) + })?; + let sequence: Option = row.get(11)?; + let revision: i64 = row.get(12)?; + let payload_bytes: i64 = row.get(14)?; + let developer: String = row.get(15)?; + let origin: String = row.get(16)?; + let install_source: String = row.get(17)?; + let package_digest: String = row.get(18)?; + let received_at: i64 = row.get(19)?; + let sequence = sequence.map(u64::try_from).transpose().map_err(|error| { + rusqlite::Error::FromSqlConversionFailure( + 11, + rusqlite::types::Type::Integer, + Box::new(error), + ) + })?; + let revision = u64::try_from(revision).map_err(|error| { + rusqlite::Error::FromSqlConversionFailure( + 12, + rusqlite::types::Type::Integer, + Box::new(error), + ) + })?; + let payload_bytes = u64::try_from(payload_bytes).map_err(|error| { + rusqlite::Error::FromSqlConversionFailure( + 14, + rusqlite::types::Type::Integer, + Box::new(error), + ) + })?; + Ok(StoredTelemetryRecord { + record_id: row.get(0)?, + record: TelemetryRecord { + family, + resource_id: row.get(2)?, + schema_id: row.get(7)?, + schema_version: row.get(8)?, + observed_at: row.get(9)?, + expires_at: row.get(10)?, + sequence, + payload, + }, + owner: TelemetryOwner { + plugin_id: row.get(3)?, + developer, + origin, + install_source, + publisher_fingerprint: row.get(4)?, + package_version: row.get(5)?, + package_digest, + profile_id: row.get(6)?, + }, + received_at, + revision, + payload_bytes, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn owner() -> TelemetryOwner { + TelemetryOwner { + plugin_id: "org.example.collector".into(), + developer: "Example Developer".into(), + origin: "https://plugins.example/collector".into(), + install_source: "manual-import".into(), + publisher_fingerprint: "SHA256:publisher-key".into(), + package_version: "1.2.3".into(), + package_digest: "a".repeat(64), + profile_id: "profile-a".into(), + } + } + + fn record(sequence: Option, expires_at: Option) -> TelemetryRecord { + TelemetryRecord { + family: TelemetryFamily::GamePerformance, + resource_id: "series-1".into(), + schema_id: "org.example.performance.v1".into(), + schema_version: 1, + observed_at: 100, + expires_at, + sequence, + payload: json!({"frames_per_second": 60.0, "cpu_percent": 12.5}), + } + } + + #[test] + fn publication_assigns_provenance_record_id_and_receipt_time() { + let temp = tempfile::tempdir().unwrap(); + let store = PluginTelemetryStore::open(&temp.path().join("telemetry.sqlite")).unwrap(); + let owner = owner(); + let stored = store + .publish(&owner, &record(Some(1), Some(200)), 110) + .unwrap(); + + assert!(stored.record_id.starts_with("telemetry-")); + assert_ne!(stored.record_id, "plugin-selected-id"); + assert_eq!(stored.owner, owner); + assert_eq!(stored.received_at, 110); + assert_eq!(stored.record.sequence, Some(1)); + assert_eq!(stored.record.schema_version, 1); + } + + #[test] + fn forged_provenance_and_envelope_fields_are_rejected() { + let temp = tempfile::tempdir().unwrap(); + let store = PluginTelemetryStore::open(&temp.path().join("telemetry.sqlite")).unwrap(); + let mut forged = record(None, Some(200)); + forged.payload = json!({ + "frames_per_second": 60.0, + "publisher_fingerprint": "SHA256:attacker", + "package_version": "9.9.9" + }); + + assert!(matches!( + store.publish(&owner(), &forged, 110), + Err(TelemetryError::InvalidRecord( + "payload contains a host-owned attribution or envelope field" + )) + )); + assert!( + store + .list(TelemetryFamily::GamePerformance, None, None, 0, 10, 110) + .unwrap() + .is_empty() + ); + } + + #[test] + fn duplicate_and_out_of_order_sequences_stay_rejected_after_expiry_and_restart() { + let temp = tempfile::tempdir().unwrap(); + let path = temp.path().join("telemetry.sqlite"); + let owner = owner(); + let store = PluginTelemetryStore::open(&path).unwrap(); + store + .publish(&owner, &record(Some(2), Some(105)), 100) + .unwrap(); + assert!(matches!( + store.publish(&owner, &record(Some(2), Some(205)), 110), + Err(TelemetryError::SequenceConflict) + )); + assert!(matches!( + store.publish(&owner, &record(Some(1), Some(205)), 110), + Err(TelemetryError::SequenceConflict) + )); + assert_eq!(store.expire(106).unwrap(), 1); + drop(store); + + let reopened = PluginTelemetryStore::open(&path).unwrap(); + assert!(matches!( + reopened.publish(&owner, &record(Some(1), Some(205)), 110), + Err(TelemetryError::SequenceConflict) + )); + assert_eq!( + reopened + .publish(&owner, &record(Some(3), Some(205)), 110) + .unwrap() + .record + .sequence, + Some(3) + ); + } + + #[test] + fn oversized_records_and_non_expiring_presence_are_refused() { + let temp = tempfile::tempdir().unwrap(); + let store = PluginTelemetryStore::open(&temp.path().join("telemetry.sqlite")).unwrap(); + let mut oversized = record(None, Some(200)); + oversized.payload = json!({"padding": "x".repeat(MAX_RECORD_BYTES)}); + assert!(matches!( + store.publish(&owner(), &oversized, 110), + Err(TelemetryError::RecordTooLarge) + )); + + let mut presence = record(Some(1), None); + presence.family = TelemetryFamily::GamePresence; + assert!(matches!( + store.publish(&owner(), &presence, 110), + Err(TelemetryError::InvalidRecord( + "presence records require an expiry" + )) + )); + } + + #[test] + fn expired_records_are_hidden_and_reclaimed_by_ttl() { + let temp = tempfile::tempdir().unwrap(); + let store = PluginTelemetryStore::open(&temp.path().join("telemetry.sqlite")).unwrap(); + let stored = store + .publish(&owner(), &record(None, Some(120)), 110) + .unwrap(); + + assert!(store.get(&stored.record_id, 119).unwrap().is_some()); + assert!(store.get(&stored.record_id, 120).unwrap().is_none()); + assert!( + store + .list(TelemetryFamily::GamePerformance, None, None, 0, 10, 120) + .unwrap() + .is_empty() + ); + assert_eq!(store.expire(120).unwrap(), 1); + } + + #[test] + fn schema_upgrade_preserves_records_and_seeds_sequence_watermarks() { + let temp = tempfile::tempdir().unwrap(); + let path = temp.path().join("telemetry.sqlite"); + let owner = owner(); + let old = Connection::open(&path).unwrap(); + old.execute_batch( + "CREATE TABLE telemetry_records ( + record_id TEXT PRIMARY KEY, + family TEXT NOT NULL, + resource_id TEXT NOT NULL, + plugin_id TEXT NOT NULL, + publisher_fingerprint TEXT NOT NULL, + package_version TEXT NOT NULL, + profile_id TEXT NOT NULL, + schema_id TEXT NOT NULL, + schema_version INTEGER NOT NULL, + observed_at INTEGER NOT NULL, + expires_at INTEGER, + sequence INTEGER, + revision INTEGER NOT NULL, + payload BLOB NOT NULL, + payload_bytes INTEGER NOT NULL + ); + CREATE TABLE telemetry_revisions ( + plugin_id TEXT NOT NULL, + publisher_fingerprint TEXT NOT NULL, + profile_id TEXT NOT NULL, + revision INTEGER NOT NULL, + PRIMARY KEY (plugin_id, publisher_fingerprint, profile_id) + ); + INSERT INTO telemetry_records VALUES ( + 'legacy-record', 'game_performance', 'series-1', + 'org.example.collector', 'SHA256:publisher-key', '1.2.3', 'profile-a', + 'org.example.performance.v1', 1, 100, 200, 2, 1, X'7B7D', 2 + ); + PRAGMA user_version = 1;", + ) + .unwrap(); + drop(old); + + let store = PluginTelemetryStore::open(&path).unwrap(); + let legacy = store.get("legacy-record", 110).unwrap().unwrap(); + assert_eq!(legacy.received_at, 0, "legacy receipt time remains unknown"); + assert_eq!(legacy.record.sequence, Some(2)); + assert!(matches!( + store.publish(&owner, &record(Some(2), Some(200)), 110), + Err(TelemetryError::SequenceConflict) + )); + } +} diff --git a/crates/platform/src/plugin_updates.rs b/crates/platform/src/plugin_updates.rs new file mode 100644 index 000000000..eed008174 --- /dev/null +++ b/crates/platform/src/plugin_updates.rs @@ -0,0 +1,536 @@ +//! Signed, replay-resistant third-party plugin update metadata and package retrieval. +//! +//! The caller supplies the user's pinned publisher key and the currently approved origins. +//! Sequence state is committed only after the complete index has passed validation. + +use crate::plugin_network::{FetchClient, Request}; +use base64::{Engine as _, engine::general_purpose::STANDARD}; +use ring::signature::{ED25519, UnparsedPublicKey}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use std::{ + fs::{self, File, OpenOptions}, + io::{self, Write}, + path::PathBuf, + sync::{Arc, Mutex}, +}; +use thiserror::Error; +use url::Url; + +pub const INDEX_SIGNATURE_DOMAIN: &[u8] = b"GameNode/plugin-update-index/v1\0"; +const MAX_INDEX_BYTES: usize = 1024 * 1024; +const MAX_PACKAGE_BYTES: u64 = crate::plugin_packages::MAX_COMPRESSED_BYTES; +const MAX_INDEX_RESPONSE_BYTES: u64 = 1_500_000; + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct SignedIndexEnvelope { + /// Base64 of the exact JSON bytes covered by the detached signature. + payload: String, + /// Lowercase hexadecimal Ed25519 signature. + signature: String, +} + +#[derive(Debug, Error, PartialEq, Eq)] +pub enum UpdateError { + #[error("update index is malformed or unsupported")] + InvalidIndex, + #[error("update index signature is invalid")] + InvalidSignature, + #[error("update index has expired")] + Expired, + #[error("update index sequence is a replay")] + Replay, + #[error("package URL is not an HTTPS URL")] + InvalidUrl, + #[error("package response failed validation")] + InvalidPackage, + #[error("update request failed: {0}")] + Fetch(String), + #[error("update state I/O failed: {0}")] + Io(String), +} + +#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct UpdateIndex { + pub schema: u32, + pub plugin_id: String, + pub sequence: u64, + /// Unix seconds; indexes are rejected at or after this instant. + pub expires_at: u64, + pub releases: Vec, +} + +/// An index whose signature, expiry, identity schema and replay sequence were accepted by the +/// verifier. The contained parsed index cannot be constructed by downstream callers. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct VerifiedUpdateIndex(UpdateIndex); + +impl VerifiedUpdateIndex { + pub fn index(&self) -> &UpdateIndex { + &self.0 + } +} + +#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct UpdateRelease { + pub version: String, + pub targets: Vec, + pub api_range: String, + pub package_url: String, + pub package_size: u64, + pub package_sha256: String, + /// Present when this release is a signed bundle rather than a single package: the lowercase + /// SHA-256 of the exact signed `bundle.json` bytes. A bundle release and a standalone release + /// are never interchangeable, so the review can reject a mixed update before downloading it. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub bundle_sha256: Option, +} + +/// Persists each publisher's highest accepted sequence under the app data directory. +#[derive(Clone, Debug)] +pub struct UpdateIndexVerifier { + root: PathBuf, + commit_lock: Arc>, +} + +impl UpdateIndexVerifier { + pub fn open(root: impl Into) -> Result { + let root = root.into(); + fs::create_dir_all(&root).map_err(io_error)?; + restrict_owner_dir(&root).map_err(io_error)?; + Ok(Self { + root, + commit_lock: Arc::new(Mutex::new(())), + }) + } + + pub fn verify( + &self, + raw: &[u8], + signature: &[u8], + key: &[u8], + now_unix: u64, + ) -> Result { + if raw.is_empty() || raw.len() > MAX_INDEX_BYTES || key.len() != 32 || signature.len() != 64 + { + return Err(UpdateError::InvalidIndex); + } + let mut signed = Vec::with_capacity(INDEX_SIGNATURE_DOMAIN.len() + raw.len()); + signed.extend_from_slice(INDEX_SIGNATURE_DOMAIN); + signed.extend_from_slice(raw); + UnparsedPublicKey::new(&ED25519, key) + .verify(&signed, signature) + .map_err(|_| UpdateError::InvalidSignature)?; + let index: UpdateIndex = + serde_json::from_slice(raw).map_err(|_| UpdateError::InvalidIndex)?; + validate_index(&index)?; + if index.expires_at <= now_unix { + return Err(UpdateError::Expired); + } + let _guard = self + .commit_lock + .lock() + .unwrap_or_else(|poison| poison.into_inner()); + let state_dir = self.root.join(safe_id(&index.plugin_id)); + fs::create_dir_all(&state_dir).map_err(io_error)?; + restrict_owner_dir(&state_dir).map_err(io_error)?; + let previous = highest_sequence(&state_dir)?; + if index.sequence <= previous { + return Err(UpdateError::Replay); + } + let path = state_dir.join(format!("seq-{}", index.sequence)); + let mut record = OpenOptions::new() + .write(true) + .create_new(true) + .open(path) + .map_err(|error| { + if error.kind() == io::ErrorKind::AlreadyExists { + UpdateError::Replay + } else { + io_error(error) + } + })?; + record + .write_all(&index.sequence.to_le_bytes()) + .map_err(io_error)?; + record.write_all(&Sha256::digest(raw)).map_err(io_error)?; + record.sync_all().map_err(io_error)?; + sync_dir(&state_dir).map_err(io_error)?; + Ok(index) + } + + /// Fetch and verify the signed JSON envelope for one per-plugin update feed. The network + /// client rechecks origin approval, DNS results and HTTPS at every redirect hop. + pub async fn check_feed( + &self, + client: &FetchClient, + feed_url: &str, + publisher_key: &[u8], + now_unix: u64, + allowed_origin: impl Fn(&str) -> bool + Send + Sync, + ) -> Result { + let request = Request::build( + feed_url, + "GET", + [], + Vec::new(), + MAX_INDEX_RESPONSE_BYTES, + 30_000, + ) + .map_err(|_| UpdateError::InvalidUrl)?; + let response = client + .fetch(request, allowed_origin) + .await + .map_err(|error| UpdateError::Fetch(error.to_string()))?; + if response.status != 200 || response.body.len() as u64 > MAX_INDEX_RESPONSE_BYTES { + return Err(UpdateError::InvalidIndex); + } + let envelope: SignedIndexEnvelope = + serde_json::from_slice(&response.body).map_err(|_| UpdateError::InvalidIndex)?; + let raw = STANDARD + .decode(envelope.payload) + .map_err(|_| UpdateError::InvalidIndex)?; + let signature = decode_signature(&envelope.signature)?; + match self.verify(&raw, &signature, publisher_key, now_unix) { + Ok(index) => Ok(VerifiedUpdateIndex(index)), + // A periodic/manual reread of the exact accepted feed is safe and useful. Equal + // sequence with different bytes and every lower sequence remain rejected. + Err(UpdateError::Replay) => self + .verify_same_sequence(&raw, &signature, publisher_key, now_unix) + .map(VerifiedUpdateIndex), + Err(error) => Err(error), + } + } + + fn verify_same_sequence( + &self, + raw: &[u8], + signature: &[u8], + key: &[u8], + now_unix: u64, + ) -> Result { + if raw.is_empty() || raw.len() > MAX_INDEX_BYTES || key.len() != 32 || signature.len() != 64 + { + return Err(UpdateError::InvalidIndex); + } + let mut signed = Vec::with_capacity(INDEX_SIGNATURE_DOMAIN.len() + raw.len()); + signed.extend_from_slice(INDEX_SIGNATURE_DOMAIN); + signed.extend_from_slice(raw); + UnparsedPublicKey::new(&ED25519, key) + .verify(&signed, signature) + .map_err(|_| UpdateError::InvalidSignature)?; + let index: UpdateIndex = + serde_json::from_slice(raw).map_err(|_| UpdateError::InvalidIndex)?; + validate_index(&index)?; + if index.expires_at <= now_unix { + return Err(UpdateError::Expired); + } + let _guard = self + .commit_lock + .lock() + .unwrap_or_else(|poison| poison.into_inner()); + let state_dir = self.root.join(safe_id(&index.plugin_id)); + if highest_sequence(&state_dir)? != index.sequence { + return Err(UpdateError::Replay); + } + let record = + fs::read(state_dir.join(format!("seq-{}", index.sequence))).map_err(io_error)?; + let digest = Sha256::digest(raw); + let sequence_matches = record.len() >= 8 && record[..8] == index.sequence.to_le_bytes(); + // Older schema-1 state files stored only the sequence. Continue accepting that exact + // high-water mark after signature and expiry validation; new records bind the sequence + // to the exact signed payload bytes. + let digest_matches = + record.len() == 8 || (record.len() == 8 + digest.len() && record[8..] == digest[..]); + if !sequence_matches || !digest_matches { + return Err(UpdateError::Replay); + } + Ok(index) + } + + /// Downloads a release through the same HTTPS, public-address, redirect and timeout checks + /// used for plugin network fetches. Package bytes remain inert until the caller verifies and + /// stages them. The response is bounded by the package archive size policy. + pub async fn download_release( + &self, + client: &FetchClient, + release: &UpdateRelease, + allowed_origin: impl Fn(&str) -> bool + Send + Sync, + ) -> Result, UpdateError> { + validate_release(release)?; + let request = Request::build_package_download(&release.package_url, release.package_size) + .map_err(|_| UpdateError::InvalidUrl)?; + let response = client + .fetch(request, move |origin| allowed_origin(origin)) + .await + .map_err(|error| UpdateError::Fetch(error.to_string()))?; + let bytes = response.body; + if response.status != 200 + || bytes.len() as u64 != release.package_size + || format!("{:x}", Sha256::digest(&bytes)) != release.package_sha256 + { + return Err(UpdateError::InvalidPackage); + } + Ok(bytes) + } +} + +fn decode_signature(value: &str) -> Result, UpdateError> { + if value.len() != 128 + || !value + .bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) + { + return Err(UpdateError::InvalidIndex); + } + (0..64) + .map(|index| { + u8::from_str_radix(&value[index * 2..index * 2 + 2], 16) + .map_err(|_| UpdateError::InvalidIndex) + }) + .collect() +} + +fn validate_index(index: &UpdateIndex) -> Result<(), UpdateError> { + if index.schema != 1 + || !valid_id(&index.plugin_id) + || index.sequence == 0 + || index.expires_at == 0 + || index.releases.is_empty() + || index.releases.len() > 128 + { + return Err(UpdateError::InvalidIndex); + } + for release in &index.releases { + validate_release(release)?; + } + Ok(()) +} + +fn validate_release(release: &UpdateRelease) -> Result<(), UpdateError> { + let url = Url::parse(&release.package_url).map_err(|_| UpdateError::InvalidUrl)?; + if url.scheme() != "https" + || url.host_str().is_none() + || !url.username().is_empty() + || url.password().is_some() + || release.package_size == 0 + || release.package_size > MAX_PACKAGE_BYTES + || release.package_sha256.len() != 64 + || !release + .package_sha256 + .bytes() + .all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase()) + || release.targets.is_empty() + || release + .targets + .iter() + .any(|target| target.is_empty() || target.len() > 128) + || release.bundle_sha256.as_deref().is_some_and(|digest| { + digest.len() != 64 + || !digest + .bytes() + .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)) + }) + || semver::Version::parse(&release.version).is_err() + || semver::VersionReq::parse(&release.api_range).is_err() + { + return Err(UpdateError::InvalidIndex); + } + Ok(()) +} + +fn valid_id(id: &str) -> bool { + !id.is_empty() + && id.len() <= 256 + && id + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b"._:-".contains(&b)) +} +fn safe_id(id: &str) -> String { + format!("{:x}", Sha256::digest(id.as_bytes())) +} +fn highest_sequence(root: &std::path::Path) -> Result { + let mut highest = 0u64; + for entry in fs::read_dir(root).map_err(io_error)? { + let entry = entry.map_err(io_error)?; + let name = entry.file_name(); + let name = name.to_str().ok_or(UpdateError::InvalidIndex)?; + if let Some(value) = name.strip_prefix("seq-") { + highest = highest.max( + value + .parse::() + .map_err(|_| UpdateError::InvalidIndex)?, + ); + } + } + Ok(highest) +} +fn sync_dir(path: &std::path::Path) -> io::Result<()> { + #[cfg(unix)] + File::open(path)?.sync_all()?; + #[cfg(not(unix))] + let _ = path; + Ok(()) +} +#[cfg(unix)] +fn restrict_owner_dir(path: &std::path::Path) -> io::Result<()> { + use std::os::unix::fs::PermissionsExt; + fs::set_permissions(path, fs::Permissions::from_mode(0o700)) +} +#[cfg(not(unix))] +fn restrict_owner_dir(_: &std::path::Path) -> io::Result<()> { + Ok(()) +} +fn io_error(error: io::Error) -> UpdateError { + UpdateError::Io(error.to_string()) +} + +#[cfg(test)] +mod tests { + use super::*; + use ring::signature::{Ed25519KeyPair, KeyPair}; + use tempfile::tempdir; + + fn signed(key: &Ed25519KeyPair, sequence: u64, expires_at: u64) -> (Vec, Vec) { + let index = UpdateIndex { + schema: 1, + plugin_id: "com.example.plugin".into(), + sequence, + expires_at, + releases: vec![UpdateRelease { + version: "1.2.3".into(), + targets: vec!["linux-x64".into()], + api_range: ">=1.0.0, <2.0.0".into(), + package_url: "https://updates.example/plugin.zip".into(), + package_size: 10, + package_sha256: "a".repeat(64), + bundle_sha256: None, + }], + }; + let raw = serde_json::to_vec(&index).unwrap(); + let mut message = INDEX_SIGNATURE_DOMAIN.to_vec(); + message.extend_from_slice(&raw); + (raw, key.sign(&message).as_ref().to_vec()) + } + fn key() -> Ed25519KeyPair { + Ed25519KeyPair::from_seed_unchecked(&[7u8; 32]).unwrap() + } + + #[test] + fn rejects_invalid_signature_expiry_and_replay_without_advancing_state() { + let dir = tempdir().unwrap(); + let verifier = UpdateIndexVerifier::open(dir.path()).unwrap(); + let key = key(); + let (raw, signature) = signed(&key, 1, 200); + assert_eq!( + verifier.verify(&raw, &[0; 64], key.public_key().as_ref(), 100), + Err(UpdateError::InvalidSignature) + ); + assert_eq!( + verifier.verify(&raw, &signature, key.public_key().as_ref(), 200), + Err(UpdateError::Expired) + ); + assert_eq!( + verifier + .verify(&raw, &signature, key.public_key().as_ref(), 100) + .unwrap() + .sequence, + 1 + ); + assert_eq!( + verifier.verify(&raw, &signature, key.public_key().as_ref(), 100), + Err(UpdateError::Replay) + ); + let (next, sig) = signed(&key, 2, 300); + assert_eq!( + verifier + .verify(&next, &sig, key.public_key().as_ref(), 100) + .unwrap() + .sequence, + 2 + ); + let reopened = UpdateIndexVerifier::open(dir.path()).unwrap(); + assert_eq!( + reopened.verify(&next, &sig, key.public_key().as_ref(), 100), + Err(UpdateError::Replay), + "accepted sequences survive verifier restart" + ); + } + + #[test] + fn rejects_non_https_and_oversized_release_metadata() { + let mut release = UpdateRelease { + version: "1.0.0".into(), + targets: vec!["linux-x64".into()], + api_range: "^1".into(), + package_url: "http://example.com/a".into(), + package_size: 10, + package_sha256: "a".repeat(64), + bundle_sha256: None, + }; + assert_eq!(validate_release(&release), Err(UpdateError::InvalidIndex)); + release.package_url = "https://example.com/a".into(); + release.package_size = MAX_PACKAGE_BYTES + 1; + assert_eq!(validate_release(&release), Err(UpdateError::InvalidIndex)); + } + + #[test] + fn a_release_without_a_bundle_hash_stays_a_standalone_package_release() { + let mut release = UpdateRelease { + version: "1.0.0".into(), + targets: vec!["linux-x64".into()], + api_range: "^1".into(), + package_url: "https://example.com/a".into(), + package_size: 10, + package_sha256: "a".repeat(64), + bundle_sha256: None, + }; + assert_eq!(validate_release(&release), Ok(())); + release.bundle_sha256 = Some("b".repeat(64)); + assert_eq!(validate_release(&release), Ok(())); + for invalid in [ + "b".repeat(63), + "B".repeat(64), + "g".repeat(64), + String::new(), + ] { + release.bundle_sha256 = Some(invalid.clone()); + assert_eq!( + validate_release(&release), + Err(UpdateError::InvalidIndex), + "bundle hash {invalid:?} is not a lowercase SHA-256" + ); + } + } + + #[test] + fn exact_current_feed_can_be_reread_but_same_sequence_changes_are_rejected() { + let dir = tempdir().unwrap(); + let verifier = UpdateIndexVerifier::open(dir.path()).unwrap(); + let key = key(); + let (raw, signature) = signed(&key, 1, 500); + verifier + .verify(&raw, &signature, key.public_key().as_ref(), 100) + .unwrap(); + assert_eq!( + verifier + .verify_same_sequence(&raw, &signature, key.public_key().as_ref(), 100) + .unwrap() + .sequence, + 1 + ); + let (different, different_signature) = signed(&key, 1, 600); + assert_eq!( + verifier.verify_same_sequence( + &different, + &different_signature, + key.public_key().as_ref(), + 100 + ), + Err(UpdateError::Replay) + ); + } +} diff --git a/crates/platform/src/ports/extractor.rs b/crates/platform/src/ports/extractor.rs index 6a5b1ab24..cf3d737fd 100644 --- a/crates/platform/src/ports/extractor.rs +++ b/crates/platform/src/ports/extractor.rs @@ -30,7 +30,7 @@ use std::process::{Child, Command, ExitStatus, Stdio}; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::{Arc, Mutex}; use std::thread::JoinHandle; -use std::time::Duration; +use std::time::{Duration, Instant}; use gamenode_core::ports::Extractor; use gamenode_core::tools::ToolError; @@ -44,7 +44,13 @@ use crate::download::{ /// Bytes of combined stdout and stderr kept for the failure details (design D8). pub const MAX_CAPTURED_OUTPUT_BYTES: usize = 64 * 1024; -/// How often a running tool checks for cancellation. +/// How long one extraction run may take before its process tree is stopped (design D8). +/// +/// Six hours leaves room for a 30 GB base package on a slow disk while still freeing the single +/// install worker from a tool that hung. Cancellation stays immediate. +pub const DEFAULT_EXTRACTION_TIMEOUT: Duration = Duration::from_secs(6 * 60 * 60); + +/// How often a running tool checks for cancellation and its timeout. const CANCEL_POLL_INTERVAL: Duration = Duration::from_millis(25); /// The longest the runner waits for the output pipes to close after the tool exited. @@ -213,6 +219,8 @@ pub enum ExtractorError { Exit { code: i32 }, #[error("the extraction tool was terminated before it finished")] Terminated, + #[error("the extraction tool did not finish within {seconds} seconds")] + TimedOut { seconds: u64 }, #[error( "the package is an encrypted retail package; GameNode ships no keys and cannot extract it" )] @@ -401,11 +409,24 @@ impl ExtractorRunner { pub fn run_extractor( request: ExtractorRunRequest<'_>, ) -> Result { - run_extractor_inner(&request) + run_extractor_with_timeout(request, DEFAULT_EXTRACTION_TIMEOUT) +} + +/// Runs a prepared tool once with an explicit timeout. +/// +/// [`run_extractor`] uses [`DEFAULT_EXTRACTION_TIMEOUT`]; this entry point exists so a caller (and +/// the tests) can bound a run more tightly. A timeout kills the whole process tree and reports +/// [`ExtractorError::TimedOut`], exactly like a cancellation reports [`ExtractorError::Cancelled`]. +pub fn run_extractor_with_timeout( + request: ExtractorRunRequest<'_>, + timeout: Duration, +) -> Result { + run_extractor_inner(&request, timeout) } fn run_extractor_inner( request: &ExtractorRunRequest<'_>, + timeout: Duration, ) -> Result { let package = canonical_file(request.package, "package").map_err(ExtractorFailure::from_error)?; @@ -475,6 +496,7 @@ fn run_extractor_inner( &arguments, &working, request.cancel, + timeout, ) { Ok(raw) => raw, Err((error, output)) => { @@ -498,6 +520,16 @@ fn run_extractor_inner( }); } + if raw.timed_out { + return Err(ExtractorFailure { + error: ExtractorError::TimedOut { + seconds: timeout.as_secs(), + }, + output: raw.output, + created_paths, + }); + } + if looks_like_encrypted_package(&raw.output) { return Err(ExtractorFailure { error: ExtractorError::EncryptedPackage, @@ -769,6 +801,7 @@ fn is_link_or_reparse(metadata: &fs::Metadata) -> bool { struct RawRun { status: ExitStatus, cancelled: bool, + timed_out: bool, output: String, } @@ -897,6 +930,7 @@ fn spawn_and_wait( arguments: &[OsString], working_directory: &Path, cancel: &CancelFlag, + timeout: Duration, ) -> Result { let mut command = Command::new(executable); command @@ -914,12 +948,18 @@ fn spawn_and_wait( let capture = Arc::new(OutputCapture::new()); let (readers, readers_done) = read_pipes(&mut child, &capture); + let started = Instant::now(); let mut cancelled = false; + let mut timed_out = false; let status = loop { - if cancel.is_cancelled() { + if !cancelled && cancel.is_cancelled() { cancelled = true; tree.kill(); } + if !cancelled && !timed_out && started.elapsed() >= timeout { + timed_out = true; + tree.kill(); + } match child.try_wait() { Ok(Some(status)) => break status, Ok(None) => {} @@ -939,6 +979,7 @@ fn spawn_and_wait( Ok(RawRun { status, cancelled, + timed_out, output: capture.text(), }) } @@ -1760,6 +1801,20 @@ exit 3"#; assert!(!output.exists()); } + #[test] + fn encryption_errors_from_the_pinned_tool_are_recognised() { + for output in [ + "failed to open or parse PKG file: cannot decrypt EKPFS", + "Error: no key for index 0", + "error: this is an encrypted retail package (EKPFS)", + ] { + assert!(looks_like_encrypted_package(output), "{output}"); + } + assert!(!looks_like_encrypted_package( + "PFS extraction complete (42 files)." + )); + } + #[cfg(unix)] #[test] fn an_encrypted_package_gets_a_clear_error() { @@ -1880,6 +1935,58 @@ while :; do sleep 0.05; done"#; assert_eq!(later, after_cancel, "the stub's child kept running"); } + #[cfg(unix)] + #[test] + fn a_timeout_stops_a_hung_tool_and_its_children() { + let temp = tempfile::tempdir().unwrap(); + let script = r#"( + while :; do + echo tick >> "$2/progress.txt" + sleep 0.05 + done +) & +while :; do sleep 0.05; done"#; + let package = temp.path().join("base.pkg"); + fs::write(&package, b"base").unwrap(); + let staging = temp.path().join("staging"); + fs::create_dir_all(&staging).unwrap(); + let output = temp.path().join("out"); + + let definition = extractor(shell_args(script)); + let started = Instant::now(); + let failure = run_extractor_with_timeout( + ExtractorRunRequest { + extractor: &definition, + tool: &shell_tool(), + package: &package, + update: None, + output: &output, + working_directory: &staging, + cancel: &CancelFlag::new(), + validate_output: &accept_all(), + }, + Duration::from_millis(500), + ) + .expect_err("timed out"); + + assert!(matches!( + failure.error, + ExtractorError::TimedOut { seconds: 0 } + )); + assert!( + started.elapsed() < Duration::from_secs(5), + "the timeout did not stop the stub" + ); + assert!(failure.reason().contains("did not finish within")); + + // The background child of the stub must be dead after the timeout killed the tree. + let progress = output.join("progress.txt"); + let after_timeout = fs::metadata(&progress).unwrap().len(); + std::thread::sleep(Duration::from_millis(400)); + let later = fs::metadata(&progress).unwrap().len(); + assert_eq!(later, after_timeout, "the stub's child kept running"); + } + #[cfg(unix)] #[test] fn a_missing_tool_executable_fails_before_spawning() { diff --git a/crates/platform/src/ports/job_runner.rs b/crates/platform/src/ports/job_runner.rs index b5624b019..021d01dcd 100644 --- a/crates/platform/src/ports/job_runner.rs +++ b/crates/platform/src/ports/job_runner.rs @@ -438,7 +438,11 @@ struct QueuedJob { cancel: Arc, } +pub type InstallAuthority = Arc bool + Send + Sync>; + +#[derive(Default)] struct Shared { + authorities: Mutex>, queue: Mutex>, /// Every queued or running job. Removed once the job is terminal. cancels: Mutex>>, @@ -473,9 +477,33 @@ pub struct JobRunner { } impl JobRunner { + pub fn enqueue_checked( + &self, + request: InstallJobRequest, + check: InstallAuthority, + ) -> Result<(), JobError> { + if !check() { + return Err(JobError::Closed); + } + let id = request.job_id.clone(); + { + let mut authorities = lock(&self.shared.authorities); + if authorities.contains_key(&id) { + return Err(JobError::DuplicateJob { job_id: id }); + } + authorities.insert(id.clone(), check); + } + let result = self.enqueue(request); + if result.is_err() { + lock(&self.shared.authorities).remove(&id); + } + result + } + /// Creates the single install worker thread. The callback runs on that thread. pub fn start(config: JobRunnerConfig) -> Self { let shared = Arc::new(Shared { + authorities: Mutex::new(HashMap::new()), queue: Mutex::new(VecDeque::new()), cancels: Mutex::new(HashMap::new()), awaiting: Mutex::new(HashSet::new()), @@ -756,6 +784,9 @@ fn execute(config: &JobRunnerConfig, shared: &Shared, job: QueuedJob) { let job_id = context.job.id.clone(); *lock(&shared.active) = None; lock(&shared.cancels).remove(&job_id); + if !awaiting { + lock(&shared.authorities).remove(&job_id); + } if awaiting { if cancel.load(Ordering::SeqCst) { // A cancel that arrived as the job entered the waiting phase still removes its files. @@ -834,6 +865,7 @@ impl<'a> JobContext<'a> { /// Saves a new phase and reports it. Illegal transitions are prevented by the core state /// machine, so one is a runner bug, not a user-facing failure. fn set_phase(&mut self, phase: PortJobPhase) -> Result<(), InstallError> { + self.check_cancelled()?; self.job.phase = self .job .phase @@ -841,6 +873,11 @@ impl<'a> JobContext<'a> { .map_err(|error| InstallError::Internal(error.to_string()))?; self.job.updated_at = self.now(); self.config.store.save_job(&self.job)?; + // Register the wait before the phase event, so a user pick that follows the event cannot + // race the worker's own bookkeeping. + if self.job.phase == PortJobPhase::AwaitingExecutable { + lock(&self.shared.awaiting).insert(self.job.id.clone()); + } self.emit_phase(); Ok(()) } @@ -856,7 +893,7 @@ impl<'a> JobContext<'a> { // The row was stored by `enqueue`; report the queued phase from the worker so the app's // callback only ever runs on one thread. self.emit_phase(); - if self.shared.quitting.load(Ordering::SeqCst) || self.cancel.load(Ordering::SeqCst) { + if self.shared.quitting.load(Ordering::SeqCst) || self.check_cancelled().is_err() { self.finish_cancelled(); return; } @@ -1354,7 +1391,7 @@ impl<'a> JobContext<'a> { if self.shared.quitting.load(Ordering::SeqCst) { return; } - if self.cancel.load(Ordering::SeqCst) { + if self.check_cancelled().is_err() { self.finish_cancelled(); return; } @@ -1365,7 +1402,7 @@ impl<'a> JobContext<'a> { return; } }; - if self.cancel.load(Ordering::SeqCst) { + if self.check_cancelled().is_err() { self.finish_cancelled(); return; } @@ -1461,7 +1498,8 @@ impl<'a> JobContext<'a> { } fn check_cancelled(&self) -> Result<(), InstallError> { - if self.cancel.load(Ordering::SeqCst) { + let authority = lock(&self.shared.authorities).get(&self.job.id).cloned(); + if self.cancel.load(Ordering::SeqCst) || authority.is_some_and(|check| !check()) { Err(InstallError::Cancelled) } else { Ok(()) @@ -1469,6 +1507,10 @@ impl<'a> JobContext<'a> { } fn finish_completed(&mut self, registration: Registration, installation: PortInstallation) { + if self.check_cancelled().is_err() { + self.finish_cancelled(); + return; + } let now = self.now(); let mut completed = self.job.clone(); let phase = match completed.phase.transition(PortJobPhase::Completed) { @@ -1615,6 +1657,7 @@ fn cleanup_job(store: &dyn PortStore, job: &PortJobRow) -> Option { /// Ends a job that waits for an executable pick: removes its files and marks it `Cancelled`. fn cancel_awaiting(config: &JobRunnerConfig, shared: &Shared, job_id: &str) { + lock(&shared.authorities).remove(job_id); let job = match config.store.job(job_id) { Ok(Some(job)) => job, Ok(None) => { @@ -1731,6 +1774,9 @@ fn complete_awaiting( let awaiting = context.job.phase == PortJobPhase::AwaitingExecutable; *lock(&shared.active) = None; lock(&shared.cancels).remove(&job_id); + if !awaiting { + lock(&shared.authorities).remove(&job_id); + } if awaiting { lock(&shared.awaiting).insert(job_id); } diff --git a/crates/platform/src/ports/job_runner/tests.rs b/crates/platform/src/ports/job_runner/tests.rs index 7e29cb37f..311041ade 100644 --- a/crates/platform/src/ports/job_runner/tests.rs +++ b/crates/platform/src/ports/job_runner/tests.rs @@ -1876,3 +1876,78 @@ fn an_awaiting_job_survives_a_restart_and_is_completed_from_the_stored_plan() { assert_eq!(fixture.local.registrations().unwrap().len(), 1); assert_eq!(fixture.ports.installations().unwrap().len(), 1); } + +#[test] +fn scoped_authority_loss_during_identity_read_prevents_registration_and_cleans_files() { + let fixture = Fixture::new(); + let bytes = zip_bytes(&[("Port.exe", b"fixture launcher")]); + let (plan, setup, matching) = plan_for( + entry("fixture", "Fixture", "Port.exe"), + &bytes, + "fixture.zip", + &fixture.parent, + "scoped-port", + vec![], + ); + let folder = PathBuf::from(&plan.target); + let (identity, reached, release) = GatedIdentity::new(); + let (runner, events) = fixture.start(FakeFetcher::new(bytes), Arc::new(identity)); + let allowed = Arc::new(AtomicBool::new(true)); + let flag = allowed.clone(); + runner + .enqueue_checked( + request("scoped-port", plan, setup, matching), + Arc::new(move || flag.load(Ordering::SeqCst)), + ) + .unwrap(); + reached.recv_timeout(Duration::from_secs(15)).unwrap(); + allowed.store(false, Ordering::SeqCst); + release.send(()).unwrap(); + let (job, completion) = wait_for_finished(&events); + runner.shutdown(); + assert_eq!(job.phase, PortJobPhase::Cancelled); + assert!(completion.is_none()); + assert!(fixture.local.registrations().unwrap().is_empty()); + assert!(fixture.ports.installations().unwrap().is_empty()); + assert!(!folder.exists()); +} + +#[test] +fn scoped_authority_survives_the_executable_wait_and_blocks_a_revoked_followup() { + let fixture = Fixture::new(); + let bytes = zip_bytes(&[("Second.exe", b"second")]); + let (plan, setup, matching) = plan_for( + entry("fixture", "Fixture", "Missing.exe"), + &bytes, + "fixture.zip", + &fixture.parent, + "scoped-wait", + vec![], + ); + let folder = PathBuf::from(&plan.target); + let (runner, events) = fixture.start(FakeFetcher::new(bytes), Arc::new(PathIdentity)); + let allowed = Arc::new(AtomicBool::new(true)); + let flag = allowed.clone(); + runner + .enqueue_checked( + request("scoped-wait", plan, setup, matching), + Arc::new(move || flag.load(Ordering::SeqCst)), + ) + .unwrap(); + wait_for_phase(&events, "scoped-wait", PortJobPhase::AwaitingExecutable); + let deadline = std::time::Instant::now() + Duration::from_secs(5); + while !lock(&runner.shared.awaiting).contains("scoped-wait") { + assert!(std::time::Instant::now() < deadline); + std::thread::yield_now(); + } + allowed.store(false, Ordering::SeqCst); + runner + .complete_with_executable("scoped-wait", "Second.exe") + .unwrap(); + let (job, completion) = wait_for_finished(&events); + runner.shutdown(); + assert_eq!(job.phase, PortJobPhase::Cancelled); + assert!(completion.is_none()); + assert!(!folder.exists()); + assert!(fixture.local.registrations().unwrap().is_empty()); +} diff --git a/crates/platform/src/ports/mod.rs b/crates/platform/src/ports/mod.rs index b890f3945..f36524135 100644 --- a/crates/platform/src/ports/mod.rs +++ b/crates/platform/src/ports/mod.rs @@ -30,9 +30,10 @@ pub use quiver::{ }; pub use extractor::{ - CancelFlag, ExtractorError, ExtractorFailure, ExtractorRunOutcome, ExtractorRunRequest, - ExtractorRunner, InstalledTool, MAX_CAPTURED_OUTPUT_BYTES, OutputFolderValidator, - SuppliedFolderValidator, run_extractor, supplied_folder_validator, + CancelFlag, DEFAULT_EXTRACTION_TIMEOUT, ExtractorError, ExtractorFailure, ExtractorRunOutcome, + ExtractorRunRequest, ExtractorRunner, InstalledTool, MAX_CAPTURED_OUTPUT_BYTES, + OutputFolderValidator, SuppliedFolderValidator, run_extractor, run_extractor_with_timeout, + supplied_folder_validator, }; pub use job_runner::{ ExecutableIdentity, InstallCompletion, InstallJobRequest, JobError, JobEvent, JobProgress, diff --git a/crates/platform/src/processes.rs b/crates/platform/src/processes.rs index cd7766cfd..3100ab98d 100644 --- a/crates/platform/src/processes.rs +++ b/crates/platform/src/processes.rs @@ -1,6 +1,7 @@ -//! Platform process inspection. Linux tracking is intentionally unavailable in the MVP. +//! Platform process inspection. Windows keeps OS handles; Linux reads `/proc`; other targets +//! report the port as unavailable. -#[cfg(not(windows))] +#[cfg(not(any(windows, target_os = "linux")))] mod unsupported { use gamenode_core::ports::{ProcessError, ProcessInfo, Processes}; #[derive(Default)] @@ -41,9 +42,14 @@ mod unsupported { } } } -#[cfg(not(windows))] +#[cfg(not(any(windows, target_os = "linux")))] pub use unsupported::HostProcesses; +#[cfg(target_os = "linux")] +mod linux; +#[cfg(target_os = "linux")] +pub use linux::HostProcesses; + #[cfg(windows)] mod windows; #[cfg(windows)] diff --git a/crates/platform/src/processes/linux.rs b/crates/platform/src/processes/linux.rs new file mode 100644 index 000000000..e8ca25f56 --- /dev/null +++ b/crates/platform/src/processes/linux.rs @@ -0,0 +1,237 @@ +//! `/proc` process inspection for external runtime-use checks and playtime tracking. +//! +//! The identity of a process is `(pid, start time)`: Linux reuses PIDs, so a start-time change +//! means a different process. `created_at` is derived from `/proc/stat` `btime` and the `starttime` +//! field of `/proc//stat`, assuming the common Linux userspace clock of 100 ticks per second. +//! Unreadable processes are skipped, exactly as the Windows adapter skips inaccessible handles. +use std::collections::BTreeMap; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use gamenode_core::ports::{ProcessError, ProcessIdentity, ProcessInfo, Processes}; + +/// Linux `USER_HZ`; every architecture GameNode ships for uses 100 except alpha. +const TICKS_PER_SECOND: u64 = 100; + +#[derive(Default)] +pub struct HostProcesses; + +impl HostProcesses { + pub fn new() -> Self { + Self + } +} + +#[derive(Clone, Copy)] +struct Stat { + parent: u32, + start_ticks: u64, +} + +fn boot_time() -> Option { + let text = std::fs::read_to_string("/proc/stat").ok()?; + let seconds: u64 = text + .lines() + .find_map(|line| line.strip_prefix("btime "))? + .trim() + .parse() + .ok()?; + Some(UNIX_EPOCH + Duration::from_secs(seconds)) +} + +fn stat(pid: u32) -> Option { + let text = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?; + // `comm` may contain spaces and parentheses; fields resume after its final ')'. + let mut fields = text.rsplit_once(')')?.1.split_ascii_whitespace(); + let _state = fields.next()?; + let parent = fields.next()?.parse().ok()?; + let start_ticks = fields.nth(17)?.parse().ok()?; + Some(Stat { + parent, + start_ticks, + }) +} + +fn executable(pid: u32) -> Option { + let path = std::fs::read_link(format!("/proc/{pid}/exe")).ok()?; + let path = path.to_string_lossy(); + // A replaced or unlinked binary keeps the approved pathname plus this kernel suffix; keep + // the process visible so a backup is not allowed to race an emulator running the old image. + Some(path.strip_suffix(" (deleted)").unwrap_or(&path).to_owned()) +} + +fn inspect(pid: u32, boot: SystemTime) -> Option<(ProcessInfo, u32)> { + let stat = stat(pid)?; + let exe_path = executable(pid)?; + Some(( + ProcessInfo { + pid, + created_at: boot + + Duration::from_millis(stat.start_ticks.saturating_mul(1000 / TICKS_PER_SECOND)), + exe_path, + parent: None, + }, + stat.parent, + )) +} + +impl Processes for HostProcesses { + fn list(&self) -> Result, ProcessError> { + let boot = boot_time().ok_or(ProcessError::Failed)?; + let entries = std::fs::read_dir("/proc").map_err(|_| ProcessError::Failed)?; + let mut identities = BTreeMap::new(); + let mut rows: Vec<(ProcessInfo, u32)> = Vec::new(); + for entry in entries.flatten() { + let Some(pid) = entry + .file_name() + .to_str() + .and_then(|name| name.parse::().ok()) + else { + continue; + }; + let Some((process, parent)) = inspect(pid, boot) else { + continue; + }; + identities.insert( + pid, + ProcessIdentity { + pid, + created_at: process.created_at, + }, + ); + rows.push((process, parent)); + } + Ok(rows + .into_iter() + .map(|(mut process, parent)| { + process.parent = identities + .get(&parent) + .filter(|identity| identity.created_at <= process.created_at) + .cloned(); + process + }) + .collect()) + } + + fn watch( + &self, + process: &ProcessInfo, + on_exit: Box, + ) -> Result<(), ProcessError> { + let boot = boot_time().ok_or(ProcessError::Failed)?; + let (current, _) = inspect(process.pid, boot).ok_or(ProcessError::Failed)?; + if current.created_at != process.created_at { + return Err(ProcessError::Failed); + } + let pid = rustix::process::Pid::from_raw(process.pid as i32).ok_or(ProcessError::Failed)?; + let watched_pid = process.pid; + let watched_created_at = process.created_at; + let pidfd = rustix::process::pidfd_open(pid, rustix::process::PidfdFlags::empty()).ok(); + std::thread::Builder::new() + .name("gamenode-process-watch".into()) + .spawn(move || { + let waited = pidfd.is_some_and(|fd| { + // A pidfd is readable once any process, child or not, exits. Polling it never + // reaps a child that the application owns. + let mut poll_fds = [rustix::event::PollFd::new( + &fd, + rustix::event::PollFlags::IN, + )]; + loop { + match rustix::event::poll(&mut poll_fds, None) { + Ok(_) => return true, + Err(rustix::io::Errno::INTR) => continue, + Err(_) => return false, + } + } + }); + if !waited { + // Kernels without pidfds, or a vanished descriptor: poll the identity. + while inspect(watched_pid, boot) + .is_some_and(|(seen, _)| seen.created_at == watched_created_at) + { + std::thread::sleep(Duration::from_secs(1)); + } + } + on_exit(SystemTime::now()); + }) + .map_err(|_| ProcessError::Failed)?; + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::process::{Command, Stdio}; + + fn canonical(path: &str) -> std::path::PathBuf { + std::fs::canonicalize(path).unwrap() + } + + #[test] + fn a_child_is_listed_with_its_real_executable_and_parent() { + let mut child = Command::new("/bin/sleep") + .arg("5") + .stdin(Stdio::null()) + .spawn() + .unwrap(); + let adapter = HostProcesses::new(); + let process = adapter + .list() + .unwrap() + .into_iter() + .find(|process| process.pid == child.id()) + .expect("the child is listed"); + assert_eq!( + std::path::Path::new(&process.exe_path), + canonical("/bin/sleep") + ); + let parent = process + .parent + .as_ref() + .expect("the observing test process is its parent"); + assert_eq!(parent.pid, std::process::id()); + assert!(parent.created_at <= process.created_at); + + let (tx, rx) = std::sync::mpsc::channel(); + adapter + .watch( + &process, + Box::new(move |at| { + tx.send(at).unwrap(); + }), + ) + .unwrap(); + child.kill().unwrap(); + child.wait().unwrap(); + let at = rx.recv_timeout(Duration::from_secs(10)).unwrap(); + assert!(at >= process.created_at); + assert!(at <= SystemTime::now()); + } + + #[test] + fn a_reused_pid_identity_is_refused() { + let mut child = Command::new("/bin/sleep") + .arg("5") + .stdin(Stdio::null()) + .spawn() + .unwrap(); + let adapter = HostProcesses::new(); + let current = adapter + .list() + .unwrap() + .into_iter() + .find(|process| process.pid == child.id()) + .unwrap(); + let stale = ProcessInfo { + created_at: current.created_at - Duration::from_secs(1), + ..current + }; + assert_eq!( + adapter.watch(&stale, Box::new(|_| panic!("must not report an exit"))), + Err(ProcessError::Failed) + ); + child.kill().unwrap(); + child.wait().unwrap(); + } +} diff --git a/crates/platform/src/sealed.rs b/crates/platform/src/sealed.rs new file mode 100644 index 000000000..aa877a14d --- /dev/null +++ b/crates/platform/src/sealed.rs @@ -0,0 +1,168 @@ +//! Opaque, tamper-proof tokens the host hands to plugins in place of its own identifiers. +//! +//! A token seals a small payload with a key that never leaves the process, so a plugin cannot +//! read what it holds, change it or build one. Each token is bound to a purpose and to a +//! context string (a plugin session), and only opens with the same ones: a token issued to +//! one session is meaningless to another, and a cursor is not a handle. Tokens are random per +//! issue, so two for the same payload differ. + +use ring::aead::{Aad, CHACHA20_POLY1305, LessSafeKey, NONCE_LEN, Nonce, UnboundKey}; +use ring::rand::{SecureRandom, SystemRandom}; + +/// Issues and opens sealed tokens with one random key. +pub struct Sealer { + key: LessSafeKey, + random: SystemRandom, +} + +impl Default for Sealer { + fn default() -> Self { + Self::new() + } +} + +impl Sealer { + /// A sealer with a fresh random key. Tokens do not survive the process. + pub fn new() -> Self { + let random = SystemRandom::new(); + let mut key = [0u8; 32]; + random + .fill(&mut key) + .expect("the system random source is available"); + let key = LessSafeKey::new( + UnboundKey::new(&CHACHA20_POLY1305, &key).expect("a 32-byte ChaCha20-Poly1305 key"), + ); + Self { key, random } + } + + fn aad(purpose: u8, binding: &str) -> Vec { + let mut aad = Vec::with_capacity(binding.len() + 1); + aad.push(purpose); + aad.extend_from_slice(binding.as_bytes()); + aad + } + + /// Seals `payload` for `purpose` and `binding`, as lowercase hex text. + pub fn seal(&self, purpose: u8, binding: &str, payload: &[u8]) -> String { + let mut nonce = [0u8; NONCE_LEN]; + self.random + .fill(&mut nonce) + .expect("the system random source is available"); + let mut buffer = payload.to_vec(); + self.key + .seal_in_place_append_tag( + Nonce::assume_unique_for_key(nonce), + Aad::from(Self::aad(purpose, binding)), + &mut buffer, + ) + .expect("sealing in memory cannot fail"); + let mut token = Vec::with_capacity(NONCE_LEN + buffer.len()); + token.extend_from_slice(&nonce); + token.extend_from_slice(&buffer); + hex(&token) + } + + /// The payload of `token` if it was sealed by this sealer for the same purpose and binding. + pub fn open(&self, purpose: u8, binding: &str, token: &str) -> Option> { + let bytes = unhex(token)?; + if bytes.len() < NONCE_LEN + CHACHA20_POLY1305.tag_len() { + return None; + } + let (nonce, sealed) = bytes.split_at(NONCE_LEN); + let nonce = Nonce::try_assume_unique_for_key(nonce).ok()?; + let mut buffer = sealed.to_vec(); + let opened = self + .key + .open_in_place(nonce, Aad::from(Self::aad(purpose, binding)), &mut buffer) + .ok()?; + Some(opened.to_vec()) + } +} + +fn hex(bytes: &[u8]) -> String { + const DIGITS: &[u8; 16] = b"0123456789abcdef"; + let mut text = String::with_capacity(bytes.len() * 2); + for byte in bytes { + text.push(DIGITS[(byte >> 4) as usize] as char); + text.push(DIGITS[(byte & 0x0f) as usize] as char); + } + text +} + +fn unhex(text: &str) -> Option> { + let bytes = text.as_bytes(); + if !bytes.len().is_multiple_of(2) { + return None; + } + let digit = |b: u8| match b { + b'0'..=b'9' => Some(b - b'0'), + b'a'..=b'f' => Some(b - b'a' + 10), + _ => None, + }; + bytes + .chunks(2) + .map(|pair| Some(digit(pair[0])? << 4 | digit(pair[1])?)) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_token_opens_only_for_its_purpose_and_binding() { + let sealer = Sealer::new(); + let token = sealer.seal(1, "session-a", b"payload"); + assert_eq!( + sealer.open(1, "session-a", &token).as_deref(), + Some(&b"payload"[..]) + ); + assert_eq!(sealer.open(2, "session-a", &token), None, "another purpose"); + assert_eq!(sealer.open(1, "session-b", &token), None, "another session"); + assert_eq!( + Sealer::new().open(1, "session-a", &token), + None, + "another key" + ); + } + + #[test] + fn tokens_are_random_and_do_not_show_their_payload() { + let sealer = Sealer::new(); + let (a, b) = ( + sealer.seal(1, "s", b"secret/path"), + sealer.seal(1, "s", b"secret/path"), + ); + assert_ne!(a, b); + assert!( + !a.contains("736563726574"), + "the payload is not in the token" + ); + assert!(a.bytes().all(|byte| byte.is_ascii_hexdigit())); + } + + #[test] + fn damaged_or_forged_tokens_open_nothing() { + let sealer = Sealer::new(); + let token = sealer.seal(1, "s", b"payload"); + for bad in [ + "".to_owned(), + "zz".to_owned(), + "abc".to_owned(), + token[..token.len() - 2].to_owned(), + format!("{token}00"), + token.to_uppercase(), + ] { + assert_eq!(sealer.open(1, "s", &bad), None, "{bad}"); + } + // Flipping any single hex digit breaks authentication. + for index in (0..token.len()).step_by(7) { + let mut bytes = token.clone().into_bytes(); + bytes[index] = if bytes[index] == b'0' { b'1' } else { b'0' }; + assert_eq!( + sealer.open(1, "s", &String::from_utf8(bytes).unwrap()), + None + ); + } + } +} diff --git a/crates/platform/src/tools/installer.rs b/crates/platform/src/tools/installer.rs index fd0532367..d7e1d1a16 100644 --- a/crates/platform/src/tools/installer.rs +++ b/crates/platform/src/tools/installer.rs @@ -256,6 +256,28 @@ impl ToolInstallerHost for PlatformToolInstaller { request: &InstallRequest, install_dir: &str, ) -> Result { + self.install_or_update_checked( + store, + catalog, + descriptor, + release, + request, + install_dir, + &|| Ok(()), + ) + } + + fn install_or_update_checked( + &self, + store: &dyn ToolStore, + catalog: &dyn ToolCatalogApi, + descriptor: &ToolDescriptor, + release: &ToolRelease, + request: &InstallRequest, + install_dir: &str, + check: &dyn Fn() -> Result<(), ToolError>, + ) -> Result { + check()?; // 1. Validate install_dir exists and canonicalize let install_path = Path::new(install_dir); let canonical_install_dir = inspect::strip_verbatim_prefix( @@ -299,6 +321,7 @@ impl ToolInstallerHost for PlatformToolInstaller { PathBuf::from(cached.path) }; + check()?; // 6. Extract into temporary staging directory let staging_dir = TempDirGuard::new("staging")?; let entries = match catalog::extract_archive_to_dir(&archive_path, staging_dir.path()) { @@ -358,6 +381,8 @@ impl ToolInstallerHost for PlatformToolInstaller { &installed_ini_patches, )?; + check()?; + self.ensure_game_stopped(&canonical_install_dir)?; // 10. Record transient state let now = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) @@ -395,6 +420,7 @@ impl ToolInstallerHost for PlatformToolInstaller { let mut journal = InstallRollbackJournal::new(rollback_temp.path().to_path_buf()); let deploy_result: Result, ToolError> = (|| { + check()?; std::fs::create_dir_all(&tool_backup_dir).map_err(|e| ToolError::Io(e.to_string()))?; // A. If updating: handle obsolete files from prior_tool_files @@ -405,6 +431,7 @@ impl ToolInstallerHost for PlatformToolInstaller { .collect(); for prior_file in &prior_tool_files { + check()?; if !new_destinations.contains(&prior_file.relative_path) { // Check if overridden by a higher tool layer let overriding_tool = all_installed_files.iter().find(|other| { @@ -470,6 +497,7 @@ impl ToolInstallerHost for PlatformToolInstaller { let mut new_records = Vec::new(); for file in &plan.files { + check()?; let dest_full = canonical_install_dir.join(&file.destination_path); for comp in Path::new(&file.destination_path).components() { if let std::path::Component::ParentDir = comp { @@ -704,6 +732,7 @@ impl ToolInstallerHost for PlatformToolInstaller { } } + check()?; // D. Save updated file records store.delete_files(&request.entry_key, &descriptor.id)?; store.save_files(&new_records)?; @@ -738,6 +767,18 @@ impl ToolInstallerHost for PlatformToolInstaller { tool_id: &str, install_dir: &str, ) -> Result<(), ToolError> { + self.uninstall_checked(store, entry_key, tool_id, install_dir, &|| Ok(())) + } + + fn uninstall_checked( + &self, + store: &dyn ToolStore, + entry_key: &str, + tool_id: &str, + install_dir: &str, + check: &dyn Fn() -> Result<(), ToolError>, + ) -> Result<(), ToolError> { + check()?; let install_path = Path::new(install_dir); let canonical_install_dir = inspect::strip_verbatim_prefix( &install_path @@ -751,6 +792,7 @@ impl ToolInstallerHost for PlatformToolInstaller { self.ensure_game_stopped(&canonical_install_dir)?; let tool_id_obj = ToolId::new(tool_id); + check()?; if let Some(mut inst) = store.get_installation(entry_key, &tool_id_obj)? { inst.state = ToolInstallState::Uninstalling; @@ -1927,6 +1969,86 @@ mod tests { ); } + #[test] + fn guarded_install_revalidates_after_download_and_rolls_back_revocation_during_deployment() { + for during_deployment in [false, true] { + let temp = TempDir::new().unwrap(); + let game = temp.path().join("game"); + setup_unreal_game_folder(&game); + let before = collect_dir_fingerprint(&game); + let payload = temp.path().join("OptiScaler.dll"); + std::fs::write(&payload, b"guarded-fixture-payload").unwrap(); + let installer = PlatformToolInstaller::new( + temp.path().join("backups"), + Arc::new(MockProcesses::new(vec![])), + ); + let store = InMemoryToolStore::default(); + let catalog = MockCatalog::new(); + let descriptor = optiscaler_descriptor(); + catalog.register_archive( + descriptor.id.clone(), + ToolChannel::Stable, + "fixture", + &payload, + ); + let release = ToolRelease { + tool_id: descriptor.id.clone(), + channel: ToolChannel::Stable, + version: "fixture".into(), + tag_name: "fixture".into(), + name: "Fixture".into(), + published_at: String::new(), + download_url: "https://example.invalid/fixture".into(), + asset_name: "OptiScaler.dll".into(), + size_bytes: 23, + sha256: None, + cached_path: None, + }; + let request = InstallRequest { + entry_key: "fixture:1".into(), + tool_id: descriptor.id.clone(), + channel: ToolChannel::Stable, + version: release.version.clone(), + target_exe: "Binaries/Win64/Game-Win64-Shipping.exe".into(), + proxy_dll: Some(ProxyDllName::Dxgi), + reset_config: false, + anticheat_confirmed: true, + custom_payload_path: None, + }; + let checks = std::cell::Cell::new(0); + let after_write = std::cell::Cell::new(false); + let check = || { + checks.set(checks.get() + 1); + let written = std::fs::read(game.join("Binaries/Win64/dxgi.dll")) + .is_ok_and(|b| b == b"guarded-fixture-payload"); + after_write.set(after_write.get() || written); + if (during_deployment && written) || (!during_deployment && checks.get() == 2) { + Err(ToolError::Failed("authority revoked".into())) + } else { + Ok(()) + } + }; + let error = installer + .install_or_update_checked( + &store, + &catalog, + &descriptor, + &release, + &request, + game.to_str().unwrap(), + &check, + ) + .unwrap_err(); + assert!( + matches!(error, ToolError::Failed(ref message) if message == "authority revoked"), + "{error:?}" + ); + assert_eq!(after_write.get(), during_deployment); + assert_eq!(collect_dir_fingerprint(&game), before); + assert!(store.list_installations().unwrap().is_empty()); + } + } + #[test] fn test_mid_install_failure_rollback() { let temp = TempDir::new().unwrap(); diff --git a/crates/platform/src/volume.rs b/crates/platform/src/volume.rs new file mode 100644 index 000000000..8663e5855 --- /dev/null +++ b/crates/platform/src/volume.rs @@ -0,0 +1,579 @@ +//! Read-only volume observations for approved plugin resources (13.5). +//! Blocking: callers must use a worker. Linux reads mountinfo, sysfs and statvfs; +//! Windows reads volume GUIDs, drive type and capacity through Win32 metadata APIs. +//! Unknown dimensions remain unknown. Tokens hash filesystem UUIDs/volume GUIDs; +//! Linux falls back conservatively to a boot-scoped mount instance when no UUID is +//! visible. That fallback requires review after remount/reboot instead of trusting +//! a reused device number. Tokens expose no serial numbers. + +use sha2::{Digest, Sha256}; +use std::path::Path; +use std::time::{SystemTime, UNIX_EPOCH}; + +/// Locality: whether the volume is local or on the network. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Locality { + Local, + Network, + Unknown, +} + +impl Locality { + pub const fn as_str(self) -> &'static str { + match self { + Self::Local => "local", + Self::Network => "network", + Self::Unknown => "unknown", + } + } +} + +/// Removability: whether the volume is permanently attached or removable. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Removability { + Internal, + External, + Removable, + Unknown, +} + +impl Removability { + pub const fn as_str(self) -> &'static str { + match self { + Self::Internal => "internal", + Self::External => "external", + Self::Removable => "removable", + Self::Unknown => "unknown", + } + } +} + +/// Bus type: the interface the volume is connected through. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum BusType { + Usb, + Sata, + Nvme, + Mmc, + Other, + Unknown, +} + +impl BusType { + pub const fn as_str(self) -> &'static str { + match self { + Self::Usb => "usb", + Self::Sata => "sata", + Self::Nvme => "nvme", + Self::Mmc => "mmc", + Self::Other => "other", + Self::Unknown => "unknown", + } + } +} + +/// Media type: HDD (rotating disk), SSD, or unknown. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum MediaType { + Hdd, + Ssd, + Other, + Unknown, +} + +impl MediaType { + pub const fn as_str(self) -> &'static str { + match self { + Self::Hdd => "hdd", + Self::Ssd => "ssd", + Self::Other => "other", + Self::Unknown => "unknown", + } + } +} + +/// Metadata about the volume that holds a path. +#[derive(Clone, Debug)] +pub struct VolumeInfo { + /// An opaque token that identifies the volume (filesystem UUID or device number). Two paths + /// on the same volume have the same token. A different disk at the same mount point has a + /// different token. + pub volume_identity_token: String, + /// The mount point that this volume is at (best effort; empty if unknown). + pub mount_point: String, + pub locality: Locality, + pub removability: Removability, + pub bus_type: BusType, + pub media_type: MediaType, + /// Total capacity of the volume in bytes; `0` if unknown. + pub capacity_bytes: u64, + /// Free bytes available to the current user; `0` if unknown. + pub free_bytes: u64, + /// Unix seconds when the observation was made. + pub observed_at: i64, +} + +impl VolumeInfo { + /// Returns an all-unknown `VolumeInfo` for `path`, filling in capacity/free from statvfs. + #[allow(dead_code)] + fn unknown(capacity_bytes: u64, free_bytes: u64) -> Self { + Self { + volume_identity_token: String::new(), + mount_point: String::new(), + locality: Locality::Unknown, + removability: Removability::Unknown, + bus_type: BusType::Unknown, + media_type: MediaType::Unknown, + capacity_bytes, + free_bytes, + observed_at: unix_now(), + } + } +} + +fn unix_now() -> i64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0, |d| d.as_secs() as i64) +} + +/// Reads volume metadata for the volume that holds `path`. Blocking; call from a worker. +/// +/// Returns `None` when capacity cannot be queried, including a missing path. +pub fn volume_info(path: &Path) -> Option { + // Resolve capacity/free first; they tell us the volume is reachable. + let (capacity_bytes, free_bytes) = capacity_and_free(path)?; + Some(volume_info_with_capacity(path, capacity_bytes, free_bytes)) +} + +/// Reads volume metadata when the caller already holds the capacity/free values. +pub fn volume_info_with_capacity(path: &Path, capacity_bytes: u64, free_bytes: u64) -> VolumeInfo { + #[cfg(target_os = "linux")] + { + linux::volume_info_linux(path, capacity_bytes, free_bytes) + } + #[cfg(windows)] + { + windows_info(path, capacity_bytes, free_bytes) + } + #[cfg(not(any(target_os = "linux", windows)))] + { + let _ = path; + VolumeInfo::unknown(capacity_bytes, free_bytes) + } +} + +/// Returns `(capacity_bytes, free_bytes)` for the volume that holds `path`. +pub fn capacity_and_free(path: &Path) -> Option<(u64, u64)> { + capacity_and_free_at(path) +} + +#[cfg(unix)] +fn capacity_and_free_at(path: &Path) -> Option<(u64, u64)> { + let stats = rustix::fs::statvfs(path).ok()?; + let block = stats.f_frsize; + let total = stats.f_blocks.saturating_mul(block); + let free = stats.f_bavail.saturating_mul(block); + Some((total, free)) +} + +#[cfg(windows)] +fn capacity_and_free_at(path: &Path) -> Option<(u64, u64)> { + use std::os::windows::ffi::OsStrExt; + use windows_sys::Win32::Storage::FileSystem::GetDiskFreeSpaceExW; + let path: Vec<_> = path.as_os_str().encode_wide().chain(Some(0)).collect(); + let (mut free, mut total) = (0, 0); + // SAFETY: terminated path and writable counters live for this synchronous call. + (unsafe { GetDiskFreeSpaceExW(path.as_ptr(), &mut free, &mut total, std::ptr::null_mut()) } + != 0) + .then_some((total, free)) +} + +#[cfg(not(any(unix, windows)))] +fn capacity_and_free_at(_path: &Path) -> Option<(u64, u64)> { + None +} + +#[cfg(windows)] +fn windows_info(path: &Path, capacity: u64, free: u64) -> VolumeInfo { + use std::os::windows::ffi::OsStrExt; + use windows_sys::Win32::Storage::FileSystem::{ + GetDriveTypeW, GetVolumeNameForVolumeMountPointW, GetVolumePathNameW, + }; + let path: Vec<_> = path.as_os_str().encode_wide().chain(Some(0)).collect(); + let mut mount = vec![0u16; 32768]; + let mut name = vec![0u16; 1024]; + let mut info = VolumeInfo::unknown(capacity, free); + // SAFETY: buffers are writable, sized as passed, and input is terminated. + if unsafe { GetVolumePathNameW(path.as_ptr(), mount.as_mut_ptr(), mount.len() as u32) } == 0 { + return info; + } + let len = mount.iter().position(|c| *c == 0).unwrap_or(0); + info.mount_point = String::from_utf16_lossy(&mount[..len]); + // SAFETY: mount is terminated and name has the advertised capacity. + if unsafe { + GetVolumeNameForVolumeMountPointW(mount.as_ptr(), name.as_mut_ptr(), name.len() as u32) + } != 0 + { + let len = name.iter().position(|c| *c == 0).unwrap_or(0); + let bytes: Vec<_> = name[..len].iter().flat_map(|c| c.to_le_bytes()).collect(); + info.volume_identity_token = format!("volume:{:x}", Sha256::digest(bytes)); + } + // SAFETY: mount is a terminated string. + match unsafe { GetDriveTypeW(mount.as_ptr()) } { + 4 => info.locality = Locality::Network, + 2 => { + info.locality = Locality::Local; + info.removability = Removability::Removable; + } + 3 | 5 | 6 => info.locality = Locality::Local, + _ => {} + } + info +} + +// ── Linux implementation ────────────────────────────────────────────────────── + +#[cfg(target_os = "linux")] +mod linux { + use std::path::{Path, PathBuf}; + + use super::*; + + /// Filesystem types that are network-backed. + const NETWORK_FS: &[&str] = &[ + "nfs", + "nfs4", + "nfs3", + "cifs", + "smb3", + "smbfs", + "9p", + "afs", + "glusterfs", + "ceph", + "lustre", + "beegfs", + "gpfs", + "ncpfs", + "sshfs", + "ftpfs", + "davfs", + "davfs2", + ]; + + pub(super) fn volume_info_linux( + path: &Path, + capacity_bytes: u64, + free_bytes: u64, + ) -> VolumeInfo { + // Parse /proc/self/mountinfo for the best mount point and device name. + let mounts = read_mountinfo().unwrap_or_default(); + let (mount_point, fs_type, dev_name, dev_major_minor) = + best_mount_for(path, &mounts).unwrap_or_default(); + + let locality = locality_from_fs(&fs_type); + let (removability, bus_type, media_type) = if locality == Locality::Network { + // Network volumes: physical medium is unknown. + (Removability::Unknown, BusType::Unknown, MediaType::Unknown) + } else { + block_dimensions(&dev_name, &dev_major_minor) + }; + + let volume_identity_token = volume_token(&dev_name, &dev_major_minor, &mount_point); + + VolumeInfo { + volume_identity_token, + mount_point, + locality, + removability, + bus_type, + media_type, + capacity_bytes, + free_bytes, + observed_at: unix_now(), + } + } + + /// One line of `/proc/self/mountinfo`. + struct MountEntry { + /// Major:minor of the device (e.g. `8:1`). + dev_major_minor: String, + /// The root of the mount within the filesystem. + _fs_root: String, + /// Where it is mounted in this process's view. + mount_point: PathBuf, + /// The filesystem type (e.g. `ext4`, `nfs`). + fs_type: String, + /// The source device or host (e.g. `/dev/sda1`, `server:/share`). + source: String, + } + + fn read_mountinfo() -> Option> { + let text = std::fs::read_to_string("/proc/self/mountinfo").ok()?; + parse_mountinfo(&text) + } + + fn parse_mountinfo(text: &str) -> Option> { + let mut entries = Vec::new(); + for line in text.lines() { + // Format: id parent_id major:minor fs_root mount_point opt... - fs_type source opt + let mut parts = line.split_whitespace(); + let _id = parts.next()?; + let _parent = parts.next()?; + let dev_major_minor = parts.next()?.to_owned(); + let fs_root = parts.next()?.to_owned(); + let mount_point_str = parts.next()?; + // Skip optional fields until the separator `-` + let rest: Vec<&str> = parts.collect(); + let sep = rest.iter().position(|s| *s == "-")?; + let after: &[&str] = &rest[sep + 1..]; + let fs_type = after.first()?.to_string(); + let source = after.get(1).unwrap_or(&"").to_string(); + entries.push(MountEntry { + dev_major_minor, + _fs_root: fs_root, + mount_point: PathBuf::from(unescape_mount(mount_point_str)), + fs_type, + source, + }); + } + Some(entries) + } + + /// Finds the most specific (longest) mount that is a prefix of `path`. + fn best_mount_for( + path: &Path, + mounts: &[MountEntry], + ) -> Option<(String, String, String, String)> { + let canonical = std::fs::canonicalize(path) + .ok() + .unwrap_or_else(|| path.to_path_buf()); + let mut best: Option<&MountEntry> = None; + let mut best_len = 0usize; + for entry in mounts { + if canonical.starts_with(&entry.mount_point) { + let len = entry.mount_point.as_os_str().len(); + if len > best_len { + best_len = len; + best = Some(entry); + } + } + } + let entry = best?; + let mount_point = entry.mount_point.to_str().unwrap_or("").to_owned(); + Some(( + mount_point, + entry.fs_type.clone(), + entry.source.clone(), + entry.dev_major_minor.clone(), + )) + } + + fn locality_from_fs(fs_type: &str) -> Locality { + // Fuse filesystems used by GVFS (gvfsd-fuse) may be local or remote; we cannot know. + if NETWORK_FS.contains(&fs_type) || fs_type == "fuse.sshfs" { + Locality::Network + } else if fs_type.is_empty() || fs_type.starts_with("fuse") { + Locality::Unknown + } else { + Locality::Local + } + } + + /// Derives the block device name from the source or device path, then reads + /// /sys/block//{queue/rotational,removable} and the symlink to find the bus. + fn block_dimensions(source: &str, dev_major_minor: &str) -> (Removability, BusType, MediaType) { + let dev_name = block_dev_name(source, dev_major_minor); + let Some(dev_name) = dev_name else { + return (Removability::Unknown, BusType::Unknown, MediaType::Unknown); + }; + let rotational = read_sysfs_u8(&format!("/sys/block/{dev_name}/queue/rotational")); + let removable = read_sysfs_u8(&format!("/sys/block/{dev_name}/removable")); + let bus = bus_from_syslink(&dev_name); + + let media_type = match rotational { + Some(1) => MediaType::Hdd, + Some(0) + if matches!( + bus, + BusType::Usb | BusType::Sata | BusType::Nvme | BusType::Mmc + ) => + { + MediaType::Ssd + } + _ => MediaType::Unknown, + }; + let removability = match removable { + Some(1) => Removability::Removable, + Some(0) if bus == BusType::Usb => Removability::External, + // Non-removable does not establish an internal connection. + Some(0) => Removability::Unknown, + _ => Removability::Unknown, + }; + (removability, bus, media_type) + } + + /// Returns the base block device name (e.g. `sda` from `/dev/sda1`, `nvme0n1`). + fn block_dev_name(source: &str, dev_major_minor: &str) -> Option { + // If source is a /dev/... path, strip to base block device name by looking for + // the device in /sys/block/. We try both the full name and the name without digits. + if let Some(name) = source.strip_prefix("/dev/") { + // Strip trailing partition suffix: sda1 → sda, nvme0n1p2 → nvme0n1. + let base = strip_partition_suffix(name); + if std::path::Path::new(&format!("/sys/block/{base}")).exists() { + return Some(base.to_owned()); + } + } + // Fall back: look in /sys/block for a device whose `dev` file matches major:minor + // (expensive but only reached for unusual setups like device-mapper). + if !dev_major_minor.is_empty() + && let Ok(entries) = std::fs::read_dir("/sys/block") + { + for entry in entries.flatten() { + let name = entry.file_name().to_string_lossy().into_owned(); + let dev_path = format!("/sys/block/{name}/dev"); + if let Ok(content) = std::fs::read_to_string(&dev_path) + && content.trim() == dev_major_minor + { + return Some(name); + } + } + } + None + } + + fn strip_partition_suffix(name: &str) -> &str { + // nvme0n1p2 → nvme0n1 (strip 'p' + digits at end when there's also 'n') + if let Some(pos) = name.rfind('p') + && pos > 0 + && name[pos + 1..].chars().all(char::is_numeric) + && (name[..pos].starts_with("nvme") || name[..pos].starts_with("mmcblk")) + { + return &name[..pos]; + } + // sda1 → sda (strip trailing digits) + if name.starts_with("mmcblk") || name.starts_with("nvme") { + return name; + } + let stripped = name.trim_end_matches(char::is_numeric); + if !stripped.is_empty() && stripped.len() < name.len() { + stripped + } else { + name + } + } + + fn read_sysfs_u8(path: &str) -> Option { + std::fs::read_to_string(path) + .ok() + .and_then(|s| s.trim().parse().ok()) + } + + /// Reads the sysfs symlink for the block device and infers the bus type. + fn bus_from_syslink(dev_name: &str) -> BusType { + let link = match std::fs::read_link(format!("/sys/block/{dev_name}")) { + Ok(l) => l.to_string_lossy().into_owned(), + Err(_) => return BusType::Unknown, + }; + // The symlink target contains bus identifiers in its path, e.g.: + // ../devices/pci0000:00/.../usb1/... → USB + // ../devices/pci0000:00/.../ata1/... → SATA/ATA + // ../devices/pci0000:00/.../nvme/... → NVMe + // ../devices/pci0000:00/.../mmc/... → MMC/SD + let components: Vec<_> = link.split('/').collect(); + if components.iter().any(|c| c.starts_with("usb")) { + return BusType::Usb; + } + if components.iter().any(|c| c.starts_with("nvme")) { + return BusType::Nvme; + } + if components.iter().any(|c| c.starts_with("ata")) { + return BusType::Sata; + } + if components.iter().any(|c| c.starts_with("mmc")) { + return BusType::Mmc; + } + // A virtio or other PCI device that did not match anything specific. + if link.contains("pci") || link.contains("virtio") { + return BusType::Other; + } + BusType::Unknown + } + + // A mount instance is deliberately conservative: after a reboot or remount, scope + // approval requires review. A device number or mount path alone is never identity. + fn volume_token(source: &str, device: &str, mount: &str) -> String { + if let Ok(source) = std::fs::canonicalize(source) + && let Ok(entries) = std::fs::read_dir("/dev/disk/by-uuid") + { + for entry in entries.flatten() { + if std::fs::canonicalize(entry.path()).ok().as_ref() == Some(&source) { + return format!( + "fs:{:x}", + Sha256::digest(entry.file_name().as_encoded_bytes()) + ); + } + } + } + let Ok(boot) = std::fs::read_to_string("/proc/sys/kernel/random/boot_id") else { + return String::new(); + }; + let Ok(text) = std::fs::read_to_string("/proc/self/mountinfo") else { + return String::new(); + }; + for line in text.lines() { + let fields: Vec<_> = line.split_whitespace().collect(); + if fields.len() > 5 && fields[2] == device && unescape_mount(fields[4]) == mount { + let input = format!("{}:{}:{}:{}", boot.trim(), fields[0], device, fields[3]); + return format!("mount-instance:{:x}", Sha256::digest(input.as_bytes())); + } + } + String::new() + } + + fn unescape_mount(value: &str) -> String { + value + .replace("\\040", " ") + .replace("\\011", "\t") + .replace("\\012", "\n") + .replace("\\134", "\\") + } + #[cfg(test)] + mod fixtures { + use super::*; + #[test] + fn mount_paths_decode_escapes_and_match_components() { + let entries = parse_mountinfo("1 0 8:1 / / rw - ext4 /dev/sda1 rw\n2 1 8:2 / /games\\040disk rw - ext4 /dev/sdb1 rw").unwrap(); + assert_eq!( + best_mount_for(Path::new("/games disk/save"), &entries) + .unwrap() + .0, + "/games disk" + ); + assert_eq!( + best_mount_for(Path::new("/games disks/save"), &entries) + .unwrap() + .0, + "/" + ); + } + #[test] + fn network_unknown_and_partition_shapes_remain_distinct() { + assert_eq!(locality_from_fs("fuse.sshfs"), Locality::Network); + assert_eq!(locality_from_fs("fuse.custom"), Locality::Unknown); + assert_eq!(locality_from_fs(""), Locality::Unknown); + for (input, expected) in [ + ("sda1", "sda"), + ("nvme0n1", "nvme0n1"), + ("nvme0n1p2", "nvme0n1"), + ("mmcblk0p1", "mmcblk0"), + ] { + assert_eq!(strip_partition_suffix(input), expected); + } + } + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/platform/src/volume/tests.rs b/crates/platform/src/volume/tests.rs new file mode 100644 index 000000000..c4804e385 --- /dev/null +++ b/crates/platform/src/volume/tests.rs @@ -0,0 +1,110 @@ +//! Tests for `volume`. + +use std::path::Path; + +use super::*; + +#[test] +fn volume_info_for_temp_dir_has_known_locality() { + let dir = std::env::temp_dir(); + let info = volume_info(&dir); + // tmpfs or similar is expected; at minimum capacity_and_free must work. + assert!(info.is_some(), "volume_info returned None for temp dir"); + let info = info.unwrap(); + // On Linux tmpfs is a local filesystem. + #[cfg(target_os = "linux")] + { + // tmpfs is local. + assert!( + matches!(info.locality, Locality::Local | Locality::Unknown), + "unexpected locality for temp dir: {:?}", + info.locality + ); + } + assert!(info.observed_at > 0); +} + +#[test] +fn locality_as_str_values_are_stable() { + assert_eq!(Locality::Local.as_str(), "local"); + assert_eq!(Locality::Network.as_str(), "network"); + assert_eq!(Locality::Unknown.as_str(), "unknown"); +} + +#[test] +fn removability_as_str_values_are_stable() { + assert_eq!(Removability::Internal.as_str(), "internal"); + assert_eq!(Removability::Removable.as_str(), "removable"); + assert_eq!(Removability::Unknown.as_str(), "unknown"); +} + +#[test] +fn bus_type_as_str_values_are_stable() { + assert_eq!(BusType::Usb.as_str(), "usb"); + assert_eq!(BusType::Sata.as_str(), "sata"); + assert_eq!(BusType::Nvme.as_str(), "nvme"); + assert_eq!(BusType::Mmc.as_str(), "mmc"); + assert_eq!(BusType::Other.as_str(), "other"); + assert_eq!(BusType::Unknown.as_str(), "unknown"); +} + +#[test] +fn media_type_as_str_values_are_stable() { + assert_eq!(MediaType::Hdd.as_str(), "hdd"); + assert_eq!(MediaType::Ssd.as_str(), "ssd"); + assert_eq!(MediaType::Other.as_str(), "other"); + assert_eq!(MediaType::Unknown.as_str(), "unknown"); +} + +#[test] +fn capacity_and_free_for_root_are_nonzero() { + let root = Path::new("/"); + // On any Unix system, root has capacity and free bytes. + if let Some((cap, free)) = capacity_and_free(root) { + assert!(cap > 0, "root capacity should be nonzero"); + assert!(cap >= free, "free must not exceed capacity"); + } + // On non-Unix it may return None; that is acceptable. +} + +#[test] +fn missing_path_does_not_report_an_ancestors_volume() { + let dir = tempfile::tempdir().unwrap(); + let missing = dir.path().join("not-there").join("deeper"); + let info = volume_info(&missing); + assert!(info.is_none()); +} + +#[cfg(target_os = "linux")] +mod linux_tests { + use super::*; + + #[test] + fn strip_partition_suffix_handles_nvme_and_sda() { + // These are internal helpers; test through the public interface. + // We just check the shapes work for a real device on this machine. + let root = Path::new("/"); + let info = volume_info(root).expect("root volume_info"); + // On a real Linux machine the token should not be empty. + assert!( + !info.volume_identity_token.is_empty(), + "token should be non-empty for root on Linux: {:?}", + info + ); + // mount_point for root is always "/". + assert_eq!(info.mount_point, "/"); + // Locality should be local. + assert_eq!(info.locality, Locality::Local); + } + + #[test] + fn sysfs_bus_recognized_for_known_devices() { + // We cannot assert a specific bus type (the test runner may be a VM), + // but the value must be one of the declared variants. + let root = Path::new("/"); + let info = volume_info(root).unwrap(); + // Any known variant is fine; Unknown is also valid (e.g. tmpfs on root in CI). + let _ = info.bus_type; + let _ = info.media_type; + } +} diff --git a/crates/plugin-epic/src/runtime.rs b/crates/plugin-epic/src/runtime.rs index 6628fbe92..bd099c31a 100644 --- a/crates/plugin-epic/src/runtime.rs +++ b/crates/plugin-epic/src/runtime.rs @@ -192,6 +192,7 @@ impl ProviderPlugin for EpicPlugin { name: record.name.unwrap_or_default(), install_dir: record.install_dir, fields: record.fields.into_iter().collect(), + target: None, }) .collect(), install_root: scan.install_root, diff --git a/crates/plugin-epic/src/runtime/tests.rs b/crates/plugin-epic/src/runtime/tests.rs index ccda27d27..eabc75266 100644 --- a/crates/plugin-epic/src/runtime/tests.rs +++ b/crates/plugin-epic/src/runtime/tests.rs @@ -118,6 +118,8 @@ fn authorize(context: Option<&ServiceContext>) -> Result<(), Status> { #[tonic::async_trait] impl plugin_host_server::PluginHost for Host { + type WatchPermissionChangesStream = tokio_stream::Empty>; + async fn open_session( &self, request: Request, @@ -134,9 +136,12 @@ impl plugin_host_server::PluginHost for Host { return Err(Status::permission_denied("invalid launch")); } Ok(Response::new(OpenSessionReply { + resource_context: None, session_id: "reference".into(), api_major: API_MAJOR, api_minor: API_MINOR, + features: vec![], + support_window: None, granted_capabilities: hello.requested_capabilities, })) } @@ -147,6 +152,27 @@ impl plugin_host_server::PluginHost for Host { ) -> Result, Status> { Err(Status::unimplemented("stream only")) } + + async fn describe_api( + &self, + _: Request, + ) -> Result, Status> { + Err(Status::unimplemented("reference fixture")) + } + + async fn get_permissions( + &self, + _: Request, + ) -> Result, Status> { + Err(Status::unimplemented("reference fixture")) + } + + async fn watch_permission_changes( + &self, + _: Request, + ) -> Result, Status> { + Err(Status::unimplemented("reference fixture")) + } } #[tonic::async_trait] @@ -642,6 +668,8 @@ impl Harness { operation_id: id.into(), account_epoch: epoch, profile_epoch: 1, + session_kind: SessionKind::Unspecified as i32, + target_game: None, }), operation: kind as i32, ..Default::default() diff --git a/crates/plugin-packagekit/Cargo.toml b/crates/plugin-packagekit/Cargo.toml index 925ea0731..710f6ecf4 100644 --- a/crates/plugin-packagekit/Cargo.toml +++ b/crates/plugin-packagekit/Cargo.toml @@ -15,7 +15,7 @@ workspace = true async-trait.workspace = true gamenode-plugin-protocol = { path = "../plugin-protocol" } gamenode-plugin-sdk = { path = "../plugin-sdk" } -tokio = { workspace = true, features = ["macros", "rt-multi-thread", "process", "time"] } +tokio = { workspace = true, features = ["macros", "net", "process", "rt-multi-thread", "sync", "time"] } futures-util = "0.3" serde.workspace = true zbus = "5.19" @@ -24,3 +24,5 @@ tracing-subscriber = { version = "0.3.23", default-features = false, features = [dev-dependencies] tempfile.workspace = true +tokio-stream = { version = "0.1", features = ["net"] } +tonic = { version = "0.14", features = ["transport"] } diff --git a/crates/plugin-packagekit/src/linux/fixtures.rs b/crates/plugin-packagekit/src/linux/fixtures.rs new file mode 100644 index 000000000..777b9841b --- /dev/null +++ b/crates/plugin-packagekit/src/linux/fixtures.rs @@ -0,0 +1,655 @@ +//! Fixtures for the bounded package-manager queries. +//! +//! The backend processes and the PackageKit connection are replaced by in-memory fakes so every +//! outcome (success, empty, timeout, malformed output, unavailable backend) and the pacman / +//! PackageKit record parity can be asserted without touching the host package manager. + +use std::{ + collections::BTreeMap, + path::{Path, PathBuf}, + sync::Mutex, + time::Duration, +}; + +use async_trait::async_trait; + +use super::scan::{ + DesktopEntry, InstalledFileQuery, MAX_RECORDS, PackageBackend, PackageRow, PacmanRunner, + ScanFailure, candidate_from_desktop, exec_program, normalized_package_name, + parse_game_desktop_entry, parse_package_owner, resolve_exec, scan_packagekit, scan_pacman, + search_installed_files, +}; + +const SHORT_TIMEOUT: Duration = Duration::from_millis(20); + +struct FakePacman { + owners: BTreeMap, ScanFailure>>, + queries: Mutex>, +} + +impl FakePacman { + fn new(owners: impl IntoIterator)>) -> Self { + Self { + owners: owners + .into_iter() + .map(|(path, owner)| (path, Ok(owner.map(str::to_owned)))) + .collect(), + queries: Mutex::new(Vec::new()), + } + } + + fn failing(failure: ScanFailure) -> Self { + Self { + owners: BTreeMap::from([( + PathBuf::from("/usr/share/applications/supertux2.desktop"), + Err(failure), + )]), + queries: Mutex::new(Vec::new()), + } + } +} + +#[async_trait] +impl PacmanRunner for FakePacman { + async fn owner(&self, path: &Path) -> Result, ScanFailure> { + self.queries.lock().unwrap().push(path.to_owned()); + self.owners.get(path).cloned().unwrap_or(Ok(None)) + } +} + +struct HangingPacman; + +#[async_trait] +impl PacmanRunner for HangingPacman { + async fn owner(&self, _: &Path) -> Result, ScanFailure> { + std::future::pending().await + } +} + +struct FakePackageKit { + rows: BTreeMap, + failure: Option, + calls: Mutex)>>, +} + +impl FakePackageKit { + fn new(rows: impl IntoIterator) -> Self { + Self { + rows: rows.into_iter().collect(), + failure: None, + calls: Mutex::new(Vec::new()), + } + } + + fn empty() -> Self { + Self::new(Vec::new()) + } + + fn failing(failure: ScanFailure) -> Self { + Self { + rows: BTreeMap::new(), + failure: Some(failure), + calls: Mutex::new(Vec::new()), + } + } +} + +#[async_trait] +impl InstalledFileQuery for FakePackageKit { + async fn search_installed_files( + &self, + filter: u64, + files: Vec, + ) -> Result, ScanFailure> { + self.calls.lock().unwrap().push((filter, files.clone())); + if let Some(failure) = self.failure { + return Err(failure); + } + Ok(files + .iter() + .filter_map(|file| self.rows.get(file).cloned()) + .collect()) + } +} + +/// Returns as many rows as a PackageKit transaction can be asked to report. +struct FloodingPackageKit; + +#[async_trait] +impl InstalledFileQuery for FloodingPackageKit { + async fn search_installed_files( + &self, + _: u64, + _: Vec, + ) -> Result, ScanFailure> { + Ok((0..MAX_RECORDS + 100) + .map(|index| PackageRow { + package_id: format!("game-{index};1.0;x86_64;installed"), + summary: String::new(), + }) + .collect()) + } +} + +struct HangingPackageKit; + +#[async_trait] +impl InstalledFileQuery for HangingPackageKit { + async fn search_installed_files( + &self, + _: u64, + _: Vec, + ) -> Result, ScanFailure> { + std::future::pending().await + } +} + +fn executable(directory: &Path, name: &str) -> PathBuf { + let path = directory.join(name); + std::fs::write(&path, b"fixture").unwrap(); + path +} + +fn entry(path: &str, name: &str, program: &Path) -> DesktopEntry { + DesktopEntry { + path: PathBuf::from(path), + name: Some(name.to_owned()), + exec: program.to_string_lossy().into_owned(), + binary: Some(program.to_owned()), + } +} + +#[tokio::test] +async fn pacman_reports_the_installed_owner_of_a_visible_game_entry() { + let directory = tempfile::tempdir().unwrap(); + let program = executable(directory.path(), "supertux2"); + let game = entry( + "/usr/share/applications/supertux2.desktop", + "SuperTux", + &program, + ); + let other = entry("/usr/share/applications/editor.desktop", "Editor", &program); + let runner = FakePacman::new([(game.path.clone(), Some("supertux"))]); + + let records = scan_pacman(&runner, &[game.clone(), other.clone()], SHORT_TIMEOUT) + .await + .unwrap(); + + assert_eq!(records.len(), 1); + assert_eq!(records[0].id, "supertux"); + assert_eq!(records[0].name.as_deref(), Some("SuperTux")); + assert_eq!(records[0].install_dir, directory.path().to_string_lossy()); + assert_eq!(records[0].fields["package_manager"], "pacman"); + assert_eq!(records[0].fields["package_id"], "supertux"); + assert_eq!( + records[0].fields["desktop_file"], + "/usr/share/applications/supertux2.desktop" + ); + assert_eq!(records[0].fields["executable"], program.to_string_lossy()); + // Only candidate entries were queried, and each owner was asked exactly once. + assert_eq!( + runner.queries.lock().unwrap().as_slice(), + [game.path, other.path] + ); +} + +#[tokio::test] +async fn pacman_distinguishes_a_successful_empty_scan_from_backend_failures() { + let directory = tempfile::tempdir().unwrap(); + let program = executable(directory.path(), "supertux2"); + let game = entry( + "/usr/share/applications/supertux2.desktop", + "SuperTux", + &program, + ); + + let empty = scan_pacman( + &FakePacman::new(Vec::new()), + std::slice::from_ref(&game), + SHORT_TIMEOUT, + ) + .await + .expect("an unowned entry is a successful empty scan"); + assert!(empty.is_empty()); + + for (runner, failure) in [ + ( + FakePacman::failing(ScanFailure::PacmanUnavailable), + ScanFailure::PacmanUnavailable, + ), + ( + FakePacman::failing(ScanFailure::PacmanFailed), + ScanFailure::PacmanFailed, + ), + ( + FakePacman::failing(ScanFailure::PacmanMalformed), + ScanFailure::PacmanMalformed, + ), + ] { + assert_eq!( + scan_pacman(&runner, std::slice::from_ref(&game), SHORT_TIMEOUT) + .await + .unwrap_err(), + failure + ); + } + + assert_eq!( + scan_pacman(&HangingPacman, &[game], SHORT_TIMEOUT) + .await + .unwrap_err(), + ScanFailure::PacmanTimeout + ); +} + +#[tokio::test] +async fn pacman_scan_never_executes_the_desktop_command() { + let directory = tempfile::tempdir().unwrap(); + let marker = directory.path().join("executed"); + let program = directory.path().join("game"); + std::fs::write( + &program, + format!("#!/bin/sh\ntouch '{}'\n", marker.display()), + ) + .unwrap(); + let mut permissions = std::fs::metadata(&program).unwrap().permissions(); + std::os::unix::fs::PermissionsExt::set_mode(&mut permissions, 0o755); + std::fs::set_permissions(&program, permissions).unwrap(); + + let text = format!( + "[Desktop Entry]\nType=Application\nName=Trap\nExec={} --launch %U\nCategories=Game;\n", + program.display() + ); + let game = + parse_game_desktop_entry(PathBuf::from("/usr/share/applications/trap.desktop"), &text) + .expect("the entry resolves to an existing program"); + let runner = FakePacman::new([(game.path.clone(), Some("trap-game"))]); + + let records = scan_pacman(&runner, &[game], SHORT_TIMEOUT).await.unwrap(); + + assert_eq!(records.len(), 1); + assert!( + !marker.exists(), + "the desktop command must never be executed" + ); +} + +#[tokio::test] +async fn pacman_keeps_one_stable_record_for_repeated_package_owners() { + let directory = tempfile::tempdir().unwrap(); + let program = executable(directory.path(), "supertux2"); + let main = entry( + "/usr/share/applications/supertux2.desktop", + "SuperTux", + &program, + ); + let editor = entry( + "/usr/share/applications/supertux-editor.desktop", + "SuperTux Editor", + &program, + ); + let runner = FakePacman::new([ + (main.path.clone(), Some("supertux")), + (editor.path.clone(), Some("supertux")), + ]); + + let records = scan_pacman(&runner, &[main, editor], SHORT_TIMEOUT) + .await + .unwrap(); + + assert_eq!(records.len(), 1); + assert_eq!(records[0].id, "supertux"); + assert_eq!(records[0].name.as_deref(), Some("SuperTux")); +} + +#[tokio::test] +async fn packagekit_queries_only_installed_files_in_bounded_batches() { + let paths = (0..130) + .map(|index| format!("/usr/share/applications/game-{index}.desktop")) + .collect::>(); + let rows = paths + .iter() + .map(|path| { + ( + path.clone(), + PackageRow { + package_id: "game;1.0;x86_64;installed".into(), + summary: "Game".into(), + }, + ) + }) + .collect::>(); + let query = FakePackageKit::new(rows); + + let found = search_installed_files(&query, &paths, SHORT_TIMEOUT) + .await + .unwrap(); + + let calls = query.calls.lock().unwrap(); + assert_eq!(calls.len(), 2); + // PackageKit's Installed enum is ordinal 2, so the wire bitfield is 4. + assert!(calls.iter().all(|(filter, _)| *filter == 4)); + assert_eq!(calls[0].1.len(), 128); + assert_eq!(calls[1].1.len(), 2); + assert_eq!( + calls + .iter() + .flat_map(|(_, files)| files.clone()) + .collect::>(), + paths + ); + assert_eq!(found.len(), 130); +} + +#[tokio::test] +async fn packagekit_truncates_an_over_long_record_set() { + let paths = vec!["/usr/share/applications/game.desktop".to_owned()]; + let found = search_installed_files(&FloodingPackageKit, &paths, SHORT_TIMEOUT) + .await + .unwrap(); + assert_eq!(found.len(), MAX_RECORDS); +} + +#[tokio::test] +async fn packagekit_distinguishes_empty_results_from_failures_and_timeouts() { + let directory = tempfile::tempdir().unwrap(); + let program = executable(directory.path(), "supertux2"); + let game = entry( + "/usr/share/applications/supertux2.desktop", + "SuperTux", + &program, + ); + + let empty = scan_packagekit( + &FakePackageKit::empty(), + std::slice::from_ref(&game), + SHORT_TIMEOUT, + ) + .await + .expect("no installed owner is a successful empty scan"); + assert!(empty.is_empty()); + + for (failure, expected) in [ + ( + ScanFailure::PackageKitUnavailable, + ScanFailure::PackageKitUnavailable, + ), + (ScanFailure::PackageKitFailed, ScanFailure::PackageKitFailed), + ] { + assert_eq!( + scan_packagekit( + &FakePackageKit::failing(failure), + std::slice::from_ref(&game), + SHORT_TIMEOUT + ) + .await + .unwrap_err(), + expected + ); + } + + assert_eq!( + scan_packagekit( + &HangingPackageKit, + std::slice::from_ref(&game), + SHORT_TIMEOUT + ) + .await + .unwrap_err(), + ScanFailure::PackageKitTimeout + ); + + // Malformed package ids are skipped, not turned into a backend failure. + let malformed = FakePackageKit::new([( + game.path.to_string_lossy().into_owned(), + PackageRow { + package_id: ";1.0;x86_64;installed".into(), + summary: "Broken".into(), + }, + )]); + assert!( + scan_packagekit(&malformed, &[game], SHORT_TIMEOUT) + .await + .unwrap() + .is_empty() + ); +} + +#[tokio::test] +async fn packagekit_normalizes_a_package_record() { + let directory = tempfile::tempdir().unwrap(); + let program = executable(directory.path(), "supertux2"); + let game = entry( + "/usr/share/applications/supertux2.desktop", + "SuperTux", + &program, + ); + let query = FakePackageKit::new([( + game.path.to_string_lossy().into_owned(), + PackageRow { + package_id: "supertux;0.6.3-1;x86_64;installed".into(), + summary: "A classic 2D jump'n run".into(), + }, + )]); + + let records = scan_packagekit(&query, &[game], SHORT_TIMEOUT) + .await + .unwrap(); + + assert_eq!(records.len(), 1); + assert_eq!(records[0].id, "supertux"); + assert_eq!(records[0].name.as_deref(), Some("SuperTux")); + assert_eq!(records[0].fields["package_manager"], "packagekit"); + assert_eq!( + records[0].fields["package_id"], + "supertux;0.6.3-1;x86_64;installed" + ); +} + +#[tokio::test] +async fn pacman_and_packagekit_report_the_same_provider_local_records() { + let directory = tempfile::tempdir().unwrap(); + let program = executable(directory.path(), "supertux2"); + let game = entry( + "/usr/share/applications/supertux2.desktop", + "SuperTux", + &program, + ); + let editor = entry( + "/usr/share/applications/supertux-editor.desktop", + "SuperTux Editor", + &program, + ); + let entries = [game.clone(), editor.clone()]; + + let pacman = scan_pacman( + &FakePacman::new([ + (game.path.clone(), Some("supertux")), + (editor.path.clone(), Some("supertux")), + ]), + &entries, + SHORT_TIMEOUT, + ) + .await + .unwrap(); + let packagekit = scan_packagekit( + &FakePackageKit::new([ + ( + game.path.to_string_lossy().into_owned(), + PackageRow { + package_id: "supertux;0.6.3-1;x86_64;installed".into(), + summary: String::new(), + }, + ), + ( + editor.path.to_string_lossy().into_owned(), + PackageRow { + package_id: "supertux;0.6.3-1;x86_64;installed".into(), + summary: String::new(), + }, + ), + ]), + &entries, + SHORT_TIMEOUT, + ) + .await + .unwrap(); + + let identity = |records: &[super::scan::PackageCandidate]| { + records + .iter() + .map(|record| { + ( + record.id.clone(), + record.name.clone(), + record.install_dir.clone(), + record.fields["desktop_file"].clone(), + record.fields["executable"].clone(), + ) + }) + .collect::>() + }; + assert_eq!(identity(&pacman), identity(&packagekit)); + assert_eq!(pacman[0].fields["package_manager"], "pacman"); + assert_eq!(packagekit[0].fields["package_manager"], "packagekit"); +} + +/// Manual, read-only evidence on a live Arch-family host. +/// +/// The scan only stats desktop files and runs `pacman -Qqo`; it never executes a desktop entry. +/// Run with `cargo test -p gamenode-plugin-packagekit --offline -- --ignored --nocapture`. +#[tokio::test] +#[ignore = "reads the live /etc/os-release and pacman database; run manually on Arch"] +async fn live_arch_system_reports_installed_game_desktop_owners() { + let os_release = std::fs::read_to_string("/etc/os-release").unwrap_or_default(); + assert_eq!( + PackageBackend::for_os_release(&os_release), + PackageBackend::Pacman, + "the live evidence needs an Arch-family host" + ); + let records = super::scan::discover().await.unwrap(); + assert!( + !records.is_empty(), + "the live host should report at least one installed game" + ); + for record in &records { + assert_eq!(record.fields["package_manager"], "pacman"); + assert!(Path::new(&record.fields["executable"]).is_file()); + assert!(Path::new(&record.fields["desktop_file"]).is_file()); + println!( + "{} ({}) -> {} [{}]", + record.id, + record.name.as_deref().unwrap_or_default(), + record.fields["executable"], + record.fields["desktop_file"] + ); + } +} + +#[test] +fn selects_pacman_for_arch_and_arch_derivatives() { + assert_eq!( + PackageBackend::for_os_release("ID=arch\n"), + PackageBackend::Pacman + ); + assert_eq!( + PackageBackend::for_os_release("ID=manjaro\nID_LIKE=arch\n"), + PackageBackend::Pacman + ); + assert_eq!( + PackageBackend::for_os_release("ID=\"arch\"\n"), + PackageBackend::Pacman + ); +} + +#[test] +fn selects_packagekit_for_other_or_unknown_distributions() { + assert_eq!( + PackageBackend::for_os_release("ID=fedora\nID_LIKE=redhat\n"), + PackageBackend::PackageKit + ); + assert_eq!( + PackageBackend::for_os_release(""), + PackageBackend::PackageKit + ); +} + +#[test] +fn pacman_owner_output_accepts_package_and_skips_empty_or_malformed_values() { + assert_eq!( + parse_package_owner(b"supertux\n").unwrap(), + Some("supertux".to_owned()) + ); + assert_eq!(parse_package_owner(b"\n").unwrap(), None); + assert_eq!(parse_package_owner(b"bad\nname\n").unwrap(), None); + assert_eq!(parse_package_owner(b"bad\x00name\n").unwrap(), None); + assert_eq!( + parse_package_owner(&[0xff]), + Err(ScanFailure::PacmanMalformed) + ); +} + +#[test] +fn packagekit_ids_normalize_to_the_same_package_name_as_pacman() { + assert_eq!( + normalized_package_name("supertux;0.6.3-4;x86_64;installed"), + Some("supertux") + ); + assert_eq!(normalized_package_name("supertux"), Some("supertux")); + assert_eq!(normalized_package_name(";1.0;x86_64;installed"), None); + assert_eq!(normalized_package_name("bad/name;1.0;arch;installed"), None); +} + +#[test] +fn game_desktop_metadata_is_required_and_candidates_keep_package_identity() { + let desktop = parse_game_desktop_entry( + PathBuf::from("/usr/share/applications/supertux2.desktop"), + "[Desktop Entry]\nType=Application\nName=SuperTux\nExec=/usr/bin/true\nCategories=Game;\n", + ) + .unwrap(); + let candidate = candidate_from_desktop("supertux", &desktop, "pacman").unwrap(); + assert_eq!(candidate.id, "supertux"); + assert_eq!(candidate.name.as_deref(), Some("SuperTux")); + assert_eq!(candidate.fields["package_manager"], "pacman"); + + assert!(parse_game_desktop_entry( + PathBuf::from("/usr/share/applications/not-a-game.desktop"), + "[Desktop Entry]\nType=Application\nName=Text Editor\nExec=/usr/bin/true\nCategories=Utility;\n", + ) + .is_none()); + assert!(parse_game_desktop_entry( + PathBuf::from("/usr/share/applications/hidden.desktop"), + "[Desktop Entry]\nType=Application\nName=Hidden\nExec=/usr/bin/true\nCategories=Game;\nNoDisplay=true\n", + ) + .is_none()); + assert!( + parse_game_desktop_entry( + PathBuf::from("/usr/share/applications/malformed.desktop"), + "not a desktop entry", + ) + .is_none() + ); + assert!(parse_game_desktop_entry( + PathBuf::from("/usr/share/applications/missing.desktop"), + "[Desktop Entry]\nType=Application\nName=Missing\nExec=/nonexistent/program\nCategories=Game;\n", + ) + .is_some_and(|entry| entry.binary.is_none())); +} + +#[test] +fn quoted_exec_program_with_spaces_is_discovered_without_interpreting_arguments() { + let dir = tempfile::tempdir().unwrap(); + let program = dir.path().join("Game With Spaces"); + std::fs::write(&program, b"fixture").unwrap(); + let exec = format!("\"{}\" --fullscreen %U", program.display()); + assert_eq!(resolve_exec(&exec), Some(program)); + assert!(exec_program("\"unterminated path").is_none()); + assert!(exec_program("game\\").is_none()); + assert!(exec_program("%f --game").is_none()); + assert!(exec_program(&"a".repeat(8_193)).is_none()); + assert_eq!( + exec_program("\"game\\\"name\" %U").as_deref(), + Some("game\"name") + ); + assert_eq!(resolve_exec("/nonexistent/game"), None); +} diff --git a/crates/plugin-packagekit/src/linux/mod.rs b/crates/plugin-packagekit/src/linux/mod.rs new file mode 100644 index 000000000..70ff36be0 --- /dev/null +++ b/crates/plugin-packagekit/src/linux/mod.rs @@ -0,0 +1,16 @@ +//! Linux-only package-manager discovery provider. +//! +//! The provider offers discovery only: it reads installed desktop entries, asks the package +//! manager which installed package owns each entry, and reports the candidates through the SDK's +//! `OperationResult.discovery` event. It never executes a desktop entry command and declares no +//! account, catalog, playtime, launch or install authority. + +mod plugin; +mod scan; + +#[cfg(test)] +mod fixtures; +#[cfg(test)] +mod reference_host; + +pub(crate) use plugin::run; diff --git a/crates/plugin-packagekit/src/linux/plugin.rs b/crates/plugin-packagekit/src/linux/plugin.rs new file mode 100644 index 000000000..741dda084 --- /dev/null +++ b/crates/plugin-packagekit/src/linux/plugin.rs @@ -0,0 +1,136 @@ +//! The `gamenode-plugin-sdk::ProviderPlugin` implementation. +//! +//! Discovery is the only supported operation. The plugin obtains the trusted provider context +//! from the host, checks that it really is the Linux `packagekit` provider, runs one bounded scan +//! and returns normalized records in `OperationResult.discovery`. Every other operation is +//! declined so the plugin keeps no account, catalog, action, settings or launch authority. + +use std::{env, sync::Arc, time::Duration}; + +use async_trait::async_trait; +use gamenode_plugin_protocol::{capability, proto::*}; +use gamenode_plugin_sdk::{Error, HostClient, Launch, ProviderPlugin, Session}; + +use super::scan::{self, MAX_RECORDS, PackageCandidate, ScanFailure}; + +pub(super) const PLUGIN_ID: &str = "org.gamenode.plugin.packagekit-discovery"; +pub(super) const PROVIDER_ID: &str = "packagekit"; +pub(super) const PLATFORM: &str = "linux"; +const SCAN_TIMEOUT: Duration = Duration::from_secs(60); + +/// A source of already-normalized package candidates. +/// +/// The production source reads the system and queries the selected backend; fixtures substitute +/// a static source so the SDK contract can be exercised without host package metadata. +#[async_trait] +pub(super) trait DiscoverySource: Send + Sync { + async fn discover(&self) -> Result, ScanFailure>; +} + +struct SystemDiscovery; + +#[async_trait] +impl DiscoverySource for SystemDiscovery { + async fn discover(&self) -> Result, ScanFailure> { + scan::discover().await + } +} + +pub(super) struct PackageManagerPlugin { + source: Arc, + timeout: Duration, +} + +impl PackageManagerPlugin { + fn system() -> Self { + Self { + source: Arc::new(SystemDiscovery), + timeout: SCAN_TIMEOUT, + } + } + + #[cfg(test)] + pub(super) fn with_source(source: Arc, timeout: Duration) -> Self { + Self { source, timeout } + } +} + +#[async_trait] +impl ProviderPlugin for PackageManagerPlugin { + async fn handle( + &self, + command: ProviderCommand, + host: HostClient, + ) -> Result { + let operation = + ProviderOperation::try_from(command.operation).map_err(|_| Error::Protocol)?; + match operation { + ProviderOperation::Initialize => Ok(OperationResult { + disposition: OperationDisposition::Completed as i32, + ..Default::default() + }), + ProviderOperation::Discover => { + let context = host.provider_context().await?; + if context.provider_id != PROVIDER_ID || context.platform != PLATFORM { + return Err(Error::Denied); + } + let candidates = tokio::time::timeout(self.timeout, self.source.discover()) + .await + .map_err(|_| { + tracing::warn!(code = "scan_timeout", "Linux package discovery timed out"); + Error::Unavailable + })? + .map_err(|failure| { + tracing::warn!(code = failure.code(), "Linux package discovery failed"); + Error::Unavailable + })?; + Ok(OperationResult { + disposition: OperationDisposition::Completed as i32, + discovery: Some(DiscoveryResult { + provider_id: context.provider_id, + records: discovery_records(candidates), + // Packages have no store install location or library folders. + ..Default::default() + }), + ..Default::default() + }) + } + _ => Err(Error::Denied), + } + } +} + +/// Normalizes and bounds the provider-local records sent to the host. +fn discovery_records(candidates: Vec) -> Vec { + candidates + .into_iter() + .take(MAX_RECORDS) + .map(|record| DiscoveryRecord { + id: record.id, + name: record.name.unwrap_or_default(), + install_dir: record.install_dir, + fields: record.fields.into_iter().collect(), + target: None, + }) + .collect() +} + +pub(crate) async fn run() -> Result<(), &'static str> { + let _ = tracing_subscriber::fmt() + .with_env_filter("warn") + .with_writer(std::io::stderr) + .try_init(); + let launch = Launch::from_env().map_err(|_| "invalid_launch_configuration")?; + let session = Session::open( + launch, + PLUGIN_ID, + PROVIDER_ID, + env!("CARGO_PKG_VERSION"), + &[capability::CONTEXT, capability::DISCOVERY], + ) + .await + .map_err(|_| "provider_session_unavailable")?; + gamenode_plugin_sdk::run(session, Arc::new(PackageManagerPlugin::system())) + .await + .map_err(|_| "provider_session_failed") +} diff --git a/crates/plugin-packagekit/src/linux/reference_host.rs b/crates/plugin-packagekit/src/linux/reference_host.rs new file mode 100644 index 000000000..252700853 --- /dev/null +++ b/crates/plugin-packagekit/src/linux/reference_host.rs @@ -0,0 +1,440 @@ +//! SDK reference-host fixture for the package provider contract. +//! +//! The fixture runs the real `gamenode-plugin-sdk` client and dispatcher against an in-process +//! reference host over a Unix socket. Discovery is served by a static source, so the test proves +//! the provider returns normalized `OperationResult.discovery` records and declines every other +//! operation without calling the retired `SubmitDiscovery` RPC. + +use std::{ + collections::BTreeMap, + sync::{ + Arc, + atomic::{AtomicUsize, Ordering}, + }, + time::Duration, +}; + +use async_trait::async_trait; +use gamenode_plugin_protocol::{API_MAJOR, LEGACY_API_MINOR}; +use gamenode_plugin_sdk::{Launch, Session, capability, proto::*}; +use tokio::sync::{mpsc, oneshot}; +use tokio_stream::wrappers::{ReceiverStream, UnixListenerStream}; +use tonic::{Request, Response, Status}; + +use super::plugin::{DiscoverySource, PLUGIN_ID, PROVIDER_ID, PackageManagerPlugin}; +use super::scan::{MAX_RECORDS, PackageCandidate, ScanFailure}; + +const SESSION_ID: &str = "packagekit-session"; +const CREDENTIAL: [u8; 32] = [9; 32]; +const ACCOUNT_EPOCH: u64 = 3; +const PROFILE_EPOCH: u64 = 5; +const FIXTURE_TIMEOUT: Duration = Duration::from_secs(5); + +struct StaticSource(Result, ScanFailure>); + +#[async_trait] +impl DiscoverySource for StaticSource { + async fn discover(&self) -> Result, ScanFailure> { + self.0.clone() + } +} + +#[derive(Clone)] +struct ReferenceHost { + completed: mpsc::Sender<(String, OperationResult)>, + submit_discovery_calls: Arc, + /// The provider context the host reports, which the plugin must validate before scanning. + context_provider_id: &'static str, + context_platform: &'static str, +} + +fn authorize(context: Option<&ServiceContext>) -> Result<&ServiceContext, Status> { + let context = context.ok_or_else(|| Status::unauthenticated("missing context"))?; + if context.session_id != SESSION_ID + || context.session_credential != CREDENTIAL + || context.provider_id != PROVIDER_ID + { + return Err(Status::permission_denied("wrong session")); + } + if context.account_epoch != ACCOUNT_EPOCH || context.profile_epoch != PROFILE_EPOCH { + return Err(Status::failed_precondition("stale context")); + } + Ok(context) +} + +/// The SDK sends the ready event without account/profile epochs; only the session identity is +/// available at that point. +fn ready_session(context: Option<&ServiceContext>) -> Result<(), Status> { + let context = context.ok_or_else(|| Status::unauthenticated("missing context"))?; + if context.session_id != SESSION_ID + || context.session_credential != CREDENTIAL + || context.provider_id != PROVIDER_ID + { + return Err(Status::permission_denied("wrong session")); + } + Ok(()) +} + +#[tonic::async_trait] +impl plugin_host_server::PluginHost for ReferenceHost { + type WatchPermissionChangesStream = + tokio_stream::Iter>>; + + async fn open_session( + &self, + request: Request, + ) -> Result, Status> { + let hello = request.into_inner(); + // `Session::open` keeps the legacy unspecified kind; both forms are a provider session. + let provider_kind = hello.session_kind == SessionKind::Unspecified as i32 + || hello.session_kind == SessionKind::Provider as i32; + if hello.plugin_id != PLUGIN_ID + || hello.session_credential != CREDENTIAL + || !provider_kind + || hello.target_game.is_some() + || hello.requested_capabilities != [capability::CONTEXT, capability::DISCOVERY] + { + return Err(Status::permission_denied("invalid launch")); + } + Ok(Response::new(OpenSessionReply { + resource_context: None, + session_id: SESSION_ID.into(), + granted_capabilities: hello.requested_capabilities, + api_major: API_MAJOR, + api_minor: LEGACY_API_MINOR, + features: Vec::new(), + support_window: None, + })) + } + + /// The current host returns this RPC as unimplemented; a plugin that used it would fail here. + async fn submit_discovery( + &self, + _: Request, + ) -> Result, Status> { + self.submit_discovery_calls.fetch_add(1, Ordering::SeqCst); + Err(Status::permission_denied("not granted")) + } + + async fn describe_api( + &self, + request: Request, + ) -> Result, Status> { + if request.get_ref().session_id != SESSION_ID + || request.get_ref().session_credential != CREDENTIAL + { + return Err(Status::unauthenticated("invalid fixture")); + } + Ok(Response::new(DescribeApiReply { + api_major: API_MAJOR, + api_minor: LEGACY_API_MINOR, + support_window: None, + features: Vec::new(), + methods: Vec::new(), + })) + } + + async fn get_permissions( + &self, + request: Request, + ) -> Result, Status> { + if request.get_ref().session_id != SESSION_ID + || request.get_ref().session_credential != CREDENTIAL + { + return Err(Status::unauthenticated("invalid fixture")); + } + Ok(Response::new(GetPermissionsReply { + revision: 1, + grants: [capability::CONTEXT, capability::DISCOVERY] + .into_iter() + .map(|permission_id| PermissionGrant { + permission_id: permission_id.into(), + state: "granted".into(), + scope: "provider".into(), + reason: String::new(), + revision: 1, + }) + .collect(), + })) + } + + async fn watch_permission_changes( + &self, + _: Request, + ) -> Result, Status> { + Ok(Response::new(tokio_stream::iter(Vec::new()))) + } +} + +#[tonic::async_trait] +impl provider_host_server::ProviderHost for ReferenceHost { + type ExchangeStream = ReceiverStream>; + + async fn exchange( + &self, + request: Request>, + ) -> Result, Status> { + let mut input = request.into_inner(); + let ready = input + .message() + .await? + .ok_or_else(|| Status::unauthenticated("no ready event"))?; + let context = ready + .context + .clone() + .ok_or_else(|| Status::unauthenticated("no session"))?; + ready_session(Some(&context))?; + if !matches!(ready.event, Some(provider_event::Event::Ready(true))) { + return Err(Status::permission_denied("invalid ready event")); + } + let (tx, rx) = mpsc::channel(8); + let completed = self.completed.clone(); + tokio::spawn(async move { + let command = |operation, id: &str| ProviderCommand { + context: Some(ServiceContext { + operation_id: id.into(), + account_epoch: ACCOUNT_EPOCH, + profile_epoch: PROFILE_EPOCH, + ..context.clone() + }), + operation: operation as i32, + target_operation_id: String::new(), + settings: None, + runtime_session_result: None, + runtime_session_context_result: None, + achievements: None, + }; + let operations = [ + (ProviderOperation::Initialize, "initialize"), + (ProviderOperation::Discover, "discover"), + (ProviderOperation::SignIn, "sign-in"), + ]; + for (operation, id) in operations { + tx.send(Ok(command(operation, id))).await.unwrap(); + } + let mut results = 0; + while let Some(event) = input.message().await.unwrap() { + if let Some(provider_event::Event::Result(result)) = event.event { + let context = authorize(event.context.as_ref()).unwrap(); + completed + .send((context.operation_id.clone(), result)) + .await + .unwrap(); + results += 1; + if results == operations.len() { + tx.send(Ok(command(ProviderOperation::Shutdown, "shutdown"))) + .await + .unwrap(); + break; + } + } + } + }); + Ok(Response::new(ReceiverStream::new(rx))) + } + + async fn get_context( + &self, + request: Request, + ) -> Result, Status> { + authorize(Some(request.get_ref()))?; + Ok(Response::new(ProviderContext { + provider_id: self.context_provider_id.into(), + platform: self.context_platform.into(), + max_records: MAX_RECORDS as u32, + max_message_bytes: 8 * 1024 * 1024, + catalog_chunk_records: 256, + secret_storage: SecretStorage::PrivateFile as i32, + ..Default::default() + })) + } + + async fn account(&self, _: Request) -> Result, Status> { + Err(Status::permission_denied("not granted")) + } + + async fn secret(&self, _: Request) -> Result, Status> { + Err(Status::permission_denied("not granted")) + } + + async fn login(&self, _: Request) -> Result, Status> { + Err(Status::permission_denied("not granted")) + } + + async fn declare_actions( + &self, + _: Request, + ) -> Result, Status> { + Err(Status::permission_denied("not granted")) + } +} + +/// Runs the provider against the reference host and returns its operation results. +async fn run_fixture( + source: Arc, + context_provider_id: &'static str, + context_platform: &'static str, +) -> (BTreeMap, Arc) { + let temp = tempfile::tempdir().unwrap(); + let endpoint = temp.path().join("reference.sock"); + let listener = tokio::net::UnixListener::bind(&endpoint).unwrap(); + let (tx, mut completed) = mpsc::channel(16); + let submit_discovery_calls = Arc::new(AtomicUsize::new(0)); + let reference = ReferenceHost { + completed: tx, + submit_discovery_calls: submit_discovery_calls.clone(), + context_provider_id, + context_platform, + }; + let (shutdown, stopped) = oneshot::channel(); + let server = tokio::spawn( + tonic::transport::Server::builder() + .add_service(plugin_host_server::PluginHostServer::new(reference.clone())) + .add_service(provider_host_server::ProviderHostServer::new(reference)) + .serve_with_incoming_shutdown(UnixListenerStream::new(listener), async { + let _ = stopped.await; + }), + ); + let session = Session::open( + Launch { + endpoint, + credential: CREDENTIAL.to_vec(), + operation_id: "launch".into(), + }, + PLUGIN_ID, + PROVIDER_ID, + "0.1.0", + &[capability::CONTEXT, capability::DISCOVERY], + ) + .await + .unwrap(); + let plugin = PackageManagerPlugin::with_source(source, FIXTURE_TIMEOUT); + tokio::time::timeout( + FIXTURE_TIMEOUT, + gamenode_plugin_sdk::run(session, Arc::new(plugin)), + ) + .await + .unwrap() + .unwrap(); + + let mut results = BTreeMap::new(); + for _ in 0..3 { + let (id, result) = completed.recv().await.unwrap(); + results.insert(id, result); + } + let _ = shutdown.send(()); + server.await.unwrap().unwrap(); + (results, submit_discovery_calls) +} + +fn candidate(id: &str, name: &str, install_dir: &str) -> PackageCandidate { + PackageCandidate { + id: id.into(), + name: Some(name.into()), + install_dir: install_dir.into(), + fields: BTreeMap::from([ + ("package_id".into(), id.into()), + ("package_manager".into(), "pacman".into()), + ( + "desktop_file".into(), + format!("/usr/share/applications/{id}.desktop"), + ), + ("executable".into(), format!("{install_dir}/{id}")), + ]), + } +} + +#[tokio::test] +async fn provider_returns_normalized_discovery_records_and_declines_other_operations() { + let records = vec![ + candidate("supertux", "SuperTux", "/usr/bin"), + candidate("0ad", "0 A.D.", "/usr/bin"), + ]; + let (results, submit_discovery) = + run_fixture(Arc::new(StaticSource(Ok(records))), PROVIDER_ID, "linux").await; + + assert_eq!( + results["initialize"].disposition, + OperationDisposition::Completed as i32 + ); + let discovery = results["discover"] + .discovery + .as_ref() + .expect("Discover returns records through OperationResult.discovery"); + assert_eq!(discovery.provider_id, PROVIDER_ID); + assert_eq!(discovery.records.len(), 2); + assert_eq!(discovery.records[0].id, "supertux"); + assert_eq!(discovery.records[0].name, "SuperTux"); + assert_eq!(discovery.records[0].install_dir, "/usr/bin"); + assert_eq!(discovery.records[0].fields["package_manager"], "pacman"); + assert!(discovery.records[0].target.is_none()); + assert!(discovery.install_root.is_none()); + + // Only discovery is granted: the account, catalog, login and action operations are declined. + let declined = &results["sign-in"]; + assert_eq!(declined.disposition, OperationDisposition::Failed as i32); + assert_eq!(declined.failure.as_ref().unwrap().code, "denied"); + assert!(declined.discovery.is_none()); + assert_eq!(submit_discovery.load(Ordering::SeqCst), 0); +} + +#[tokio::test] +async fn provider_reports_a_successful_empty_scan_as_completed() { + let (results, submit_discovery) = + run_fixture(Arc::new(StaticSource(Ok(Vec::new()))), PROVIDER_ID, "linux").await; + + let completion = &results["discover"]; + assert_eq!( + completion.disposition, + OperationDisposition::Completed as i32 + ); + let discovery = completion + .discovery + .as_ref() + .expect("an empty scan still returns a discovery result"); + assert_eq!(discovery.provider_id, PROVIDER_ID); + assert!(discovery.records.is_empty()); + assert!(completion.failure.is_none()); + assert_eq!(submit_discovery.load(Ordering::SeqCst), 0); +} + +#[tokio::test] +async fn provider_reports_a_failed_scan_without_returning_stale_or_partial_records() { + let (results, submit_discovery) = run_fixture( + Arc::new(StaticSource(Err(ScanFailure::PackageKitUnavailable))), + PROVIDER_ID, + "linux", + ) + .await; + + let discovery = &results["discover"]; + assert_eq!(discovery.disposition, OperationDisposition::Failed as i32); + assert!(discovery.discovery.is_none()); + assert_eq!(discovery.failure.as_ref().unwrap().code, "unavailable"); + // The host keeps the previous successful records itself because this result carries none. + assert_eq!(submit_discovery.load(Ordering::SeqCst), 0); +} + +#[tokio::test] +async fn provider_validates_the_trusted_context_before_scanning() { + for (provider_id, platform) in [(PROVIDER_ID, "windows"), ("steam", "linux")] { + let (results, submit_discovery) = run_fixture( + Arc::new(StaticSource(Ok(vec![candidate( + "supertux", "SuperTux", "/usr/bin", + )]))), + provider_id, + platform, + ) + .await; + + let discovery = &results["discover"]; + assert_eq!( + discovery.disposition, + OperationDisposition::Failed as i32, + "{provider_id}/{platform} must be denied" + ); + assert!(discovery.discovery.is_none()); + assert_eq!(discovery.failure.as_ref().unwrap().code, "denied"); + assert_eq!(submit_discovery.load(Ordering::SeqCst), 0); + } +} diff --git a/crates/plugin-packagekit/src/linux/scan.rs b/crates/plugin-packagekit/src/linux/scan.rs new file mode 100644 index 000000000..862a3b3cf --- /dev/null +++ b/crates/plugin-packagekit/src/linux/scan.rs @@ -0,0 +1,659 @@ +//! Bounded, read-only discovery of installed packages that own game desktop entries. +//! +//! Two backends produce the same provider-local records: `pacman -Qqo` on Arch-family systems +//! and PackageKit's installed-file search elsewhere. Both backends are queried with argument-based +//! calls, bounded by a timeout, a candidate count and a record count. A backend that is missing or +//! fails returns a typed [`ScanFailure`]; a successful query with no owners returns an empty list. + +use std::{ + collections::BTreeMap, + env, fs, + path::{Path, PathBuf}, + time::Duration, +}; + +use async_trait::async_trait; +use futures_util::StreamExt; +use zbus::{Connection, Proxy, zvariant::OwnedObjectPath}; + +const OS_RELEASE: &str = "/etc/os-release"; +const PACMAN: &str = "pacman"; +/// Force the C locale so the unowned-file result is a stable, non-localized message. +const PACMAN_LOCALE: &str = "C"; +const DESKTOP_DIRECTORIES: [&str; 2] = ["/usr/share/applications", "/usr/local/share/applications"]; + +const PACKAGEKIT_SERVICE: &str = "org.freedesktop.PackageKit"; +const PACKAGEKIT_PATH: &str = "/org/freedesktop/PackageKit"; +const PACKAGEKIT_INTERFACE: &str = "org.freedesktop.PackageKit"; +const TRANSACTION_INTERFACE: &str = "org.freedesktop.PackageKit.Transaction"; +/// `PkFilterEnum::Installed` is enum position 2 in the PackageKit bitfield. +const FILTER_INSTALLED: u64 = 1 << 2; +/// `PkExitEnum::Success`. +const PACKAGEKIT_EXIT_SUCCESS: u32 = 1; + +/// Maximum records reported for one scan. The host also enforces its own limit. +pub(super) const MAX_RECORDS: usize = 4_096; +/// Maximum desktop entries inspected for one scan. +const MAX_DESKTOP_FILES: usize = 4_096; +/// Maximum files per PackageKit installed-file search. +const DESKTOP_SEARCH_BATCH: usize = 128; +/// Maximum D-Bus transaction messages consumed for one search. +const MAX_PACKAGEKIT_MESSAGES: usize = 65_536; +/// Per-file pacman ownership query budget. +const PACMAN_QUERY_TIMEOUT: Duration = Duration::from_secs(5); +/// Per-batch PackageKit transaction budget. +const PACKAGEKIT_QUERY_TIMEOUT: Duration = Duration::from_secs(20); + +/// A typed reason why a package scan produced no result. +/// +/// Every variant is a failure; an empty successful scan is `Ok(Vec::new())` instead. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum ScanFailure { + DesktopMetadata, + PacmanUnavailable, + PacmanFailed, + PacmanTimeout, + PacmanMalformed, + PackageKitUnavailable, + PackageKitFailed, + PackageKitTimeout, +} + +impl ScanFailure { + /// Stable machine-readable code for the plugin log and the host failure path. + pub(super) fn code(self) -> &'static str { + match self { + Self::DesktopMetadata => "desktop_metadata_failed", + Self::PacmanUnavailable => "pacman_unavailable", + Self::PacmanFailed => "pacman_query_failed", + Self::PacmanTimeout => "pacman_query_timeout", + Self::PacmanMalformed => "pacman_invalid_output", + Self::PackageKitUnavailable => "packagekit_unavailable", + Self::PackageKitFailed => "packagekit_query_failed", + Self::PackageKitTimeout => "packagekit_query_timeout", + } + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum PackageBackend { + Pacman, + PackageKit, +} + +impl PackageBackend { + /// Reads the distribution identity from an `/etc/os-release` body. + pub(super) fn for_os_release(os_release: &str) -> Self { + let mut id = ""; + let mut id_like = ""; + for line in os_release.lines() { + if let Some((key, value)) = line.split_once('=') { + match key { + "ID" => id = value.trim_matches('"').trim_matches('\''), + "ID_LIKE" => id_like = value.trim_matches('"').trim_matches('\''), + _ => {} + } + } + } + if id.eq_ignore_ascii_case("arch") + || id_like + .split_ascii_whitespace() + .any(|family| family.eq_ignore_ascii_case("arch")) + { + Self::Pacman + } else { + Self::PackageKit + } + } +} + +/// One candidate desktop entry: a visible Application in the Game category whose program exists. +#[derive(Clone, Debug)] +pub(super) struct DesktopEntry { + pub(super) path: PathBuf, + pub(super) name: Option, + pub(super) exec: String, + pub(super) binary: Option, +} + +/// A provider-local package record. The package name is the stable identity. +#[derive(Clone, Debug)] +pub(super) struct PackageCandidate { + pub(super) id: String, + pub(super) name: Option, + pub(super) install_dir: String, + pub(super) fields: BTreeMap, +} + +/// Scans the live system with the backend selected from `/etc/os-release`. +pub(super) async fn discover() -> Result, ScanFailure> { + let (os_release, entries) = tokio::task::spawn_blocking(read_system_inputs) + .await + .map_err(|_| ScanFailure::DesktopMetadata)?; + match PackageBackend::for_os_release(&os_release) { + PackageBackend::Pacman => scan_pacman(&SystemPacman, &entries, PACMAN_QUERY_TIMEOUT).await, + PackageBackend::PackageKit => { + let client = SystemPackageKit::connect().await?; + scan_packagekit(&client, &entries, PACKAGEKIT_QUERY_TIMEOUT).await + } + } +} + +/// Reads `/etc/os-release` and the bounded desktop-entry set on a blocking worker. +fn read_system_inputs() -> (String, Vec) { + let os_release = fs::read_to_string(OS_RELEASE).unwrap_or_default(); + (os_release, read_game_desktop_entries()) +} + +/// Queries pacman ownership for every candidate entry. +pub(super) async fn scan_pacman( + runner: &dyn PacmanRunner, + entries: &[DesktopEntry], + timeout: Duration, +) -> Result, ScanFailure> { + let mut records = BTreeMap::::new(); + for entry in entries { + let owner = tokio::time::timeout(timeout, runner.owner(&entry.path)) + .await + .map_err(|_| ScanFailure::PacmanTimeout)??; + let Some(package_id) = owner else { continue }; + let Some(candidate) = candidate_from_desktop(&package_id, entry, "pacman") else { + continue; + }; + records.entry(candidate.id.clone()).or_insert(candidate); + if records.len() >= MAX_RECORDS { + break; + } + } + Ok(records.into_values().collect()) +} + +/// One `pacman -Qqo` ownership query. +#[async_trait] +pub(super) trait PacmanRunner: Send + Sync { + /// Returns the owning package, `None` when no installed package owns the file, or a typed + /// failure when pacman is missing or the query failed. + async fn owner(&self, path: &Path) -> Result, ScanFailure>; +} + +pub(super) struct SystemPacman; + +#[async_trait] +impl PacmanRunner for SystemPacman { + async fn owner(&self, path: &Path) -> Result, ScanFailure> { + // Fixed executable, argument-based arguments and a fixed locale: no shell is involved and + // the desktop file path is never interpreted as syntax. + let output = tokio::process::Command::new(PACMAN) + .arg("-Qqo") + .arg("--") + .arg(path) + .env("LC_ALL", PACMAN_LOCALE) + .env("LANG", PACMAN_LOCALE) + .stdin(std::process::Stdio::null()) + .kill_on_drop(true) + .output() + .await + .map_err(|_| ScanFailure::PacmanUnavailable)?; + if !output.status.success() { + let error = String::from_utf8_lossy(&output.stderr); + return if error.contains("No package owns") { + Ok(None) + } else { + Err(ScanFailure::PacmanFailed) + }; + } + parse_package_owner(&output.stdout) + } +} + +/// Parses a single package name from `pacman -Qqo` output. +pub(super) fn parse_package_owner(output: &[u8]) -> Result, ScanFailure> { + let text = String::from_utf8(output.to_vec()).map_err(|_| ScanFailure::PacmanMalformed)?; + let mut lines = text.lines().filter(|line| !line.trim().is_empty()); + let Some(package_id) = lines.next() else { + return Ok(None); + }; + if lines.next().is_some() { + return Ok(None); + } + let package_id = package_id.trim(); + if package_id.len() > 256 || package_id.chars().any(char::is_control) { + return Ok(None); + } + Ok(Some(package_id.to_owned())) +} + +/// Queries PackageKit installed-file ownership for every candidate entry. +pub(super) async fn scan_packagekit( + query: &dyn InstalledFileQuery, + entries: &[DesktopEntry], + timeout: Duration, +) -> Result, ScanFailure> { + if entries.is_empty() { + return Ok(Vec::new()); + } + let desktop_paths = entries + .iter() + .map(|entry| entry.path.to_string_lossy().into_owned()) + .collect::>(); + let rows = search_installed_files(query, &desktop_paths, timeout).await?; + Ok(records_from_rows(entries, rows, "packagekit")) +} + +/// One PackageKit installed-file search. +#[async_trait] +pub(super) trait InstalledFileQuery: Send + Sync { + async fn search_installed_files( + &self, + filter: u64, + files: Vec, + ) -> Result, ScanFailure>; +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(super) struct PackageRow { + pub(super) package_id: String, + pub(super) summary: String, +} + +/// Runs bounded installed-filter searches in batches, refusing more than [`MAX_RECORDS`] rows. +pub(super) async fn search_installed_files( + query: &dyn InstalledFileQuery, + desktop_paths: &[String], + timeout: Duration, +) -> Result, ScanFailure> { + let mut rows = Vec::new(); + for batch in desktop_paths.chunks(DESKTOP_SEARCH_BATCH) { + let found = tokio::time::timeout( + timeout, + query.search_installed_files(FILTER_INSTALLED, batch.to_vec()), + ) + .await + .map_err(|_| ScanFailure::PackageKitTimeout)??; + rows.extend(found); + if rows.len() >= MAX_RECORDS { + rows.truncate(MAX_RECORDS); + break; + } + } + Ok(rows) +} + +pub(super) struct SystemPackageKit { + connection: Connection, + timeout: Duration, +} + +impl SystemPackageKit { + pub(super) async fn connect() -> Result { + let connection = Connection::system() + .await + .map_err(|_| ScanFailure::PackageKitUnavailable)?; + Ok(Self { + connection, + timeout: PACKAGEKIT_QUERY_TIMEOUT, + }) + } + + async fn create_transaction(&self) -> Result { + let root = Proxy::new( + &self.connection, + PACKAGEKIT_SERVICE, + PACKAGEKIT_PATH, + PACKAGEKIT_INTERFACE, + ) + .await + .map_err(|_| ScanFailure::PackageKitFailed)?; + root.call("CreateTransaction", &()) + .await + .map_err(|_| ScanFailure::PackageKitFailed) + } + + async fn transaction_call( + &self, + transaction: &OwnedObjectPath, + method: &'static str, + ) -> Result<(), ScanFailure> { + let proxy = Proxy::new( + &self.connection, + PACKAGEKIT_SERVICE, + transaction.clone(), + TRANSACTION_INTERFACE, + ) + .await + .map_err(|_| ScanFailure::PackageKitFailed)?; + proxy + .call::<_, _, ()>(method, &()) + .await + .map_err(|_| ScanFailure::PackageKitFailed) + } + + async fn search( + &self, + transaction: &OwnedObjectPath, + filter: u64, + files: Vec, + ) -> Result, ScanFailure> { + let proxy = Proxy::new( + &self.connection, + PACKAGEKIT_SERVICE, + transaction.clone(), + TRANSACTION_INTERFACE, + ) + .await + .map_err(|_| ScanFailure::PackageKitFailed)?; + let mut packages = proxy + .receive_signal("Package") + .await + .map_err(|_| ScanFailure::PackageKitFailed)?; + let mut finished = proxy + .receive_signal("Finished") + .await + .map_err(|_| ScanFailure::PackageKitFailed)?; + proxy + .call_method("SearchFiles", &(filter, files)) + .await + .map_err(|_| ScanFailure::PackageKitFailed)?; + let mut rows = Vec::new(); + let mut messages = 0usize; + loop { + // A signal flood is a broken or hostile backend, not a truncated success. + if messages >= MAX_PACKAGEKIT_MESSAGES { + return Err(ScanFailure::PackageKitFailed); + } + messages += 1; + // Stop collecting at the record bound; the transaction is dropped with the proxy. + if rows.len() >= MAX_RECORDS { + break; + } + tokio::select! { + biased; + message = packages.next() => { + // Only a `Finished` signal completes a PackageKit transaction. + let Some(message) = message else { + return Err(ScanFailure::PackageKitFailed); + }; + if let Ok((_, package_id, summary)) = + message.body().deserialize::<(u32, String, String)>() + && package_id.contains(';') + { + rows.push(PackageRow { package_id, summary }); + } + } + message = finished.next() => { + let Some(message) = message else { + return Err(ScanFailure::PackageKitFailed); + }; + let (exit, _runtime) = message + .body() + .deserialize::<(u32, u32)>() + .map_err(|_| ScanFailure::PackageKitFailed)?; + if exit != PACKAGEKIT_EXIT_SUCCESS { + return Err(ScanFailure::PackageKitFailed); + } + break; + } + } + } + Ok(rows) + } +} + +#[async_trait] +impl InstalledFileQuery for SystemPackageKit { + async fn search_installed_files( + &self, + filter: u64, + files: Vec, + ) -> Result, ScanFailure> { + let transaction = self.create_transaction().await?; + match tokio::time::timeout(self.timeout, self.search(&transaction, filter, files)).await { + Ok(result) => result, + Err(_) => { + // The transaction is still open in PackageKit; cancel it on a best-effort basis + // so a stalled backend does not leave an idle transaction behind. + let _ = self.transaction_call(&transaction, "Cancel").await; + Err(ScanFailure::PackageKitTimeout) + } + } + } +} + +/// Maps PackageKit rows to provider records, keeping the first record per package name. +fn records_from_rows( + entries: &[DesktopEntry], + rows: Vec, + package_manager: &str, +) -> Vec { + let mut records = BTreeMap::::new(); + for row in rows { + let Some(package_name) = normalized_package_name(&row.package_id) else { + continue; + }; + for entry in entries + .iter() + .filter(|entry| package_id_has_desktop(package_name, &entry.path, &entry.exec)) + { + let Some(binary) = entry.binary.as_ref() else { + continue; + }; + records + .entry(package_name.to_owned()) + .or_insert_with(|| PackageCandidate { + id: package_name.to_owned(), + name: entry + .name + .clone() + .or_else(|| (!row.summary.is_empty()).then(|| row.summary.clone())), + install_dir: parent_dir(binary), + fields: BTreeMap::from([ + ("package_id".to_owned(), row.package_id.clone()), + ("package_manager".to_owned(), package_manager.to_owned()), + ( + "desktop_file".to_owned(), + entry.path.to_string_lossy().into_owned(), + ), + ( + "executable".to_owned(), + binary.to_string_lossy().into_owned(), + ), + ]), + }); + } + if records.len() >= MAX_RECORDS { + break; + } + } + records.into_values().collect() +} + +/// Normalizes a PackageKit package id such as `supertux;0.6.3-4;x86_64;installed`. +pub(super) fn normalized_package_name(package_id: &str) -> Option<&str> { + let name = package_id.split(';').next()?.trim(); + (!name.is_empty() + && name.len() <= 256 + && !name.chars().any(char::is_control) + && !name.contains('/')) + .then_some(name) +} + +/// Builds a record from a pacman owner and its desktop entry without executing the entry. +pub(super) fn candidate_from_desktop( + package_id: &str, + entry: &DesktopEntry, + package_manager: &str, +) -> Option { + let binary = entry.binary.as_ref()?; + Some(PackageCandidate { + id: package_id.to_owned(), + name: entry.name.clone(), + install_dir: parent_dir(binary), + fields: BTreeMap::from([ + ("package_id".to_owned(), package_id.to_owned()), + ( + "desktop_file".to_owned(), + entry.path.to_string_lossy().into_owned(), + ), + ( + "executable".to_owned(), + binary.to_string_lossy().into_owned(), + ), + ("package_manager".to_owned(), package_manager.to_owned()), + ]), + }) +} + +fn parent_dir(binary: &Path) -> String { + binary + .parent() + .unwrap_or(binary) + .to_string_lossy() + .into_owned() +} + +/// Reads bounded visible Game desktop entries from the system application directories. +fn read_game_desktop_entries() -> Vec { + let mut entries = Vec::new(); + for directory in DESKTOP_DIRECTORIES { + let Ok(files) = fs::read_dir(directory) else { + continue; + }; + for file in files + .flatten() + .take(MAX_DESKTOP_FILES.saturating_sub(entries.len())) + { + if !file + .path() + .extension() + .is_some_and(|extension| extension == "desktop") + { + continue; + } + let Ok(text) = fs::read_to_string(file.path()) else { + continue; + }; + let Some(entry) = parse_game_desktop_entry(file.path(), &text) else { + continue; + }; + // An entry whose program does not exist is never a game candidate. + if entry.binary.is_none() { + continue; + } + entries.push(entry); + if entries.len() >= MAX_DESKTOP_FILES { + break; + } + } + } + entries +} + +/// Parses one desktop entry, keeping only visible Game applications with a resolvable program. +pub(super) fn parse_game_desktop_entry(path: PathBuf, text: &str) -> Option { + let mut in_entry = false; + let mut entry_type = None; + let mut name = None; + let mut exec = None; + let mut categories = String::new(); + let mut no_display = false; + for line in text.lines() { + let line = line.trim(); + if line.starts_with('[') { + in_entry = line == "[Desktop Entry]"; + continue; + } + if !in_entry || line.is_empty() || line.starts_with('#') { + continue; + } + if let Some((key, value)) = line.split_once('=') { + match key { + "Type" => entry_type = Some(value), + "Name" => name = Some(value.to_owned()), + "Exec" => exec = Some(value.to_owned()), + "Categories" => categories = value.to_owned(), + "NoDisplay" => no_display = value.eq_ignore_ascii_case("true"), + _ => {} + } + } + } + let is_game = categories + .split(';') + .any(|category| category.eq_ignore_ascii_case("game")); + if entry_type != Some("Application") || !is_game || no_display { + return None; + } + let exec = exec?; + let binary = resolve_exec(&exec); + Some(DesktopEntry { + path, + name, + exec, + binary, + }) +} + +/// Associates a normalized package name with a desktop entry by file stem or program name. +fn package_id_has_desktop(package_name: &str, desktop_path: &Path, exec: &str) -> bool { + let desktop_stem = desktop_path + .file_stem() + .and_then(|value| value.to_str()) + .unwrap_or_default(); + let executable = exec_program(exec).unwrap_or_default(); + let executable = Path::new(&executable) + .file_name() + .and_then(|value| value.to_str()) + .unwrap_or_default(); + desktop_stem == package_name + || desktop_stem + .strip_prefix(package_name) + .is_some_and(|suffix| { + suffix.starts_with('-') || suffix.chars().all(|ch| ch.is_ascii_digit()) + }) + || executable == package_name + || executable + .strip_prefix(package_name) + .is_some_and(|suffix| suffix.chars().all(|ch| ch.is_ascii_digit())) +} + +/// Tokenizes only the program of a desktop `Exec` value. +/// +/// Shell syntax is never interpreted and field codes are rejected, so a desktop file cannot +/// influence a command line or an executable action. +pub(super) fn exec_program(exec: &str) -> Option { + if exec.len() > 8_192 { + return None; + } + let mut chars = exec.trim_start().chars(); + let mut program = String::new(); + let mut quoted = false; + while let Some(ch) = chars.next() { + match ch { + '"' => quoted = !quoted, + '\\' => { + let escaped = chars.next()?; + if quoted && !matches!(escaped, '"' | '`' | '$' | '\\') { + return None; + } + program.push(escaped); + } + ch if ch.is_whitespace() && !quoted => break, + '%' => return None, + ch => program.push(ch), + } + } + (!quoted && !program.is_empty()).then_some(program) +} + +/// Resolves the program to an existing file without ever running it. +pub(super) fn resolve_exec(exec: &str) -> Option { + let executable = exec_program(exec)?; + let candidate = PathBuf::from(&executable); + if candidate.is_absolute() { + return candidate.is_file().then_some(candidate); + } + env::var_os("PATH")? + .to_string_lossy() + .split(':') + .map(|directory| PathBuf::from(directory).join(&executable)) + .find(|path| path.is_file()) +} diff --git a/crates/plugin-packagekit/src/main.rs b/crates/plugin-packagekit/src/main.rs index 9e3984798..3733b274e 100644 --- a/crates/plugin-packagekit/src/main.rs +++ b/crates/plugin-packagekit/src/main.rs @@ -1,658 +1,5 @@ #[cfg(target_os = "linux")] -mod linux { - use std::{collections::BTreeMap, env, fs, path::PathBuf, sync::Arc, time::Duration}; - - use futures_util::StreamExt; - use gamenode_plugin_protocol::{capability, proto::*}; - use gamenode_plugin_sdk::{Error, HostClient, Launch, ProviderPlugin, Session}; - use zbus::{Connection, Proxy, zvariant::OwnedObjectPath}; - - const PLUGIN_ID: &str = "org.gamenode.plugin.packagekit-discovery"; - const PACKAGEKIT_SERVICE: &str = "org.freedesktop.PackageKit"; - const PACKAGEKIT_PATH: &str = "/org/freedesktop/PackageKit"; - const PACKAGEKIT_INTERFACE: &str = "org.freedesktop.PackageKit"; - const TRANSACTION_INTERFACE: &str = "org.freedesktop.PackageKit.Transaction"; - // PkFilterEnum::Installed is enum position 2 in the PackageKit bitfield. - const FILTER_INSTALLED: u64 = 1 << 2; - const MAX_DESKTOP_FILES: usize = 4_096; - const DESKTOP_SEARCH_BATCH: usize = 128; - - pub(super) async fn run() -> Result<(), &'static str> { - let _ = tracing_subscriber::fmt() - .with_env_filter("warn") - .with_writer(std::io::stderr) - .try_init(); - let launch = Launch::from_env().map_err(|_| "invalid_launch_configuration")?; - let session = Session::open( - launch, - PLUGIN_ID, - "packagekit", - env!("CARGO_PKG_VERSION"), - &[capability::CONTEXT, capability::DISCOVERY], - ) - .await - .map_err(|_| "provider_session_unavailable")?; - gamenode_plugin_sdk::run(session, Arc::new(PackageManagerPlugin)) - .await - .map_err(|_| "provider_session_failed") - } - - struct PackageManagerPlugin; - - #[async_trait::async_trait] - impl ProviderPlugin for PackageManagerPlugin { - async fn handle( - &self, - command: ProviderCommand, - host: HostClient, - ) -> Result { - let operation = - ProviderOperation::try_from(command.operation).map_err(|_| Error::Protocol)?; - match operation { - ProviderOperation::Initialize => Ok(OperationResult { - disposition: OperationDisposition::Completed as i32, - ..Default::default() - }), - ProviderOperation::Discover => { - let context = host.provider_context().await?; - if context.provider_id != "packagekit" || context.platform != "linux" { - return Err(Error::Denied); - } - let candidates = - tokio::time::timeout(Duration::from_secs(60), scan_package_manager()) - .await - .map_err(|_| Error::Unavailable)? - .map_err(|failure| { - tracing::warn!(failure, "Linux package discovery failed"); - Error::Unavailable - })?; - Ok(OperationResult { - disposition: OperationDisposition::Completed as i32, - discovery: Some(DiscoveryResult { - provider_id: "packagekit".to_owned(), - records: candidates - .into_iter() - .map(|record| DiscoveryRecord { - id: record.id, - name: record.name.unwrap_or_default(), - install_dir: record.install_dir, - fields: record.fields.into_iter().collect(), - }) - .collect(), - // Packages have no store install location or library folders. - ..Default::default() - }), - ..Default::default() - }) - } - _ => Err(Error::Denied), - } - } - } - - #[derive(Clone, Copy, Debug, PartialEq, Eq)] - enum PackageBackend { - Pacman, - PackageKit, - } - - impl PackageBackend { - fn for_os_release(os_release: &str) -> Self { - let mut id = ""; - let mut id_like = ""; - for line in os_release.lines() { - if let Some((key, value)) = line.split_once('=') { - match key { - "ID" => id = value.trim_matches('"').trim_matches('\''), - "ID_LIKE" => id_like = value.trim_matches('"').trim_matches('\''), - _ => {} - } - } - } - if id.eq_ignore_ascii_case("arch") - || id_like - .split_ascii_whitespace() - .any(|family| family.eq_ignore_ascii_case("arch")) - { - Self::Pacman - } else { - Self::PackageKit - } - } - } - - async fn scan_package_manager() -> Result, &'static str> { - let (os_release, desktop_entries) = tokio::task::spawn_blocking(|| { - let os_release = fs::read_to_string("/etc/os-release").unwrap_or_default(); - let desktop_entries = read_game_desktop_entries()?; - Ok::<_, &'static str>((os_release, desktop_entries)) - }) - .await - .map_err(|_| "desktop_metadata_failed")??; - match PackageBackend::for_os_release(&os_release) { - PackageBackend::Pacman => scan_pacman(desktop_entries).await, - PackageBackend::PackageKit => scan_packagekit(desktop_entries).await, - } - } - - async fn scan_pacman( - desktop_entries: Vec, - ) -> Result, &'static str> { - let mut records = BTreeMap::::new(); - for entry in desktop_entries { - let output = tokio::process::Command::new("pacman") - .args(["-Qqo"]) - .arg(&entry.path) - .env("LC_ALL", "C") - .output() - .await - .map_err(|_| "pacman_unavailable")?; - if !output.status.success() { - let error = String::from_utf8_lossy(&output.stderr); - if error.contains("No package owns") { - continue; - } - return Err("pacman_query_failed"); - } - let Some(package_id) = parse_package_owner(&output.stdout)? else { - continue; - }; - let Some(candidate) = candidate_from_desktop(&package_id, &entry, "pacman") else { - continue; - }; - records.entry(candidate.id.clone()).or_insert(candidate); - } - Ok(records.into_values().collect()) - } - - async fn scan_packagekit( - desktop_entries: Vec, - ) -> Result, &'static str> { - let connection = Connection::system() - .await - .map_err(|_| "packagekit_unavailable")?; - let desktop_paths = desktop_entries - .iter() - .map(|entry| entry.path.to_string_lossy().into_owned()) - .collect::>(); - if desktop_paths.is_empty() { - return Ok(Vec::new()); - } - let package_rows = search_installed_files(&desktop_paths, |filter, files| { - let connection = &connection; - async move { - transaction_packages(connection, "SearchFiles", &(filter, files)) - .await - .map_err(|_| "packagekit_query_failed") - } - }) - .await?; - let by_path = desktop_entries - .into_iter() - .map(|entry| (entry.path.to_string_lossy().into_owned(), entry)) - .collect::>(); - let mut records = BTreeMap::::new(); - for (package_id, summary) in package_rows { - let Some(package_name) = normalized_package_name(&package_id) else { - continue; - }; - for entry in by_path - .values() - .filter(|entry| package_id_has_desktop(package_name, &entry.path, &entry.exec)) - { - if let Some(binary) = resolve_exec(&entry.exec) { - records - .entry(package_name.to_owned()) - .or_insert_with(|| PackageCandidate { - id: package_name.to_owned(), - name: entry - .name - .clone() - .or_else(|| (!summary.is_empty()).then_some(summary.clone())), - install_dir: binary - .parent() - .unwrap_or(&binary) - .to_string_lossy() - .into_owned(), - fields: BTreeMap::from([ - ("package_id".to_owned(), package_id.clone()), - ("package_manager".to_owned(), "packagekit".to_owned()), - ( - "desktop_file".to_owned(), - entry.path.to_string_lossy().into_owned(), - ), - ( - "executable".to_owned(), - binary.to_string_lossy().into_owned(), - ), - ]), - }); - } - } - } - Ok(records.into_values().collect()) - } - - async fn search_installed_files( - desktop_paths: &[String], - mut query: F, - ) -> Result, &'static str> - where - F: FnMut(u64, Vec) -> Fut, - Fut: std::future::Future, &'static str>>, - { - let mut rows = Vec::new(); - for batch in desktop_paths.chunks(DESKTOP_SEARCH_BATCH) { - rows.extend(query(FILTER_INSTALLED, batch.to_vec()).await?); - } - Ok(rows) - } - - async fn transaction_packages( - connection: &Connection, - method: &str, - body: &B, - ) -> zbus::Result> - where - B: serde::Serialize + zbus::zvariant::DynamicType, - { - let root = Proxy::new( - connection, - PACKAGEKIT_SERVICE, - PACKAGEKIT_PATH, - PACKAGEKIT_INTERFACE, - ) - .await?; - let transaction: OwnedObjectPath = root.call("CreateTransaction", &()).await?; - let proxy = Proxy::new( - connection, - PACKAGEKIT_SERVICE, - transaction, - TRANSACTION_INTERFACE, - ) - .await?; - let mut packages = proxy.receive_signal("Package").await?; - let mut finished = proxy.receive_signal("Finished").await?; - proxy.call_method(method, body).await?; - let mut result = Vec::new(); - loop { - tokio::select! { - biased; - message = packages.next() => { - let Some(message) = message else { break }; - if let Ok((_, package_id, summary)) = message.body().deserialize::<(u32, String, String)>() - && package_id.contains(';') { - result.push((package_id, summary)); - } - } - message = finished.next() => { - let Some(message) = message else { break }; - let (exit, _runtime) = message.body().deserialize::<(u32, u32)>()?; - if exit != 1 { return Err(zbus::Error::Failure("PackageKit transaction failed".to_owned())); } - break; - } - } - } - Ok(result) - } - - struct DesktopEntry { - path: PathBuf, - name: Option, - exec: String, - } - - fn read_game_desktop_entries() -> Result, &'static str> { - let directories = ["/usr/share/applications", "/usr/local/share/applications"]; - let mut entries = Vec::new(); - for directory in directories { - let Ok(files) = fs::read_dir(directory) else { - continue; - }; - for file in files - .flatten() - .take(MAX_DESKTOP_FILES.saturating_sub(entries.len())) - { - if !file - .path() - .extension() - .is_some_and(|extension| extension == "desktop") - { - continue; - } - let Ok(text) = fs::read_to_string(file.path()) else { - continue; - }; - let Some(entry) = parse_game_desktop_entry(file.path(), &text) else { - continue; - }; - entries.push(entry); - if entries.len() >= MAX_DESKTOP_FILES { - break; - } - } - } - Ok(entries) - } - - fn parse_game_desktop_entry(path: PathBuf, text: &str) -> Option { - let mut in_entry = false; - let mut entry_type = None; - let mut name = None; - let mut exec = None; - let mut categories = String::new(); - let mut no_display = false; - for line in text.lines() { - let line = line.trim(); - if line.starts_with('[') { - in_entry = line == "[Desktop Entry]"; - continue; - } - if !in_entry || line.is_empty() || line.starts_with('#') { - continue; - } - if let Some((key, value)) = line.split_once('=') { - match key { - "Type" => entry_type = Some(value), - "Name" => name = Some(value.to_owned()), - "Exec" => exec = Some(value.to_owned()), - "Categories" => categories = value.to_owned(), - "NoDisplay" => no_display = value.eq_ignore_ascii_case("true"), - _ => {} - } - } - } - let is_game = categories - .split(';') - .any(|category| category.eq_ignore_ascii_case("game")); - if entry_type != Some("Application") || !is_game || no_display { - return None; - } - Some(DesktopEntry { - path, - name, - exec: exec?, - }) - } - - fn package_id_has_desktop( - package_name: &str, - desktop_path: &std::path::Path, - exec: &str, - ) -> bool { - let desktop_stem = desktop_path - .file_stem() - .and_then(|value| value.to_str()) - .unwrap_or_default(); - let executable = exec_program(exec).unwrap_or_default(); - let executable = std::path::Path::new(&executable) - .file_name() - .and_then(|value| value.to_str()) - .unwrap_or_default(); - desktop_stem == package_name - || desktop_stem - .strip_prefix(package_name) - .is_some_and(|suffix| { - suffix.starts_with('-') || suffix.chars().all(|ch| ch.is_ascii_digit()) - }) - || executable == package_name - || executable - .strip_prefix(package_name) - .is_some_and(|suffix| suffix.chars().all(|ch| ch.is_ascii_digit())) - } - - // Only tokenize the program, never interpret shell syntax or expand fields. - // Desktop Entry Exec is bounded by the already bounded desktop-file read. - fn exec_program(exec: &str) -> Option { - if exec.len() > 8_192 { - return None; - } - let mut chars = exec.trim_start().chars(); - let mut program = String::new(); - let mut quoted = false; - while let Some(ch) = chars.next() { - match ch { - '"' => quoted = !quoted, - '\\' => { - let escaped = chars.next()?; - if quoted && !matches!(escaped, '"' | '`' | '$' | '\\') { - return None; - } - program.push(escaped); - } - ch if ch.is_whitespace() && !quoted => break, - '%' => return None, - ch => program.push(ch), - } - } - (!quoted && !program.is_empty()).then_some(program) - } - - fn resolve_exec(exec: &str) -> Option { - let executable = exec_program(exec)?; - let candidate = PathBuf::from(&executable); - if candidate.is_absolute() && candidate.is_file() { - return Some(candidate); - } - env::var_os("PATH")? - .to_string_lossy() - .split(':') - .map(|directory| PathBuf::from(directory).join(&executable)) - .find(|path| path.is_file()) - } - - struct PackageCandidate { - id: String, - name: Option, - install_dir: String, - fields: BTreeMap, - } - - fn parse_package_owner(output: &[u8]) -> Result, &'static str> { - let package_id = String::from_utf8(output.to_vec()) - .map_err(|_| "pacman_invalid_output")? - .trim() - .to_owned(); - if package_id.is_empty() - || package_id.len() > 256 - || package_id.chars().any(char::is_control) - { - return Ok(None); - } - Ok(Some(package_id)) - } - - fn normalized_package_name(package_id: &str) -> Option<&str> { - let name = package_id.split(';').next()?.trim(); - (!name.is_empty() - && name.len() <= 256 - && !name.chars().any(char::is_control) - && !name.contains('/')) - .then_some(name) - } - - fn candidate_from_desktop( - package_id: &str, - entry: &DesktopEntry, - package_manager: &str, - ) -> Option { - let binary = resolve_exec(&entry.exec)?; - Some(PackageCandidate { - id: package_id.to_owned(), - name: entry.name.clone(), - install_dir: binary - .parent() - .unwrap_or(&binary) - .to_string_lossy() - .into_owned(), - fields: BTreeMap::from([ - ("package_id".to_owned(), package_id.to_owned()), - ( - "desktop_file".to_owned(), - entry.path.to_string_lossy().into_owned(), - ), - ( - "executable".to_owned(), - binary.to_string_lossy().into_owned(), - ), - ("package_manager".to_owned(), package_manager.to_owned()), - ]), - }) - } - - #[cfg(test)] - mod tests { - #[tokio::test] - async fn desktop_search_queries_only_installed_packages_in_bounded_batches() { - let paths = (0..130) - .map(|i| format!("/usr/share/applications/game-{i}.desktop")) - .collect::>(); - let mut calls = Vec::new(); - let rows = super::search_installed_files(&paths, |filter, files| { - calls.push((filter, files)); - std::future::ready(Ok(vec![("game;1;x86_64;installed".into(), "Game".into())])) - }) - .await - .unwrap(); - assert_eq!(calls.len(), 2); - // PackageKit's Installed enum has ordinal 2, so the wire bitfield is 4. - assert!(calls.iter().all(|(filter, _)| *filter == 4)); - assert_eq!(calls[0].1.len(), 128); - assert_eq!(calls[1].1.len(), 2); - assert_eq!( - calls - .into_iter() - .flat_map(|(_, files)| files) - .collect::>(), - paths - ); - assert_eq!(rows.len(), 2); - } - - use super::{ - DesktopEntry, PackageBackend, candidate_from_desktop, normalized_package_name, - parse_game_desktop_entry, parse_package_owner, - }; - use std::{collections::BTreeMap, path::PathBuf}; - - #[test] - fn quoted_exec_program_with_spaces_is_discovered_without_interpreting_arguments() { - let dir = tempfile::tempdir().unwrap(); - let program = dir.path().join("Game With Spaces"); - std::fs::write(&program, b"fixture").unwrap(); - let exec = format!("\"{}\" --fullscreen %U", program.display()); - assert_eq!(super::resolve_exec(&exec), Some(program)); - assert!(super::exec_program("\"unterminated path").is_none()); - assert!(super::exec_program("game\\").is_none()); - assert!(super::exec_program("%f --game").is_none()); - assert!(super::exec_program(&"a".repeat(8_193)).is_none()); - assert_eq!( - super::exec_program("\"game\\\"name\" %U").as_deref(), - Some("game\"name") - ); - } - - #[test] - fn selects_pacman_for_arch_and_arch_derivatives() { - assert_eq!( - PackageBackend::for_os_release("ID=arch\n"), - PackageBackend::Pacman - ); - assert_eq!( - PackageBackend::for_os_release("ID=manjaro\nID_LIKE=arch\n"), - PackageBackend::Pacman - ); - } - - #[test] - fn selects_packagekit_for_other_or_unknown_distributions() { - assert_eq!( - PackageBackend::for_os_release("ID=fedora\nID_LIKE=redhat\n"), - PackageBackend::PackageKit - ); - assert_eq!( - PackageBackend::for_os_release(""), - PackageBackend::PackageKit - ); - } - - #[test] - fn pacman_owner_output_accepts_package_and_skips_empty_or_malformed_values() { - assert_eq!( - parse_package_owner(b"supertux\n").unwrap(), - Some("supertux".to_owned()) - ); - assert_eq!(parse_package_owner(b"\n").unwrap(), None); - assert_eq!(parse_package_owner(b"bad\nname\n").unwrap(), None); - assert_eq!(parse_package_owner(&[0xff]), Err("pacman_invalid_output")); - } - - #[test] - fn packagekit_ids_normalize_to_the_same_package_name_as_pacman() { - assert_eq!( - normalized_package_name("supertux;0.6.3-4;x86_64;installed"), - Some("supertux") - ); - assert_eq!(normalized_package_name("supertux"), Some("supertux")); - assert_eq!(normalized_package_name(";1.0;x86_64;installed"), None); - assert_eq!(normalized_package_name("bad/name;1.0;arch;installed"), None); - } - - #[test] - fn game_desktop_metadata_is_required_and_candidates_keep_package_identity() { - let desktop = parse_game_desktop_entry( - PathBuf::from("/usr/share/applications/supertux2.desktop"), - "[Desktop Entry]\nType=Application\nName=SuperTux\nExec=/usr/bin/true\nCategories=Game;\n", - ) - .unwrap(); - let candidate = candidate_from_desktop("supertux", &desktop, "pacman").unwrap(); - assert_eq!(candidate.id, "supertux"); - assert_eq!(candidate.name.as_deref(), Some("SuperTux")); - assert_eq!(candidate.fields["package_manager"], "pacman"); - - assert!(parse_game_desktop_entry( - PathBuf::from("/usr/share/applications/not-a-game.desktop"), - "[Desktop Entry]\nType=Application\nName=Text Editor\nExec=/usr/bin/true\nCategories=Utility;\n", - ) - .is_none()); - assert!(parse_game_desktop_entry( - PathBuf::from("/usr/share/applications/hidden.desktop"), - "[Desktop Entry]\nType=Application\nName=Hidden\nExec=/usr/bin/true\nCategories=Game;\nNoDisplay=true\n", - ) - .is_none()); - assert!( - parse_game_desktop_entry( - PathBuf::from("/usr/share/applications/malformed.desktop"), - "not a desktop entry", - ) - .is_none() - ); - } - - #[test] - fn repeated_desktop_candidates_share_a_stable_package_id() { - let first = DesktopEntry { - path: PathBuf::from("/usr/share/applications/supertux2.desktop"), - name: Some("SuperTux".to_owned()), - exec: "/usr/bin/true".to_owned(), - }; - let second = DesktopEntry { - path: PathBuf::from("/usr/share/applications/supertux-editor.desktop"), - name: Some("SuperTux Editor".to_owned()), - exec: "/usr/bin/true".to_owned(), - }; - let mut candidates = BTreeMap::new(); - candidates - .entry("supertux".to_owned()) - .or_insert_with(|| candidate_from_desktop("supertux", &first, "pacman").unwrap()); - candidates - .entry("supertux".to_owned()) - .or_insert_with(|| candidate_from_desktop("supertux", &second, "pacman").unwrap()); - assert_eq!(candidates.len(), 1); - assert_eq!(candidates["supertux"].name.as_deref(), Some("SuperTux")); - } - } -} +mod linux; #[cfg(target_os = "linux")] #[tokio::main] diff --git a/crates/plugin-protocol/Cargo.toml b/crates/plugin-protocol/Cargo.toml index 7fc92f024..2572b88b6 100644 --- a/crates/plugin-protocol/Cargo.toml +++ b/crates/plugin-protocol/Cargo.toml @@ -1,12 +1,14 @@ [package] name = "gamenode-plugin-protocol" description = "Versioned local protocol shared by GameNode Desktop and plugin processes" +documentation = "https://docs.rs/gamenode-plugin-protocol" +repository = "https://github.com/game-node-app/game-node-desktop" version.workspace = true edition.workspace = true rust-version.workspace = true -license.workspace = true +license = "MIT" authors.workspace = true -publish.workspace = true +publish = ["crates-io"] build = "build.rs" [lints] @@ -14,9 +16,12 @@ workspace = true [dependencies] prost = "0.14" +prost-types = "0.14" tonic = { version = "0.14", features = ["transport"] } tonic-prost = "0.14" serde.workspace = true +serde_json.workspace = true +sha2 = "0.10.9" thiserror.workspace = true url.workspace = true @@ -24,6 +29,3 @@ url.workspace = true tonic-prost-build = "0.14" prost-build = "0.14" protoc-bin-vendored = "3" - -[dev-dependencies] -serde_json.workspace = true diff --git a/crates/plugin-protocol/LICENSE b/crates/plugin-protocol/LICENSE new file mode 100644 index 000000000..41bac266d --- /dev/null +++ b/crates/plugin-protocol/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 GameNode contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/crates/plugin-protocol/build.rs b/crates/plugin-protocol/build.rs index 6288ebdca..68c83517e 100644 --- a/crates/plugin-protocol/build.rs +++ b/crates/plugin-protocol/build.rs @@ -4,7 +4,17 @@ fn main() { // Build scripts execute on the build host, including during cross-compiles. // Do not mutate the process environment to select the compiler. config.protoc_executable(protoc_bin_vendored::protoc_bin_path().expect("bundled protoc")); + let protobuf_include = protoc_bin_vendored::include_path().expect("bundled protobuf includes"); + let descriptor_path = std::path::PathBuf::from(std::env::var_os("OUT_DIR").expect("OUT_DIR")) + .join("plugin_descriptor.bin"); + let includes = [ + "proto", + protobuf_include + .to_str() + .expect("protobuf include path is UTF-8"), + ]; tonic_prost_build::configure() + .file_descriptor_set_path(descriptor_path) .skip_debug([ ".gamenode.plugin.v1.OpenSessionRequest", ".gamenode.plugin.v1.SubmitDiscoveryRequest", @@ -15,6 +25,6 @@ fn main() { ".gamenode.plugin.v1.LoginReply", ".gamenode.plugin.v1.SettingsValue", ]) - .compile_with_config(config, &["proto/plugin.proto"], &["proto"]) + .compile_with_config(config, &["proto/plugin.proto"], &includes) .expect("compile GameNode Plugin API protobuf"); } diff --git a/crates/plugin-protocol/contracts/common_data_selector.json b/crates/plugin-protocol/contracts/common_data_selector.json new file mode 100644 index 000000000..55b8753a6 --- /dev/null +++ b/crates/plugin-protocol/contracts/common_data_selector.json @@ -0,0 +1,123 @@ +{ + "api": "1.6", + "field": { + "message": "ResourceRequest", + "name": "common_data_categories", + "number": 13, + "message_type": "CommonDataSelector", + "private_default": true, + "selected_record_ids": { + "message_type": "CommonDataSelector", + "number": 2, + "repeated": true, + "requires_per_record_grant": true + } + }, + "categories": [ + { + "name": "GAME_PATHS", + "number": 1, + "permission": "common.game_paths.read" + }, + { + "name": "GAME_PERFORMANCE_HISTORY", + "number": 2, + "permission": "common.game_performance_history.read" + }, + { + "name": "RUNTIME_CATALOG", + "number": 3, + "permission": "common.runtime_catalog.read" + }, + { + "name": "CONTENT_AVAILABILITY", + "number": 4, + "permission": "common.content_availability.read" + }, + { + "name": "LIBRARY_ROOTS", + "number": 5, + "permission": "library.roots.read" + }, + { + "name": "SAVE_PROFILES", + "number": 6, + "permission": "game.saves.read" + } + ], + "queries": [ + { + "id": "omitted", + "selector": "omitted", + "categories": [], + "selected_records": [], + "grants": [], + "record_grants": [], + "expected": "PRIVATE_ONLY" + }, + { + "id": "empty", + "selector": "present", + "categories": [], + "selected_records": [], + "grants": [], + "record_grants": [], + "expected": "PRIVATE_ONLY" + }, + { + "id": "explicit_category", + "selector": "present", + "categories": [ + "GAME_PERFORMANCE_HISTORY" + ], + "selected_records": [], + "grants": [ + "common.game_performance_history.read" + ], + "record_grants": [], + "expected": "COMMON_INCLUDED" + }, + { + "id": "category_without_grant", + "selector": "present", + "categories": [ + "CONTENT_AVAILABILITY" + ], + "selected_records": [], + "grants": [], + "record_grants": [], + "expected": "PERMISSION_DENIED" + }, + { + "id": "selected_record_without_category", + "selector": "present", + "categories": [], + "selected_records": [ + "runtime:one" + ], + "grants": [], + "record_grants": [ + "runtime:one" + ], + "expected": "COMMON_INCLUDED" + }, + { + "id": "selected_record_without_record_grant", + "selector": "present", + "categories": [], + "selected_records": [ + "runtime:one" + ], + "grants": [ + "common.runtime_catalog.read" + ], + "record_grants": [], + "expected": "PERMISSION_DENIED" + } + ], + "excluded_data": [ + "secrets", + "sensitive_data_without_review", + "custom_data_without_review" + ] +} diff --git a/crates/plugin-protocol/contracts/data_exchange_fixtures.json b/crates/plugin-protocol/contracts/data_exchange_fixtures.json new file mode 100644 index 000000000..4778238ad --- /dev/null +++ b/crates/plugin-protocol/contracts/data_exchange_fixtures.json @@ -0,0 +1,118 @@ +{ + "api": "1.6", + "note": "Shared producer/consumer fixture for the plugin examples. The host interprets the selected game, installation, computer context, units and sequence; source/tool names are descriptive. No value is a filesystem path or a collector claim.", + "performance": { + "series_id": "series-primary", + "game_id": "5", + "installation_id": "id-steam:1", + "computer_context_id": "active-host", + "projection_id": "performance.v1", + "runtime_id": "runtime:example", + "runtime_recipe_revision": "recipe-2", + "sample_interval_ms": 100, + "units": { + "fps": "frames/second", + "cpu": "percent", + "memory": "bytes" + }, + "cpu_scope": "process", + "cpu_normalization": "whole_machine_percent", + "memory_kind": "working_set_bytes", + "samples": [ + { + "sequence": 1, + "observed_at": 1760000000000, + "fps": 59.0, + "cpu_percent": 34.5, + "memory_bytes": 536870912 + }, + { + "sequence": 2, + "observed_at": 1760000000100, + "fps": 61.0, + "cpu_percent": 34.5, + "memory_bytes": 536870912 + } + ], + "average_fps": 60.0, + "metric_units": { + "fps": "frames/second", + "cpu_percent": "percent", + "memory_bytes": "bytes" + }, + "selector": "GAME_PERFORMANCE_HISTORY", + "private_default": "no records without an explicit selector", + "revoked": "empty result after revocation" + }, + "locations": { + "installation_id": "id-fixture:1", + "dimensions": ["availability", "volume", "capacity"], + "files": { + "GC/USA/card.gci": 4, + "states/s1.sav": 5 + }, + "size": { + "logical_bytes": 9, + "file_count": 2, + "directory_count": 3 + }, + "path_fields": ["mount_point", "relative_path"] + }, + "save_profiles": { + "installation_id": "id-fixture:1", + "runtime_id": "org.example.emulator", + "format_id": "gci", + "format_version": 2, + "name": "Example memory card", + "directories": [ + { + "display_name": "Memory card", + "naming_patterns": ["GC/**/*.gci"] + } + ], + "selector": "SAVE_PROFILES", + "shared_selector_outcome": "UNIMPLEMENTED" + }, + "runtime_catalog": { + "runtime_id": "runtime:example-snes", + "runtime_name": "Example SNES", + "runtime_version": "2.0", + "platform": "linux", + "supported_formats": ["snes-rom"], + "game_id": "5", + "installation_id": "id-steam:1", + "content_kind": "snes-rom", + "content_ids": ["rom:zelda", "rom:metroid"], + "selector": "RUNTIME_CATALOG", + "availability_selector": "CONTENT_AVAILABILITY", + "revoked": "PERMISSION_DENIED", + "executable_handle_in_shared_projection": "" + }, + "extension": { + "known_namespace": "org.example.runtime", + "known_schema_id": "org.example.runtime.v1", + "known_schema_version": 1, + "known_field": "display_family", + "known_value": "desktop", + "future_namespace": "org.vendor.future-runtime", + "future_schema_id": "org.vendor.future-runtime.v9", + "future_schema_version": 9, + "future_field": "new_hint", + "future_value": "preserve without parsing", + "custom_dataset_id": "org.example.game-notes", + "custom_schema_id": "org.example.game-notes.v2", + "custom_schema_version": 2, + "custom_fields": { + "game_key": "game:example", + "note": "remember controller layout" + }, + "opaque_dataset_id": "org.example.game-notes.binary", + "opaque_schema_id": "org.example.game-notes.binary.v1", + "opaque_schema_version": 1, + "opaque_bytes": [0, 1, 2, 255], + "opaque_grant_field": "opaque_payload", + "unsupported_schema_version": 10, + "unsupported_outcome": "INVALID_ARGUMENT", + "projection_paths": ["game_key"] + } +} diff --git a/crates/plugin-protocol/contracts/domain_host.json b/crates/plugin-protocol/contracts/domain_host.json new file mode 100644 index 000000000..6c88bd3e2 --- /dev/null +++ b/crates/plugin-protocol/contracts/domain_host.json @@ -0,0 +1,872 @@ +{ + "api": "1.6", + "source": "design.md sections 4 and 18", + "services": [ + "Computer", + "GamePerformance", + "GamePresence", + "Locations", + "Saves", + "StorageDiagnostics" + ], + "routes": [ + { + "route": "/gamenode.plugin.v1.Saves/ListProfiles", + "service": "Saves", + "method": "ListProfiles", + "request": "SaveProfileListRequest", + "response": "SaveProfileListReply", + "streaming": false, + "permission": "game.saves.read", + "operation_owner": "authorized save-profile reader", + "resource_owner": "host-owned source attribution; caller-owned writes; published foreign records require matching operation/scope grant", + "request_policy": "page and selected records", + "response_policy": "save-profile records, provenance, revisions, cursor", + "extension_or_opaque_policy": "Descriptive game/emulator metadata only; source paths remain scoped handles", + "access_model": "game.saves.read; own creator or category/selected-record grant; game scope", + "contract": { + "pagination": { + "supported": true, + "max_page_size": 200, + "cursor": "opaque and session scoped" + }, + "revision": { + "read": "response includes observed revision where available", + "mutation": "expected_revision required for existing resources; stale revisions return typed revision conflict" + }, + "idempotency": { + "required": false, + "key_scope": "authenticated plugin and method", + "retry": "same key returns original committed outcome" + }, + "quota": "method-specific result/page bounds; location traversal and report queries run as cancellable bounded jobs where required", + "commit_authorization": "recheck authenticated identity, named grant, record/category scope and grant revision immediately before mutation or stream delivery" + } + }, + { + "route": "/gamenode.plugin.v1.Saves/GetProfile", + "service": "Saves", + "method": "GetProfile", + "request": "SaveProfileGetRequest", + "response": "SaveProfileReply", + "streaming": false, + "permission": "game.saves.read", + "operation_owner": "authorized save-profile reader", + "resource_owner": "host-owned source attribution; caller-owned writes; published foreign records require matching operation/scope grant", + "request_policy": "profile id and selected-record selector", + "response_policy": "save-profile record, provenance, revision", + "extension_or_opaque_policy": "Descriptive game/emulator metadata only; source paths remain scoped handles", + "access_model": "game.saves.read; selected-record grant can work without category grant; game scope", + "contract": { + "pagination": { + "supported": false, + "max_page_size": 200, + "cursor": "opaque and session scoped" + }, + "revision": { + "read": "response includes observed revision where available", + "mutation": "expected_revision required for existing resources; stale revisions return typed revision conflict" + }, + "idempotency": { + "required": false, + "key_scope": "authenticated plugin and method", + "retry": "same key returns original committed outcome" + }, + "quota": "method-specific result/page bounds; location traversal and report queries run as cancellable bounded jobs where required", + "commit_authorization": "recheck authenticated identity, named grant, record/category scope and grant revision immediately before mutation or stream delivery" + } + }, + { + "route": "/gamenode.plugin.v1.Saves/CreateProfile", + "service": "Saves", + "method": "CreateProfile", + "request": "SaveProfileCreateRequest", + "response": "SaveProfileMutationReply", + "streaming": false, + "permission": "game.saves.create", + "operation_owner": "authenticated creating plugin", + "resource_owner": "host-owned source attribution; caller-owned writes; published foreign records require matching operation/scope grant", + "request_policy": "typed new profile, approved resource handles, idempotency key", + "response_policy": "created profile id and revision or typed conflict", + "extension_or_opaque_policy": "Descriptive emulator metadata only; rules/handles remain typed", + "access_model": "game.saves.create; own creator/category scope; game scope", + "contract": { + "pagination": { + "supported": false, + "max_page_size": 200, + "cursor": "opaque and session scoped" + }, + "revision": { + "read": "response includes observed revision where available", + "mutation": "expected_revision required for existing resources; stale revisions return typed revision conflict" + }, + "idempotency": { + "required": true, + "key_scope": "authenticated plugin and method", + "retry": "same key returns original committed outcome" + }, + "quota": "method-specific result/page bounds; location traversal and report queries run as cancellable bounded jobs where required", + "commit_authorization": "recheck authenticated identity, named grant, record/category scope and grant revision immediately before mutation or stream delivery" + } + }, + { + "route": "/gamenode.plugin.v1.Saves/UpdateProfile", + "service": "Saves", + "method": "UpdateProfile", + "request": "SaveProfileUpdateRequest", + "response": "SaveProfileMutationReply", + "streaming": false, + "permission": "game.saves.update", + "operation_owner": "authenticated updating plugin", + "resource_owner": "host-owned source attribution; caller-owned writes; published foreign records require matching operation/scope grant", + "request_policy": "existing profile id, expected revision, typed patch, idempotency key", + "response_policy": "updated profile id and revision or typed conflict", + "extension_or_opaque_policy": "Descriptive emulator metadata only; rules/handles remain typed", + "access_model": "game.saves.update; own creator or category/selected-record grant; game scope", + "contract": { + "pagination": { + "supported": false, + "max_page_size": 200, + "cursor": "opaque and session scoped" + }, + "revision": { + "read": "response includes observed revision where available", + "mutation": "expected_revision required for existing resources; stale revisions return typed revision conflict" + }, + "idempotency": { + "required": true, + "key_scope": "authenticated plugin and method", + "retry": "same key returns original committed outcome" + }, + "quota": "method-specific result/page bounds; location traversal and report queries run as cancellable bounded jobs where required", + "commit_authorization": "recheck authenticated identity, named grant, record/category scope and grant revision immediately before mutation or stream delivery" + } + }, + { + "route": "/gamenode.plugin.v1.Saves/RemoveProfile", + "service": "Saves", + "method": "RemoveProfile", + "request": "SaveProfileRemoveRequest", + "response": "SaveProfileMutationReply", + "streaming": false, + "permission": "game.saves.delete", + "operation_owner": "authenticated deleting plugin", + "resource_owner": "host-owned source attribution; caller-owned writes; published foreign records require matching operation/scope grant", + "request_policy": "existing profile id, expected revision, idempotency key", + "response_policy": "removed profile id and revision or typed conflict", + "extension_or_opaque_policy": "None", + "access_model": "game.saves.delete; own creator or category/selected-record grant; game scope", + "contract": { + "pagination": { + "supported": false, + "max_page_size": 200, + "cursor": "opaque and session scoped" + }, + "revision": { + "read": "response includes observed revision where available", + "mutation": "expected_revision required for existing resources; stale revisions return typed revision conflict" + }, + "idempotency": { + "required": true, + "key_scope": "authenticated plugin and method", + "retry": "same key returns original committed outcome" + }, + "quota": "method-specific result/page bounds; location traversal and report queries run as cancellable bounded jobs where required", + "commit_authorization": "recheck authenticated identity, named grant, record/category scope and grant revision immediately before mutation or stream delivery" + } + }, + { + "route": "/gamenode.plugin.v1.Locations/Inspect", + "service": "Locations", + "method": "Inspect", + "request": "LocationInspectRequest", + "response": "LocationInspectReply", + "streaming": false, + "permission": "game.storage.inspect or game.saves.inspect", + "operation_owner": "authenticated plugin within approved resource scope", + "resource_owner": "host-owned source attribution; caller-owned writes; published foreign records require matching operation/scope grant", + "request_policy": "approved resource handle, requested dimensions and bounded entry count", + "response_policy": "typed location characteristics and per-observation availability", + "extension_or_opaque_policy": "Descriptive vendor metadata only; cannot replace access, volume or digest fields", + "access_model": "game.storage.inspect or game.saves.inspect; selected approved resource scope", + "contract": { + "pagination": { + "supported": false, + "max_page_size": 200, + "cursor": "opaque and session scoped" + }, + "revision": { + "read": "response includes observed revision where available", + "mutation": "expected_revision required for existing resources; stale revisions return typed revision conflict" + }, + "idempotency": { + "required": false, + "key_scope": "authenticated plugin and method", + "retry": "same key returns original committed outcome" + }, + "quota": "method-specific result/page bounds; location traversal and report queries run as cancellable bounded jobs where required", + "commit_authorization": "recheck authenticated identity, named grant, record/category scope and grant revision immediately before mutation or stream delivery" + } + }, + { + "route": "/gamenode.plugin.v1.Locations/GetSize", + "service": "Locations", + "method": "GetSize", + "request": "LocationSizeRequest", + "response": "LocationSizeReply", + "streaming": false, + "permission": "game.storage.inspect or game.saves.inspect", + "operation_owner": "authenticated plugin within approved resource scope", + "resource_owner": "host-owned source attribution; caller-owned writes; published foreign records require matching operation/scope grant", + "request_policy": "approved resource handle and bounded entry count", + "response_policy": "logical bytes, file/directory counts, completeness and availability", + "extension_or_opaque_policy": "None; unknown states remain explicit", + "access_model": "game.storage.inspect or game.saves.inspect; selected approved resource scope", + "contract": { + "pagination": { + "supported": false, + "max_page_size": 200, + "cursor": "opaque and session scoped" + }, + "revision": { + "read": "response includes observed revision where available", + "mutation": "expected_revision required for existing resources; stale revisions return typed revision conflict" + }, + "idempotency": { + "required": false, + "key_scope": "authenticated plugin and method", + "retry": "same key returns original committed outcome" + }, + "quota": "method-specific result/page bounds; location traversal and report queries run as cancellable bounded jobs where required", + "commit_authorization": "recheck authenticated identity, named grant, record/category scope and grant revision immediately before mutation or stream delivery" + } + }, + { + "route": "/gamenode.plugin.v1.Locations/GetAccess", + "service": "Locations", + "method": "GetAccess", + "request": "LocationAccessRequest", + "response": "LocationAccessReply", + "streaming": false, + "permission": "game.storage.inspect or game.saves.inspect", + "operation_owner": "authenticated plugin within approved resource scope", + "resource_owner": "host-owned source attribution; caller-owned writes; published foreign records require matching operation/scope grant", + "request_policy": "approved resource handle and selected entry handles", + "response_policy": "read-only attributes and effective access states", + "extension_or_opaque_policy": "None; unknown states remain explicit", + "access_model": "game.storage.inspect or game.saves.inspect; selected approved resource scope", + "contract": { + "pagination": { + "supported": false, + "max_page_size": 200, + "cursor": "opaque and session scoped" + }, + "revision": { + "read": "response includes observed revision where available", + "mutation": "expected_revision required for existing resources; stale revisions return typed revision conflict" + }, + "idempotency": { + "required": false, + "key_scope": "authenticated plugin and method", + "retry": "same key returns original committed outcome" + }, + "quota": "method-specific result/page bounds; location traversal and report queries run as cancellable bounded jobs where required", + "commit_authorization": "recheck authenticated identity, named grant, record/category scope and grant revision immediately before mutation or stream delivery" + } + }, + { + "route": "/gamenode.plugin.v1.Locations/GetLastModified", + "service": "Locations", + "method": "GetLastModified", + "request": "LocationLastModifiedRequest", + "response": "LocationLastModifiedReply", + "streaming": false, + "permission": "game.storage.inspect or game.saves.inspect", + "operation_owner": "authenticated plugin within approved resource scope", + "resource_owner": "host-owned source attribution; caller-owned writes; published foreign records require matching operation/scope grant", + "request_policy": "approved resource handle and bounded entry count", + "response_policy": "per-entry timestamp/precision and optional aggregate latest time", + "extension_or_opaque_policy": "None; unknown states remain explicit", + "access_model": "game.storage.inspect or game.saves.inspect; selected approved resource scope", + "contract": { + "pagination": { + "supported": false, + "max_page_size": 200, + "cursor": "opaque and session scoped" + }, + "revision": { + "read": "response includes observed revision where available", + "mutation": "expected_revision required for existing resources; stale revisions return typed revision conflict" + }, + "idempotency": { + "required": false, + "key_scope": "authenticated plugin and method", + "retry": "same key returns original committed outcome" + }, + "quota": "method-specific result/page bounds; location traversal and report queries run as cancellable bounded jobs where required", + "commit_authorization": "recheck authenticated identity, named grant, record/category scope and grant revision immediately before mutation or stream delivery" + } + }, + { + "route": "/gamenode.plugin.v1.Locations/GetFingerprint", + "service": "Locations", + "method": "GetFingerprint", + "request": "LocationFingerprintRequest", + "response": "LocationFingerprintReply", + "streaming": false, + "permission": "game.storage.inspect or game.saves.inspect", + "operation_owner": "authenticated plugin within approved resource scope", + "resource_owner": "host-owned source attribution; caller-owned writes; published foreign records require matching operation/scope grant", + "request_policy": "approved resource handle, algorithm, freshness and idempotency key", + "response_policy": "snapshot id, digest, completeness, consistency, revision and job id", + "extension_or_opaque_policy": "None; no arbitrary path or plugin-defined hashing authority", + "access_model": "game.storage.inspect or game.saves.inspect; selected approved resource scope", + "contract": { + "pagination": { + "supported": false, + "max_page_size": 200, + "cursor": "opaque and session scoped" + }, + "revision": { + "read": "response includes observed revision where available", + "mutation": "expected_revision required for existing resources; stale revisions return typed revision conflict" + }, + "idempotency": { + "required": false, + "key_scope": "authenticated plugin and method", + "retry": "same key returns original committed outcome" + }, + "quota": "method-specific result/page bounds; location traversal and report queries run as cancellable bounded jobs where required", + "commit_authorization": "recheck authenticated identity, named grant, record/category scope and grant revision immediately before mutation or stream delivery" + } + }, + { + "route": "/gamenode.plugin.v1.Locations/Compare", + "service": "Locations", + "method": "Compare", + "request": "LocationCompareRequest", + "response": "LocationCompareReply", + "streaming": false, + "permission": "game.storage.inspect or game.saves.inspect", + "operation_owner": "authenticated plugin within approved resource scope", + "resource_owner": "host-owned source attribution; caller-owned writes; published foreign records require matching operation/scope grant", + "request_policy": "compatible snapshot ids/revision and bounded page", + "response_policy": "typed change entries, cursor and comparable/indeterminate status", + "extension_or_opaque_policy": "None; unknown observations remain explicit", + "access_model": "game.storage.inspect or game.saves.inspect; selected approved resource scope", + "contract": { + "pagination": { + "supported": true, + "max_page_size": 200, + "cursor": "opaque and session scoped" + }, + "revision": { + "read": "response includes observed revision where available", + "mutation": "expected_revision required for existing resources; stale revisions return typed revision conflict" + }, + "idempotency": { + "required": false, + "key_scope": "authenticated plugin and method", + "retry": "same key returns original committed outcome" + }, + "quota": "method-specific result/page bounds; location traversal and report queries run as cancellable bounded jobs where required", + "commit_authorization": "recheck authenticated identity, named grant, record/category scope and grant revision immediately before mutation or stream delivery" + } + }, + { + "route": "/gamenode.plugin.v1.Locations/WatchAvailability", + "service": "Locations", + "method": "WatchAvailability", + "request": "LocationAvailabilityWatchRequest", + "response": "LocationAvailabilityEvent", + "streaming": true, + "permission": "game.storage.inspect or game.saves.inspect", + "operation_owner": "authenticated plugin within approved resource scope", + "resource_owner": "host-owned source attribution; caller-owned writes; published foreign records require matching operation/scope grant", + "request_policy": "approved resource handle and sequence cursor", + "response_policy": "typed volume/mount availability event", + "extension_or_opaque_policy": "None; opaque volume identity only", + "access_model": "game.storage.inspect or game.saves.inspect; selected approved resource scope", + "contract": { + "pagination": { + "supported": false, + "max_page_size": 200, + "cursor": "opaque and session scoped" + }, + "revision": { + "read": "response includes observed revision where available", + "mutation": "expected_revision required for existing resources; stale revisions return typed revision conflict" + }, + "idempotency": { + "required": false, + "key_scope": "authenticated plugin and method", + "retry": "same key returns original committed outcome" + }, + "quota": "method-specific result/page bounds; location traversal and report queries run as cancellable bounded jobs where required", + "commit_authorization": "recheck authenticated identity, named grant, record/category scope and grant revision immediately before mutation or stream delivery" + } + }, + { + "route": "/gamenode.plugin.v1.StorageDiagnostics/List", + "service": "StorageDiagnostics", + "method": "List", + "request": "DiagnosticListRequest", + "response": "DiagnosticListReply", + "streaming": false, + "permission": "storage.diagnostics.read", + "operation_owner": "authenticated report consumer", + "resource_owner": "host-owned source attribution; caller-owned writes; published foreign records require matching operation/scope grant", + "request_policy": "owner/resource selector, approved projection and bounded page/cursor", + "response_policy": "typed reports, provenance, revisions and next cursor", + "extension_or_opaque_policy": "Approved vendor/report extensions only", + "access_model": "storage.diagnostics.read plus explicit sensitive source/recipient projection review", + "contract": { + "pagination": { + "supported": true, + "max_page_size": 200, + "cursor": "opaque and session scoped" + }, + "revision": { + "read": "response includes observed revision where available", + "mutation": "expected_revision required for existing resources; stale revisions return typed revision conflict" + }, + "idempotency": { + "required": false, + "key_scope": "authenticated plugin and method", + "retry": "same key returns original committed outcome" + }, + "quota": "method-specific result/page bounds; location traversal and report queries run as cancellable bounded jobs where required", + "commit_authorization": "recheck authenticated identity, named grant, record/category scope and grant revision immediately before mutation or stream delivery" + } + }, + { + "route": "/gamenode.plugin.v1.StorageDiagnostics/Get", + "service": "StorageDiagnostics", + "method": "Get", + "request": "DiagnosticGetRequest", + "response": "DiagnosticGetReply", + "streaming": false, + "permission": "storage.diagnostics.read", + "operation_owner": "authenticated report consumer", + "resource_owner": "host-owned source attribution; caller-owned writes; published foreign records require matching operation/scope grant", + "request_policy": "report id and approved projection", + "response_policy": "typed report, provenance and revision", + "extension_or_opaque_policy": "Approved vendor/report extensions only", + "access_model": "storage.diagnostics.read plus explicit sensitive source/recipient projection review", + "contract": { + "pagination": { + "supported": false, + "max_page_size": 200, + "cursor": "opaque and session scoped" + }, + "revision": { + "read": "response includes observed revision where available", + "mutation": "expected_revision required for existing resources; stale revisions return typed revision conflict" + }, + "idempotency": { + "required": false, + "key_scope": "authenticated plugin and method", + "retry": "same key returns original committed outcome" + }, + "quota": "method-specific result/page bounds; location traversal and report queries run as cancellable bounded jobs where required", + "commit_authorization": "recheck authenticated identity, named grant, record/category scope and grant revision immediately before mutation or stream delivery" + } + }, + { + "route": "/gamenode.plugin.v1.StorageDiagnostics/Watch", + "service": "StorageDiagnostics", + "method": "Watch", + "request": "DiagnosticWatchRequest", + "response": "DiagnosticEvent", + "streaming": true, + "permission": "storage.diagnostics.read", + "operation_owner": "authenticated report consumer", + "resource_owner": "host-owned source attribution; caller-owned writes; published foreign records require matching operation/scope grant", + "request_policy": "owner/resource selector, approved projection and revision cursor", + "response_policy": "typed report-change event and revision", + "extension_or_opaque_policy": "Approved vendor/report extensions only", + "access_model": "storage.diagnostics.read plus explicit sensitive source/recipient projection review", + "contract": { + "pagination": { + "supported": false, + "max_page_size": 200, + "cursor": "opaque and session scoped" + }, + "revision": { + "read": "response includes observed revision where available", + "mutation": "expected_revision required for existing resources; stale revisions return typed revision conflict" + }, + "idempotency": { + "required": false, + "key_scope": "authenticated plugin and method", + "retry": "same key returns original committed outcome" + }, + "quota": "method-specific result/page bounds; location traversal and report queries run as cancellable bounded jobs where required", + "commit_authorization": "recheck authenticated identity, named grant, record/category scope and grant revision immediately before mutation or stream delivery" + } + }, + { + "route": "/gamenode.plugin.v1.Computer/List", + "service": "Computer", + "method": "List", + "request": "ComputerListRequest", + "response": "ComputerListReply", + "streaming": false, + "permission": "computer.hardware.read", + "operation_owner": "authenticated report consumer", + "resource_owner": "host-owned source attribution; caller-owned writes; published foreign records require matching operation/scope grant", + "request_policy": "computer selector, approved projection and bounded page/cursor", + "response_policy": "typed hardware/software reports, provenance, revisions and next cursor", + "extension_or_opaque_policy": "Approved hardware/vendor extension fields; private identifiers excluded", + "access_model": "computer.hardware.read plus explicit sensitive source/recipient projection review", + "contract": { + "pagination": { + "supported": true, + "max_page_size": 200, + "cursor": "opaque and session scoped" + }, + "revision": { + "read": "response includes observed revision where available", + "mutation": "expected_revision required for existing resources; stale revisions return typed revision conflict" + }, + "idempotency": { + "required": false, + "key_scope": "authenticated plugin and method", + "retry": "same key returns original committed outcome" + }, + "quota": "method-specific result/page bounds; location traversal and report queries run as cancellable bounded jobs where required", + "commit_authorization": "recheck authenticated identity, named grant, record/category scope and grant revision immediately before mutation or stream delivery" + } + }, + { + "route": "/gamenode.plugin.v1.Computer/Get", + "service": "Computer", + "method": "Get", + "request": "ComputerGetRequest", + "response": "ComputerGetReply", + "streaming": false, + "permission": "computer.hardware.read", + "operation_owner": "authenticated report consumer", + "resource_owner": "host-owned source attribution; caller-owned writes; published foreign records require matching operation/scope grant", + "request_policy": "computer record id and approved projection", + "response_policy": "typed report, provenance and revision", + "extension_or_opaque_policy": "Approved hardware/vendor extension fields; private identifiers excluded", + "access_model": "computer.hardware.read plus explicit sensitive source/recipient projection review", + "contract": { + "pagination": { + "supported": false, + "max_page_size": 200, + "cursor": "opaque and session scoped" + }, + "revision": { + "read": "response includes observed revision where available", + "mutation": "expected_revision required for existing resources; stale revisions return typed revision conflict" + }, + "idempotency": { + "required": false, + "key_scope": "authenticated plugin and method", + "retry": "same key returns original committed outcome" + }, + "quota": "method-specific result/page bounds; location traversal and report queries run as cancellable bounded jobs where required", + "commit_authorization": "recheck authenticated identity, named grant, record/category scope and grant revision immediately before mutation or stream delivery" + } + }, + { + "route": "/gamenode.plugin.v1.Computer/Watch", + "service": "Computer", + "method": "Watch", + "request": "ComputerWatchRequest", + "response": "ComputerEvent", + "streaming": true, + "permission": "computer.hardware.read", + "operation_owner": "authenticated report consumer", + "resource_owner": "host-owned source attribution; caller-owned writes; published foreign records require matching operation/scope grant", + "request_policy": "computer selector, approved projection and revision cursor", + "response_policy": "typed hardware report-change event and revision", + "extension_or_opaque_policy": "Approved hardware/vendor extension fields; private identifiers excluded", + "access_model": "computer.hardware.read plus explicit sensitive source/recipient projection review", + "contract": { + "pagination": { + "supported": false, + "max_page_size": 200, + "cursor": "opaque and session scoped" + }, + "revision": { + "read": "response includes observed revision where available", + "mutation": "expected_revision required for existing resources; stale revisions return typed revision conflict" + }, + "idempotency": { + "required": false, + "key_scope": "authenticated plugin and method", + "retry": "same key returns original committed outcome" + }, + "quota": "method-specific result/page bounds; location traversal and report queries run as cancellable bounded jobs where required", + "commit_authorization": "recheck authenticated identity, named grant, record/category scope and grant revision immediately before mutation or stream delivery" + } + }, + { + "route": "/gamenode.plugin.v1.GamePresence/List", + "service": "GamePresence", + "method": "List", + "request": "PresenceListRequest", + "response": "PresenceListReply", + "streaming": false, + "permission": "game.presence.read", + "operation_owner": "authenticated presence consumer", + "resource_owner": "host-owned source attribution; caller-owned writes; published foreign records require matching operation/scope grant", + "request_policy": "game/session selector, approved projection and bounded page/cursor", + "response_policy": "typed expiring presence records and provenance", + "extension_or_opaque_policy": "Approved game-specific extension fields only", + "access_model": "game.presence.read plus explicit sensitive source/recipient projection review", + "contract": { + "pagination": { + "supported": true, + "max_page_size": 200, + "cursor": "opaque and session scoped" + }, + "revision": { + "read": "response includes observed revision where available", + "mutation": "expected_revision required for existing resources; stale revisions return typed revision conflict" + }, + "idempotency": { + "required": false, + "key_scope": "authenticated plugin and method", + "retry": "same key returns original committed outcome" + }, + "quota": "method-specific result/page bounds; location traversal and report queries run as cancellable bounded jobs where required", + "commit_authorization": "recheck authenticated identity, named grant, record/category scope and grant revision immediately before mutation or stream delivery" + } + }, + { + "route": "/gamenode.plugin.v1.GamePresence/Get", + "service": "GamePresence", + "method": "Get", + "request": "PresenceGetRequest", + "response": "PresenceGetReply", + "streaming": false, + "permission": "game.presence.read", + "operation_owner": "authenticated presence consumer", + "resource_owner": "host-owned source attribution; caller-owned writes; published foreign records require matching operation/scope grant", + "request_policy": "presence record id and approved projection", + "response_policy": "typed expiring presence record and provenance", + "extension_or_opaque_policy": "Approved game-specific extension fields only", + "access_model": "game.presence.read plus explicit sensitive source/recipient projection review", + "contract": { + "pagination": { + "supported": false, + "max_page_size": 200, + "cursor": "opaque and session scoped" + }, + "revision": { + "read": "response includes observed revision where available", + "mutation": "expected_revision required for existing resources; stale revisions return typed revision conflict" + }, + "idempotency": { + "required": false, + "key_scope": "authenticated plugin and method", + "retry": "same key returns original committed outcome" + }, + "quota": "method-specific result/page bounds; location traversal and report queries run as cancellable bounded jobs where required", + "commit_authorization": "recheck authenticated identity, named grant, record/category scope and grant revision immediately before mutation or stream delivery" + } + }, + { + "route": "/gamenode.plugin.v1.GamePresence/Watch", + "service": "GamePresence", + "method": "Watch", + "request": "PresenceWatchRequest", + "response": "PresenceEvent", + "streaming": true, + "permission": "game.presence.read", + "operation_owner": "authenticated presence consumer", + "resource_owner": "host-owned source attribution; caller-owned writes; published foreign records require matching operation/scope grant", + "request_policy": "game/session selector, approved projection and sequence cursor", + "response_policy": "typed presence event with sequence, expiry and provenance", + "extension_or_opaque_policy": "Approved game-specific extension fields only", + "access_model": "game.presence.read plus explicit sensitive source/recipient projection review", + "contract": { + "pagination": { + "supported": false, + "max_page_size": 200, + "cursor": "opaque and session scoped" + }, + "revision": { + "read": "response includes observed revision where available", + "mutation": "expected_revision required for existing resources; stale revisions return typed revision conflict" + }, + "idempotency": { + "required": false, + "key_scope": "authenticated plugin and method", + "retry": "same key returns original committed outcome" + }, + "quota": "method-specific result/page bounds; location traversal and report queries run as cancellable bounded jobs where required", + "commit_authorization": "recheck authenticated identity, named grant, record/category scope and grant revision immediately before mutation or stream delivery" + } + }, + { + "route": "/gamenode.plugin.v1.GamePerformance/List", + "service": "GamePerformance", + "method": "List", + "request": "PerformanceListRequest", + "response": "PerformanceListReply", + "streaming": false, + "permission": "game.performance.read", + "operation_owner": "authenticated performance consumer", + "resource_owner": "host-owned source attribution; caller-owned writes; published foreign records require matching operation/scope grant", + "request_policy": "game/computer selector, projection, category/record selector and bounded page", + "response_policy": "typed series/samples, provenance, revisions and next cursor", + "extension_or_opaque_policy": "Approved supplemental metric fields only", + "access_model": "game.performance.read; common standard metrics or explicit sensitive projection review", + "contract": { + "pagination": { + "supported": true, + "max_page_size": 200, + "cursor": "opaque and session scoped" + }, + "revision": { + "read": "response includes observed revision where available", + "mutation": "expected_revision required for existing resources; stale revisions return typed revision conflict" + }, + "idempotency": { + "required": false, + "key_scope": "authenticated plugin and method", + "retry": "same key returns original committed outcome" + }, + "quota": "method-specific result/page bounds; location traversal and report queries run as cancellable bounded jobs where required", + "commit_authorization": "recheck authenticated identity, named grant, record/category scope and grant revision immediately before mutation or stream delivery" + } + }, + { + "route": "/gamenode.plugin.v1.GamePerformance/Get", + "service": "GamePerformance", + "method": "Get", + "request": "PerformanceGetRequest", + "response": "PerformanceGetReply", + "streaming": false, + "permission": "game.performance.read", + "operation_owner": "authenticated performance consumer", + "resource_owner": "host-owned source attribution; caller-owned writes; published foreign records require matching operation/scope grant", + "request_policy": "series id, projection and category/record selector", + "response_policy": "typed series/samples, provenance and revision", + "extension_or_opaque_policy": "Approved supplemental metric fields only", + "access_model": "game.performance.read; selected-record grant can work without category grant", + "contract": { + "pagination": { + "supported": false, + "max_page_size": 200, + "cursor": "opaque and session scoped" + }, + "revision": { + "read": "response includes observed revision where available", + "mutation": "expected_revision required for existing resources; stale revisions return typed revision conflict" + }, + "idempotency": { + "required": false, + "key_scope": "authenticated plugin and method", + "retry": "same key returns original committed outcome" + }, + "quota": "method-specific result/page bounds; location traversal and report queries run as cancellable bounded jobs where required", + "commit_authorization": "recheck authenticated identity, named grant, record/category scope and grant revision immediately before mutation or stream delivery" + } + }, + { + "route": "/gamenode.plugin.v1.GamePerformance/Watch", + "service": "GamePerformance", + "method": "Watch", + "request": "PerformanceWatchRequest", + "response": "PerformanceEvent", + "streaming": true, + "permission": "game.performance.read", + "operation_owner": "authenticated performance consumer", + "resource_owner": "host-owned source attribution; caller-owned writes; published foreign records require matching operation/scope grant", + "request_policy": "game/computer selector, projection, selector and sequence cursor", + "response_policy": "typed series event, samples, provenance and sequence", + "extension_or_opaque_policy": "Approved supplemental metric fields only", + "access_model": "game.performance.read; common standard metrics or explicit sensitive projection review", + "contract": { + "pagination": { + "supported": false, + "max_page_size": 200, + "cursor": "opaque and session scoped" + }, + "revision": { + "read": "response includes observed revision where available", + "mutation": "expected_revision required for existing resources; stale revisions return typed revision conflict" + }, + "idempotency": { + "required": false, + "key_scope": "authenticated plugin and method", + "retry": "same key returns original committed outcome" + }, + "quota": "method-specific result/page bounds; location traversal and report queries run as cancellable bounded jobs where required", + "commit_authorization": "recheck authenticated identity, named grant, record/category scope and grant revision immediately before mutation or stream delivery" + } + }, + { + "route": "/gamenode.plugin.v1.GamePerformance/QuerySeries", + "service": "GamePerformance", + "method": "QuerySeries", + "request": "PerformanceQuerySeriesRequest", + "response": "PerformanceQuerySeriesReply", + "streaming": false, + "permission": "game.performance.read", + "operation_owner": "authenticated performance consumer", + "resource_owner": "host-owned source attribution; caller-owned writes; published foreign records require matching operation/scope grant", + "request_policy": "series/time window/resolution, category/record selector and bounded page", + "response_policy": "typed samples, coverage, gaps and dropped-sample count", + "extension_or_opaque_policy": "Approved supplemental sample fields only", + "access_model": "game.performance.read; common standard metrics or explicit sensitive projection review", + "contract": { + "pagination": { + "supported": true, + "max_page_size": 200, + "cursor": "opaque and session scoped" + }, + "revision": { + "read": "response includes observed revision where available", + "mutation": "expected_revision required for existing resources; stale revisions return typed revision conflict" + }, + "idempotency": { + "required": false, + "key_scope": "authenticated plugin and method", + "retry": "same key returns original committed outcome" + }, + "quota": "method-specific result/page bounds; location traversal and report queries run as cancellable bounded jobs where required", + "commit_authorization": "recheck authenticated identity, named grant, record/category scope and grant revision immediately before mutation or stream delivery" + } + }, + { + "route": "/gamenode.plugin.v1.GamePerformance/Aggregate", + "service": "GamePerformance", + "method": "Aggregate", + "request": "PerformanceAggregateRequest", + "response": "PerformanceAggregateReply", + "streaming": false, + "permission": "game.performance.read", + "operation_owner": "authenticated performance consumer", + "resource_owner": "host-owned source attribution; caller-owned writes; published foreign records require matching operation/scope grant", + "request_policy": "series/time window, standard metric, aggregation and category/record selector", + "response_policy": "typed value, unit, coverage, sample count and provenance", + "extension_or_opaque_policy": "No extension affects computation; unknown metrics are not aggregated", + "access_model": "game.performance.read; common standard metrics or explicit sensitive projection review", + "contract": { + "pagination": { + "supported": false, + "max_page_size": 200, + "cursor": "opaque and session scoped" + }, + "revision": { + "read": "response includes observed revision where available", + "mutation": "expected_revision required for existing resources; stale revisions return typed revision conflict" + }, + "idempotency": { + "required": false, + "key_scope": "authenticated plugin and method", + "retry": "same key returns original committed outcome" + }, + "quota": "method-specific result/page bounds; location traversal and report queries run as cancellable bounded jobs where required", + "commit_authorization": "recheck authenticated identity, named grant, record/category scope and grant revision immediately before mutation or stream delivery" + } + } + ] +} diff --git a/crates/plugin-protocol/contracts/endpoint_field_policy.json b/crates/plugin-protocol/contracts/endpoint_field_policy.json new file mode 100644 index 000000000..d8106d005 --- /dev/null +++ b/crates/plugin-protocol/contracts/endpoint_field_policy.json @@ -0,0 +1,1499 @@ +{ + "source": "openspec/changes/add-third-party-plugins/design.md#18-per-endpoint-typing-and-extensible-catalogs", + "columns": [ + "request_policy", + "response_policy", + "extension_or_opaque_policy", + "access_model" + ], + "routes": [ + { + "route": "/gamenode.plugin.v1.PluginHost/OpenSession", + "request_policy": "Existing identity, API version, credential and requested grants", + "response_policy": "Existing session/version/grant result; API 1.6+ adds the host-issued resource context", + "extension_or_opaque_policy": "None", + "access_model": "Control; existing", + "status": "protobuf_contract", + "wire_service": "PluginHost", + "wire_method": "OpenSession", + "request_type": "OpenSessionRequest", + "response_type": "OpenSessionReply", + "streaming": false, + "permission": "authenticated control session" + }, + { + "route": "/gamenode.plugin.v1.PluginHost/SubmitDiscovery", + "request_policy": "Existing scoped operation and typed result/failure; legacy record fields retained", + "response_policy": "Accepted or typed failure", + "extension_or_opaque_policy": "Only optional descriptive record extension for negotiated 1.6; legacy fields unchanged", + "access_model": "Own provider; existing", + "status": "protobuf_contract", + "wire_service": "PluginHost", + "wire_method": "SubmitDiscovery", + "request_type": "SubmitDiscoveryRequest", + "response_type": "SubmitDiscoveryReply", + "streaming": false, + "permission": "authenticated control session" + }, + { + "route": "/gamenode.plugin.v1.ProviderHost/Exchange", + "request_policy": "Existing typed context and event oneof", + "response_policy": "Typed correlated commands/results", + "extension_or_opaque_policy": "Only designated domain-record extensions; no dynamic command dispatch", + "access_model": "Operation scope; existing", + "status": "protobuf_contract", + "wire_service": "ProviderHost", + "wire_method": "Exchange", + "request_type": "ProviderEvent", + "response_type": "ProviderCommand", + "streaming": true, + "permission": "operation-specific negotiated provider permission" + }, + { + "route": "/gamenode.plugin.v1.ProviderHost/GetContext", + "request_policy": "Existing ServiceContext", + "response_policy": "Validated context, grants and limits", + "extension_or_opaque_policy": "No new Struct; legacy manifest remains packaged validated text", + "access_model": "Own provider; existing", + "status": "protobuf_contract", + "wire_service": "ProviderHost", + "wire_method": "GetContext", + "request_type": "ServiceContext", + "response_type": "ProviderContext", + "streaming": false, + "permission": "provider.context.read" + }, + { + "route": "/gamenode.plugin.v1.ProviderHost/Account", + "request_policy": "Existing read/save/clear action oneof", + "response_policy": "Existing optional account and acknowledgement", + "extension_or_opaque_policy": "None in current RPC; supplemental non-secret annotations belong to projected records", + "access_model": "Own account; existing", + "status": "protobuf_contract", + "wire_service": "ProviderHost", + "wire_method": "Account", + "request_type": "AccountRequest", + "response_type": "AccountReply", + "streaming": false, + "permission": "account.state.read/account.state.publish" + }, + { + "route": "/gamenode.plugin.v1.ProviderHost/Secret", + "request_policy": "Existing context, slot, operation and optional bytes", + "response_policy": "Typed storage/outcome and secret bytes", + "extension_or_opaque_policy": "None; never shared", + "access_model": "Private; existing", + "status": "protobuf_contract", + "wire_service": "ProviderHost", + "wire_method": "Secret", + "request_type": "SecretRequest", + "response_type": "SecretReply", + "streaming": false, + "permission": "secrets.read/secrets.write/secrets.delete" + }, + { + "route": "/gamenode.plugin.v1.ProviderHost/Login", + "request_policy": "Existing operation, handle and context", + "response_policy": "Existing state, approved cookies and bounded probe result", + "extension_or_opaque_policy": "No generic Struct; existing probe JSON is not an extensibility/execution channel", + "access_model": "Private; existing", + "status": "protobuf_contract", + "wire_service": "ProviderHost", + "wire_method": "Login", + "request_type": "LoginRequest", + "response_type": "LoginReply", + "streaming": false, + "permission": "auth.webview" + }, + { + "route": "/gamenode.plugin.v1.ProviderHost/DeclareActions", + "request_policy": "Existing approved URI declarations", + "response_policy": "Accepted or denial", + "extension_or_opaque_policy": "None; custom targets use new typed launch contract", + "access_model": "Own provider; existing", + "status": "protobuf_contract", + "wire_service": "ProviderHost", + "wire_method": "DeclareActions", + "request_type": "ActionRequest", + "response_type": "ActionReply", + "streaming": false, + "permission": "provider.actions.declare" + }, + { + "route": "/gamenode.plugin.v1.PluginControl/DescribeApi", + "request_policy": "Session", + "response_policy": "API versions, feature/permission/schema descriptors and limits", + "extension_or_opaque_policy": "None; schema descriptors are bounded declarative assets, not dynamic policy", + "access_model": "Control", + "status": "protobuf_contract", + "wire_service": "PluginHost", + "wire_method": "DescribeApi", + "request_type": "DescribeApiRequest", + "response_type": "DescribeApiReply", + "streaming": false, + "permission": "authenticated control session" + }, + { + "route": "/gamenode.plugin.v1.PluginControl/GetPermissions", + "request_policy": "Session", + "response_policy": "Effective grants, scopes and revision", + "extension_or_opaque_policy": "None; schema descriptors are bounded declarative assets, not dynamic policy", + "access_model": "Control", + "status": "protobuf_contract", + "wire_service": "PluginHost", + "wire_method": "GetPermissions", + "request_type": "GetPermissionsRequest", + "response_type": "GetPermissionsReply", + "streaming": false, + "permission": "authenticated control session" + }, + { + "route": "/gamenode.plugin.v1.PluginControl/WatchPermissionChanges", + "request_policy": "Session and cursor", + "response_policy": "Typed grant-change/revoked events", + "extension_or_opaque_policy": "None; schema descriptors are bounded declarative assets, not dynamic policy", + "access_model": "Control", + "status": "protobuf_contract", + "wire_service": "PluginHost", + "wire_method": "WatchPermissionChanges", + "request_type": "WatchPermissionChangesRequest", + "response_type": "PermissionChange", + "streaming": true, + "permission": "authenticated control session" + }, + { + "route": "/gamenode.plugin.v1.Library/List", + "request_policy": "Typed scope/id, approved projection, `common_data_categories`, pagination or cursor", + "response_policy": "Typed game projections and optional runtime-availability projection, provenance, revision and page/event envelope", + "extension_or_opaque_policy": "Namespaced descriptive game metadata only", + "access_model": "Common game-path/content category or explicit catalog read scope", + "status": "protobuf_contract", + "wire_method": "LibraryList", + "request_type": "LibraryListRequest", + "response_type": "LibraryListReply", + "permission": "library.read", + "wire_service": "ResourceHost" + }, + { + "route": "/gamenode.plugin.v1.Library/Get", + "request_policy": "Typed scope/id, approved projection, `common_data_categories`, pagination or cursor", + "response_policy": "Typed game projection and optional runtime-availability projection, provenance and revision", + "extension_or_opaque_policy": "Namespaced descriptive game metadata only", + "access_model": "Common game-path/content category or explicit catalog read scope", + "status": "protobuf_contract", + "wire_method": "LibraryGet", + "request_type": "LibraryGetRequest", + "response_type": "LibraryGetReply", + "permission": "library.read", + "wire_service": "ResourceHost" + }, + { + "route": "/gamenode.plugin.v1.Library/Watch", + "request_policy": "Typed scope/id, approved projection, `common_data_categories`, pagination or cursor", + "response_policy": "Typed game projections and optional runtime-availability projection, provenance, revision and page/event envelope", + "extension_or_opaque_policy": "Namespaced descriptive game metadata only", + "access_model": "Common game-path/content category or explicit catalog read scope", + "status": "protobuf_contract", + "wire_method": "LibraryWatch", + "request_type": "LibraryWatchRequest", + "response_type": "LibraryEvent", + "permission": "library.read", + "wire_service": "ResourceHost" + }, + { + "route": "/gamenode.plugin.v1.Metadata/Update", + "request_policy": "Game id, expected revision, typed display-field patch and field mask", + "response_policy": "Typed updated projection/revision", + "extension_or_opaque_policy": "Namespaced non-executable metadata patch allowed; no provider facts", + "access_model": "Own catalog writes", + "status": "protobuf_contract", + "wire_method": "MetadataUpdate", + "request_type": "MetadataUpdateRequest", + "response_type": "MutationReply", + "permission": "library.metadata.write", + "wire_service": "ResourceHost" + }, + { + "route": "/gamenode.plugin.v1.Favorites/List", + "request_policy": "Profile/game scope and pagination", + "response_policy": "Typed favorite references", + "extension_or_opaque_policy": "None; annotations stay on game records", + "access_model": "Catalog user scope", + "status": "protobuf_contract", + "wire_method": "FavoritesList", + "request_type": "FavoritesListRequest", + "response_type": "FavoritesListReply", + "permission": "favorites.read", + "wire_service": "ResourceHost" + }, + { + "route": "/gamenode.plugin.v1.Favorites/Set", + "request_policy": "Game id, boolean and revision/idempotency", + "response_policy": "Typed outcome/revision", + "extension_or_opaque_policy": "None", + "access_model": "Explicit user write", + "status": "protobuf_contract", + "wire_method": "FavoritesSet", + "request_type": "FavoritesSetRequest", + "response_type": "MutationReply", + "permission": "favorites.write", + "wire_service": "ResourceHost" + }, + { + "route": "/gamenode.plugin.v1.Matching/Search", + "request_policy": "Bounded title query (1 to 128 bytes), one page of at most 50; platform filter and cursor reserved", + "response_policy": "Typed candidate game id, title and release year; no scores", + "extension_or_opaque_policy": "Optional provider descriptive annotations; not matching authority", + "access_model": "Catalog search scope", + "status": "protobuf_contract", + "wire_method": "MatchingSearch", + "request_type": "MatchingSearchRequest", + "response_type": "MatchingSearchReply", + "permission": "matching.read", + "wire_service": "ResourceHost" + }, + { + "route": "/gamenode.plugin.v1.Matching/Assign", + "request_policy": "Own installation id, a game id the host knows or a search offered, and the entry revision", + "response_policy": "Typed outcome with the entry revision", + "extension_or_opaque_policy": "None", + "access_model": "Own entries under matching.write; never replaces a match the user chose", + "status": "protobuf_contract", + "wire_method": "MatchingAssign", + "request_type": "MatchingAssignRequest", + "response_type": "MutationReply", + "permission": "matching.write", + "wire_service": "ResourceHost" + }, + { + "route": "/gamenode.plugin.v1.Artwork/Read", + "request_policy": "Own installation id, cover kind and the caller's byte budget", + "response_policy": "Typed MIME, size and artwork revision plus the encoded cover", + "extension_or_opaque_policy": "No Struct in bytes; descriptive credit metadata may be a resource extension", + "access_model": "Own entries under artwork.read; nothing is downloaded", + "status": "protobuf_contract", + "wire_method": "ArtworkRead", + "request_type": "ArtworkReadRequest", + "response_type": "ArtworkReadReply", + "permission": "artwork.read", + "wire_service": "ResourceHost" + }, + { + "route": "/gamenode.plugin.v1.Artwork/Set", + "request_policy": "Own installation id, entry artwork revision and a bounded static PNG, JPEG or WebP, inline or by a files.read handle of the same installation; empty restores the game cover", + "response_policy": "Typed outcome with the entry artwork revision", + "extension_or_opaque_policy": "Descriptive credit metadata only; cannot set arbitrary fetch/scheme authority", + "access_model": "Own entries under artwork.write; never changes the matched game cover", + "status": "protobuf_contract", + "wire_method": "ArtworkSet", + "request_type": "ArtworkSetRequest", + "response_type": "MutationReply", + "permission": "artwork.write", + "wire_service": "ResourceHost" + }, + { + "route": "/gamenode.plugin.v1.Games/RegisterContent", + "request_policy": "Own-provider or scoped runtime-discovery stable game/install/content/runtime identities, approved content handle and platform support", + "response_policy": "Stable content id, binding revision and typed mutation outcome", + "extension_or_opaque_policy": "Namespaced descriptive game annotations only", + "access_model": "library.discovery; provider or runtime-content context", + "status": "protobuf_contract", + "wire_method": "GamesRegisterContent", + "request_type": "ContentRegistrationRequest", + "response_type": "MutationReply", + "permission": "library.discovery", + "wire_service": "ResourceHost" + }, + { + "route": "/gamenode.plugin.v1.Games/RequestLaunch", + "request_policy": "Game/target revision, idempotency and user intent", + "response_policy": "Typed launch/job outcome", + "extension_or_opaque_policy": "None; rejects overrides", + "access_model": "game.launch", + "status": "protobuf_contract", + "wire_method": "GamesRequestLaunch", + "request_type": "GameLaunchRequest", + "response_type": "GameLaunchReply", + "permission": "game.launch", + "wire_service": "ResourceHost" + }, + { + "route": "/gamenode.plugin.v1.Games/ProposeCustomLaunch", + "request_policy": "Game/base revision, typed target/runtime/content id/argv/cwd/env and intent", + "response_policy": "Typed recipe/host-plan id, revision and approval state", + "extension_or_opaque_policy": "Descriptive recommendation/evidence only; executable fields remain typed", + "access_model": "game.custom_launch; own recipe", + "status": "protobuf_contract", + "wire_method": "GamesProposeCustomLaunch", + "request_type": "CustomLaunchRequest", + "response_type": "CustomLaunchReply", + "permission": "game.custom_launch", + "wire_service": "ResourceHost" + }, + { + "route": "/gamenode.plugin.v1.Games/RequestCustomLaunch", + "request_policy": "Approved immutable host-plan/recipe revision and user intent; no content id override", + "response_policy": "Typed launch/job outcome or changed-plan refusal", + "extension_or_opaque_policy": "None; no dynamic execution parameters", + "access_model": "game.custom_launch", + "status": "protobuf_contract", + "wire_method": "GamesRequestCustomLaunch", + "request_type": "CustomLaunchRequest", + "response_type": "CustomLaunchReply", + "permission": "game.custom_launch", + "wire_service": "ResourceHost" + }, + { + "route": "/gamenode.plugin.v1.Games/RemoveCustomLaunch", + "request_policy": "Owned recipe id/revision", + "response_policy": "Typed removal outcome", + "extension_or_opaque_policy": "None", + "access_model": "Own recipe", + "status": "protobuf_contract", + "wire_method": "GamesRemoveCustomLaunch", + "request_type": "CustomLaunchRemoveRequest", + "response_type": "MutationReply", + "permission": "game.custom_launch", + "wire_service": "ResourceHost" + }, + { + "route": "/gamenode.plugin.v1.Games/RequestInstall", + "request_policy": "Approved game/catalog target, destination handle and user intent", + "response_policy": "Typed plan/job/outcome", + "extension_or_opaque_policy": "None; installer parameters are typed", + "access_model": "Approved domain operation", + "status": "protobuf_contract", + "wire_method": "GamesRequestInstall", + "request_type": "GameInstallRequest", + "response_type": "JobReply", + "permission": "games.install", + "wire_service": "ResourceHost" + }, + { + "route": "/gamenode.plugin.v1.Libraries/Create", + "request_policy": "Authorized resource ids/revision and typed library/root fields/approved resource handles", + "response_policy": "Typed library/root id/revision/status", + "extension_or_opaque_policy": "Descriptive namespaced metadata only; runtime executable/formats/templates stay typed", + "access_model": "library.roots.create; creator/category scope", + "status": "protobuf_contract", + "wire_method": "LibrariesCreate", + "request_type": "LibraryCreateRequest", + "response_type": "LibraryMutationReply", + "permission": "library.roots.create", + "wire_service": "ResourceHost" + }, + { + "route": "/gamenode.plugin.v1.Libraries/Update", + "request_policy": "Authorized resource ids/revision and typed library/root fields/approved resource handles", + "response_policy": "Typed library/root id/revision/status", + "extension_or_opaque_policy": "Descriptive namespaced metadata only; runtime executable/formats/templates stay typed", + "access_model": "library.roots.update; creator or explicit selected/category-authorized record scope", + "status": "protobuf_contract", + "wire_method": "LibrariesUpdate", + "request_type": "LibraryUpdateRequest", + "response_type": "LibraryMutationReply", + "permission": "library.roots.update", + "wire_service": "ResourceHost" + }, + { + "route": "/gamenode.plugin.v1.Libraries/Remove", + "request_policy": "Authorized resource ids/revision and typed deletion selection", + "response_policy": "Typed library/root id/revision/status", + "extension_or_opaque_policy": "None", + "access_model": "library.roots.delete; creator scope or explicit resource/operation grant", + "status": "protobuf_contract", + "wire_method": "LibrariesRemove", + "request_type": "DomainRemoveRequest", + "response_type": "MutationReply", + "permission": "library.roots.delete", + "wire_service": "ResourceHost" + }, + { + "route": "/gamenode.plugin.v1.Libraries/AddRoot", + "request_policy": "Authorized resource ids/revision and typed library/root fields/approved resource handles", + "response_policy": "Typed library/root id/revision/status", + "extension_or_opaque_policy": "Descriptive namespaced metadata only; runtime executable/formats/templates stay typed", + "access_model": "library.roots.create; creator/category scope", + "status": "protobuf_contract", + "wire_method": "LibrariesAddRoot", + "request_type": "LibraryRootAddRequest", + "response_type": "LibraryMutationReply", + "permission": "library.roots.create", + "wire_service": "ResourceHost" + }, + { + "route": "/gamenode.plugin.v1.Libraries/UpdateRoot", + "request_policy": "Authorized resource ids/revision and typed library/root fields/approved resource handles", + "response_policy": "Typed library/root id/revision/status", + "extension_or_opaque_policy": "Descriptive namespaced metadata only; runtime executable/formats/templates stay typed", + "access_model": "library.roots.update; creator or explicit selected/category-authorized record scope", + "status": "protobuf_contract", + "wire_method": "LibrariesUpdateRoot", + "request_type": "LibraryRootUpdateRequest", + "response_type": "LibraryMutationReply", + "permission": "library.roots.update", + "wire_service": "ResourceHost" + }, + { + "route": "/gamenode.plugin.v1.Libraries/RemoveRoot", + "request_policy": "Authorized resource ids/revision and typed deletion selection", + "response_policy": "Typed library/root id/revision/status", + "extension_or_opaque_policy": "None", + "access_model": "library.roots.delete; creator scope or explicit resource/operation grant", + "status": "protobuf_contract", + "wire_method": "LibrariesRemoveRoot", + "request_type": "LibraryRootRemoveRequest", + "response_type": "MutationReply", + "permission": "library.roots.delete", + "wire_service": "ResourceHost" + }, + { + "route": "/gamenode.plugin.v1.Libraries/List", + "request_policy": "Typed scope/id, approved projection, pagination or cursor", + "response_policy": "Typed library/root, provenance, revision and page/event envelope", + "extension_or_opaque_policy": "Descriptive resource extensions within user-approved projection", + "access_model": "library.roots.read; creator scope or explicit resource/operation grant", + "status": "protobuf_contract", + "wire_method": "LibrariesList", + "request_type": "DomainListRequest", + "response_type": "LibrariesListReply", + "permission": "library.roots.read", + "wire_service": "ResourceHost" + }, + { + "route": "/gamenode.plugin.v1.Libraries/Get", + "request_policy": "Typed scope/id, approved projection, pagination or cursor", + "response_policy": "Typed library/root, provenance, revision and page/event envelope", + "extension_or_opaque_policy": "Descriptive resource extensions within user-approved projection", + "access_model": "library.roots.read; creator scope or explicit resource/operation grant", + "status": "protobuf_contract", + "wire_method": "LibrariesGet", + "request_type": "DomainGetRequest", + "response_type": "LibraryRecordReply", + "permission": "library.roots.read", + "wire_service": "ResourceHost" + }, + { + "route": "/gamenode.plugin.v1.Libraries/Watch", + "request_policy": "Typed scope/id, approved projection, pagination or cursor", + "response_policy": "Typed library/root, provenance, revision and page/event envelope", + "extension_or_opaque_policy": "Descriptive resource extensions within user-approved projection", + "access_model": "library.roots.read; creator scope or explicit resource/operation grant", + "status": "protobuf_contract", + "wire_method": "LibrariesWatch", + "request_type": "DomainWatchRequest", + "response_type": "LibraryRecordEvent", + "permission": "library.roots.read", + "wire_service": "ResourceHost" + }, + { + "route": "/gamenode.plugin.v1.Runtimes/RequestAccess", + "request_policy": "Typed runtime name/version/platform/formats/argv template with an empty executable handle plus text executable/desktop hints", + "response_policy": "Typed runtime id/revision/status with no executable path or handle", + "extension_or_opaque_policy": "Descriptive namespaced metadata only; executable choice, identity and digest stay host-owned", + "access_model": "game.runtime.create; creator scope; the host picker approves one exact host-validated executable", + "status": "protobuf_contract", + "wire_method": "RuntimesRequestAccess", + "request_type": "RuntimeRequestAccessRequest", + "response_type": "RuntimeMutationReply", + "permission": "game.runtime.create", + "wire_service": "ResourceHost" + }, + { + "route": "/gamenode.plugin.v1.Runtimes/Register", + "request_policy": "Typed runtime name/version/platform/formats/argv template and approved executable handle", + "response_policy": "Typed runtime id/revision/status", + "extension_or_opaque_policy": "Descriptive namespaced metadata only; runtime executable/formats/templates stay typed", + "access_model": "game.runtime.create; creator/category scope", + "status": "protobuf_contract", + "wire_method": "RuntimesRegister", + "request_type": "RuntimeRegisterRequest", + "response_type": "RuntimeMutationReply", + "permission": "game.runtime.create", + "wire_service": "ResourceHost" + }, + { + "route": "/gamenode.plugin.v1.Runtimes/Update", + "request_policy": "Owned runtime id/revision and typed field patch including platform/formats/argv template/approved executable handle", + "response_policy": "Typed runtime id/revision/status", + "extension_or_opaque_policy": "Descriptive namespaced metadata only; runtime executable/formats/templates stay typed", + "access_model": "game.runtime.update; creator or explicit selected/category-authorized record scope", + "status": "protobuf_contract", + "wire_method": "RuntimesUpdate", + "request_type": "RuntimeUpdateRequest", + "response_type": "RuntimeMutationReply", + "permission": "game.runtime.update", + "wire_service": "ResourceHost" + }, + { + "route": "/gamenode.plugin.v1.Runtimes/Remove", + "request_policy": "Authorized resource ids/revision and typed deletion selection", + "response_policy": "Typed runtime id/revision/status", + "extension_or_opaque_policy": "None", + "access_model": "game.runtime.delete; creator scope or explicit resource/operation grant", + "status": "protobuf_contract", + "wire_method": "RuntimesRemove", + "request_type": "DomainRemoveRequest", + "response_type": "MutationReply", + "permission": "game.runtime.delete", + "wire_service": "ResourceHost" + }, + { + "route": "/gamenode.plugin.v1.Runtimes/List", + "request_policy": "Typed scope/id, approved projection, `common_data_categories`, pagination or cursor", + "response_policy": "Typed runtime, provenance, revision and page/event envelope", + "extension_or_opaque_policy": "Descriptive resource extensions within user-approved projection", + "access_model": "game.runtime.read; own scope or granted common category/resource scope", + "status": "protobuf_contract", + "wire_method": "RuntimesList", + "request_type": "DomainListRequest", + "response_type": "RuntimesListReply", + "permission": "game.runtime.read", + "wire_service": "ResourceHost" + }, + { + "route": "/gamenode.plugin.v1.Runtimes/Get", + "request_policy": "Typed scope/id, approved projection, `common_data_categories`, pagination or cursor", + "response_policy": "Typed runtime, provenance, revision and page/event envelope", + "extension_or_opaque_policy": "Descriptive resource extensions within user-approved projection", + "access_model": "game.runtime.read; own scope or granted common category/resource scope", + "status": "protobuf_contract", + "wire_method": "RuntimesGet", + "request_type": "DomainGetRequest", + "response_type": "RuntimeRecordReply", + "permission": "game.runtime.read", + "wire_service": "ResourceHost" + }, + { + "route": "/gamenode.plugin.v1.Runtimes/Watch", + "request_policy": "Typed scope/id, approved projection, `common_data_categories`, pagination or cursor", + "response_policy": "Typed runtime, provenance, revision and page/event envelope", + "extension_or_opaque_policy": "Descriptive resource extensions within user-approved projection", + "access_model": "game.runtime.read; own scope or granted common category/resource scope", + "status": "protobuf_contract", + "wire_method": "RuntimesWatch", + "request_type": "DomainWatchRequest", + "response_type": "RuntimeRecordEvent", + "permission": "game.runtime.read", + "wire_service": "ResourceHost" + }, + { + "route": "/gamenode.plugin.v1.Saves/ListProfiles", + "request_policy": "Authorized game/profile scope; pagination for list", + "response_policy": "Typed save-context/rules/approval/revision; optional format/compatibility descriptors", + "extension_or_opaque_policy": "Game/emulator-specific descriptive metadata; source paths remain scoped typed refs", + "access_model": "game.saves.read; creator scope or explicit resource/operation grant; game scope", + "status": "protobuf_contract", + "wire_service": "Saves", + "wire_method": "ListProfiles", + "request_type": "SaveProfileListRequest", + "response_type": "SaveProfileListReply", + "streaming": false, + "permission": "game.saves.read" + }, + { + "route": "/gamenode.plugin.v1.Saves/GetProfile", + "request_policy": "Authorized game/profile scope; pagination for list", + "response_policy": "Typed save-context/rules/approval/revision; optional format/compatibility descriptors", + "extension_or_opaque_policy": "Game/emulator-specific descriptive metadata; source paths remain scoped typed refs", + "access_model": "game.saves.read; creator scope or explicit resource/operation grant; game scope", + "status": "protobuf_contract", + "wire_service": "Saves", + "wire_method": "GetProfile", + "request_type": "SaveProfileGetRequest", + "response_type": "SaveProfileReply", + "streaming": false, + "permission": "game.saves.read" + }, + { + "route": "/gamenode.plugin.v1.Saves/CreateProfile", + "request_policy": "Authorized profile/game id, revision and typed rules/handles for create/update", + "response_policy": "Typed profile/revision/review status", + "extension_or_opaque_policy": "Descriptive emulator context only; roots/patterns/shared scope remain typed", + "access_model": "game.saves.write; creator scope or explicit resource/operation grant; game scope", + "status": "protobuf_contract", + "wire_service": "Saves", + "wire_method": "CreateProfile", + "request_type": "SaveProfileCreateRequest", + "response_type": "SaveProfileMutationReply", + "streaming": false, + "permission": "game.saves.create" + }, + { + "route": "/gamenode.plugin.v1.Saves/UpdateProfile", + "request_policy": "Authorized profile/game id, revision and typed rules/handles for create/update", + "response_policy": "Typed profile/revision/review status", + "extension_or_opaque_policy": "Descriptive emulator context only; roots/patterns/shared scope remain typed", + "access_model": "game.saves.write; creator scope or explicit resource/operation grant; game scope", + "status": "protobuf_contract", + "wire_service": "Saves", + "wire_method": "UpdateProfile", + "request_type": "SaveProfileUpdateRequest", + "response_type": "SaveProfileMutationReply", + "streaming": false, + "permission": "game.saves.update" + }, + { + "route": "/gamenode.plugin.v1.Saves/RemoveProfile", + "request_policy": "Authorized profile/game id, revision and typed rules/handles for create/update", + "response_policy": "Typed profile/revision/review status", + "extension_or_opaque_policy": "None", + "access_model": "game.saves.delete; creator scope or explicit resource/operation grant; game scope", + "status": "protobuf_contract", + "wire_service": "Saves", + "wire_method": "RemoveProfile", + "request_type": "SaveProfileRemoveRequest", + "response_type": "SaveProfileMutationReply", + "streaming": false, + "permission": "game.saves.delete" + }, + { + "route": "/gamenode.plugin.v1.Locations/Inspect", + "request_policy": "Typed Resource/filter/mode", + "response_policy": "Typed Location characteristics and requested observation results", + "extension_or_opaque_policy": "Only Inspect permits descriptive hardware/vendor metadata; never substitute access/volume/hash fields", + "access_model": "Approved game/save/runtime inspection", + "status": "protobuf_contract", + "wire_service": "Locations", + "wire_method": "Inspect", + "request_type": "LocationInspectRequest", + "response_type": "LocationInspectReply", + "streaming": false, + "permission": "game.storage.inspect or game.saves.inspect" + }, + { + "route": "/gamenode.plugin.v1.Locations/GetSize", + "request_policy": "Typed Resource/filter", + "response_policy": "Typed Logical bytes, counts, completeness", + "extension_or_opaque_policy": "None; unknown observations use typed unknown/unavailable states", + "access_model": "Approved game/save/runtime inspection", + "status": "protobuf_contract", + "wire_service": "Locations", + "wire_method": "GetSize", + "request_type": "LocationSizeRequest", + "response_type": "LocationSizeReply", + "streaming": false, + "permission": "game.storage.inspect or game.saves.inspect" + }, + { + "route": "/gamenode.plugin.v1.Locations/GetAccess", + "request_policy": "Typed Resource/entry selection", + "response_policy": "Typed Read-only attributes and effective access states", + "extension_or_opaque_policy": "None; unknown observations use typed unknown/unavailable states", + "access_model": "Approved game/save/runtime inspection", + "status": "protobuf_contract", + "wire_service": "Locations", + "wire_method": "GetAccess", + "request_type": "LocationAccessRequest", + "response_type": "LocationAccessReply", + "streaming": false, + "permission": "game.storage.inspect or game.saves.inspect" + }, + { + "route": "/gamenode.plugin.v1.Locations/GetLastModified", + "request_policy": "Typed Resource/filter", + "response_policy": "Typed Timestamp/resolution per entry and aggregate", + "extension_or_opaque_policy": "None; unknown observations use typed unknown/unavailable states", + "access_model": "Approved game/save/runtime inspection", + "status": "protobuf_contract", + "wire_service": "Locations", + "wire_method": "GetLastModified", + "request_type": "LocationLastModifiedRequest", + "response_type": "LocationLastModifiedReply", + "streaming": false, + "permission": "game.storage.inspect or game.saves.inspect" + }, + { + "route": "/gamenode.plugin.v1.Locations/GetFingerprint", + "request_policy": "Typed Resource/filter/algorithm/fresh mode", + "response_policy": "Typed Typed file/tree digests, consistency and job", + "extension_or_opaque_policy": "None; unknown observations use typed unknown/unavailable states", + "access_model": "Approved game/save/runtime inspection", + "status": "protobuf_contract", + "wire_service": "Locations", + "wire_method": "GetFingerprint", + "request_type": "LocationFingerprintRequest", + "response_type": "LocationFingerprintReply", + "streaming": false, + "permission": "game.storage.inspect or game.saves.inspect" + }, + { + "route": "/gamenode.plugin.v1.Locations/Compare", + "request_policy": "Typed Compatible snapshot ids/revisions", + "response_policy": "Typed Typed change list and comparable/indeterminate status", + "extension_or_opaque_policy": "None; unknown observations use typed unknown/unavailable states", + "access_model": "Approved game/save/runtime inspection", + "status": "protobuf_contract", + "wire_service": "Locations", + "wire_method": "Compare", + "request_type": "LocationCompareRequest", + "response_type": "LocationCompareReply", + "streaming": false, + "permission": "game.storage.inspect or game.saves.inspect" + }, + { + "route": "/gamenode.plugin.v1.Locations/WatchAvailability", + "request_policy": "Typed Resource and cursor", + "response_policy": "Typed Volume/mount/availability events", + "extension_or_opaque_policy": "None; unknown observations use typed unknown/unavailable states", + "access_model": "Approved game/save/runtime inspection", + "status": "protobuf_contract", + "wire_service": "Locations", + "wire_method": "WatchAvailability", + "request_type": "LocationAvailabilityWatchRequest", + "response_type": "LocationAvailabilityEvent", + "streaming": true, + "permission": "game.storage.inspect or game.saves.inspect" + }, + { + "route": "/gamenode.plugin.v1.Backups/List", + "request_policy": "Typed game/profile/revision; history page", + "response_policy": "Typed history/status or preview/job/outcome", + "extension_or_opaque_policy": "Descriptive snapshot notes only, never source/restore policy or commands", + "access_model": "Approved backup scope; restore confirmation", + "status": "protobuf_contract", + "wire_method": "BackupsList", + "request_type": "BackupsListRequest", + "response_type": "BackupsListReply", + "permission": "backups.read", + "wire_service": "ResourceHost" + }, + { + "route": "/gamenode.plugin.v1.Backups/RequestCreate", + "request_policy": "Typed game/profile/revision; snapshot/destination/user-confirmation context", + "response_policy": "Typed history/status or preview/job/outcome", + "extension_or_opaque_policy": "None", + "access_model": "Approved backup scope; restore confirmation", + "status": "protobuf_contract", + "wire_method": "BackupsRequestCreate", + "request_type": "BackupCreateRequest", + "response_type": "JobReply", + "permission": "backups.create", + "wire_service": "ResourceHost" + }, + { + "route": "/gamenode.plugin.v1.Backups/RequestRestore", + "request_policy": "Typed game/profile/revision; snapshot/destination/user-confirmation context", + "response_policy": "Typed history/status or preview/job/outcome", + "extension_or_opaque_policy": "None", + "access_model": "Approved backup scope; restore confirmation", + "status": "protobuf_contract", + "wire_method": "BackupsRequestRestore", + "request_type": "BackupRestoreRequest", + "response_type": "JobReply", + "permission": "backups.restore", + "wire_service": "ResourceHost" + }, + { + "route": "/gamenode.plugin.v1.Storage/Get", + "request_policy": "Typed own key; the namespace is the authenticated plugin, publisher and profile, never a request field", + "response_policy": "Typed value bytes, revision, durability and expiry; no path", + "extension_or_opaque_policy": "Opaque application bytes, not a Struct interpreted by Core", + "access_model": "Private namespace", + "status": "protobuf_contract", + "wire_method": "StorageGet", + "request_type": "StorageGetRequest", + "response_type": "StorageGetReply", + "permission": "storage.read", + "wire_service": "ResourceHost" + }, + { + "route": "/gamenode.plugin.v1.Storage/Put", + "request_policy": "Typed own key and expected revision; opaque bytes, explicit SESSION_ONLY or PERSISTENT durability and optional lifetime", + "response_policy": "Typed revision, actual durability, expiry, usage and quota; no path", + "extension_or_opaque_policy": "Opaque application bytes, not a Struct interpreted by Core", + "access_model": "Private namespace", + "status": "protobuf_contract", + "wire_method": "StoragePut", + "request_type": "StoragePutRequest", + "response_type": "StorageMutationReply", + "permission": "storage.write + storage.persist (durable)", + "wire_service": "ResourceHost" + }, + { + "route": "/gamenode.plugin.v1.Storage/Delete", + "request_policy": "Typed own key and expected revision", + "response_policy": "Typed deletion result and the revision removed", + "extension_or_opaque_policy": "Opaque application bytes, not a Struct interpreted by Core", + "access_model": "Private namespace", + "status": "protobuf_contract", + "wire_method": "StorageDelete", + "request_type": "StorageDeleteRequest", + "response_type": "MutationReply", + "permission": "storage.delete", + "wire_service": "ResourceHost" + }, + { + "route": "/gamenode.plugin.v1.Files/RequestAccess", + "request_policy": "Typed own installation, requested operations and resource kinds, plus optional declared folder suggestions (closed placeholders or absolute paths, at most 8 per kind, shown to the user as unverified); no authoritative path: the user chooses the folder", + "response_policy": "Opaque session-bound handles for the folders the user approved; no path", + "extension_or_opaque_policy": "No Struct; bytes never interpreted as Core commands", + "access_model": "Per-plugin/per-game; persistence excluded", + "status": "protobuf_contract", + "wire_method": "FilesRequestAccess", + "request_type": "FilesRequestAccessRequest", + "response_type": "FileAccessReply", + "permission": "files.read/write/delete (user-approved scope)", + "wire_service": "ResourceHost" + }, + { + "route": "/gamenode.plugin.v1.Files/List", + "request_policy": "Opaque directory handle, opaque cursor and page size", + "response_policy": "Typed entries with opaque child handles, size and modification time; no path", + "extension_or_opaque_policy": "No Struct; bytes never interpreted as Core commands", + "access_model": "Per-plugin/per-game; persistence excluded", + "status": "protobuf_contract", + "wire_method": "FilesList", + "request_type": "FilesListRequest", + "response_type": "FilesListReply", + "permission": "files.read", + "wire_service": "ResourceHost" + }, + { + "route": "/gamenode.plugin.v1.Files/Read", + "request_policy": "Opaque file handle, offset and byte budget", + "response_policy": "Opaque file bytes, next offset and end-of-file flag", + "extension_or_opaque_policy": "No Struct; bytes never interpreted as Core commands", + "access_model": "Per-plugin/per-game; persistence excluded", + "status": "protobuf_contract", + "wire_method": "FilesRead", + "request_type": "FilesReadRequest", + "response_type": "FileReadReply", + "permission": "files.read", + "wire_service": "ResourceHost" + }, + { + "route": "/gamenode.plugin.v1.Files/Write", + "request_policy": "Opaque file handle (or directory handle plus a new file name), offset and opaque bytes", + "response_policy": "Typed outcome and the handle of the written file; no revision", + "extension_or_opaque_policy": "No Struct; bytes never interpreted as Core commands", + "access_model": "Per-plugin/per-game; persistence excluded", + "status": "protobuf_contract", + "wire_method": "FilesWrite", + "request_type": "FilesWriteRequest", + "response_type": "MutationReply", + "permission": "files.write", + "wire_service": "ResourceHost" + }, + { + "route": "/gamenode.plugin.v1.Files/Delete", + "request_policy": "Opaque file handle", + "response_policy": "Typed outcome; directories are never deleted", + "extension_or_opaque_policy": "No Struct; bytes never interpreted as Core commands", + "access_model": "Per-plugin/per-game; persistence excluded", + "status": "protobuf_contract", + "wire_method": "FilesDelete", + "request_type": "FilesDeleteRequest", + "response_type": "MutationReply", + "permission": "files.delete", + "wire_service": "ResourceHost" + }, + { + "route": "/gamenode.plugin.v1.Network/Fetch", + "request_policy": "Typed https URL whose exact origin the user approved, method, bounded headers and body, response budget and deadline; no credentials of the host", + "response_policy": "Typed HTTP status, bounded headers, opaque response bytes and the final origin; never an address or redirect target", + "extension_or_opaque_policy": "No generic Struct; response body can contain application JSON as bytes", + "access_model": "Approved origins", + "status": "protobuf_contract", + "wire_method": "NetworkFetch", + "request_type": "NetworkFetchRequest", + "response_type": "NetworkFetchReply", + "permission": "network.fetch", + "wire_service": "ResourceHost" + }, + { + "route": "/gamenode.plugin.v1.Notifications/Publish", + "request_policy": "Typed bounded plain text (title, body, optional translations by locale) and severity; no markup, links or actions", + "response_policy": "Typed accepted outcome; a rate limit is RESOURCE_EXHAUSTED with the wait in retry-after-ms", + "extension_or_opaque_policy": "None; no arbitrary UI/actions", + "access_model": "Attributed notification grant", + "status": "protobuf_contract", + "wire_method": "NotificationsPublish", + "request_type": "NotificationPublishRequest", + "response_type": "MutationReply", + "permission": "notifications.publish", + "wire_service": "ResourceHost" + }, + { + "route": "/gamenode.plugin.v1.StorageDiagnostics/PublishBenchmark", + "request_policy": "Typed source observation/device, conditions, metrics/units and durability", + "response_policy": "Typed report id/revision/status", + "extension_or_opaque_policy": "Vendor/tool descriptive fields only; core metric units/types stay typed", + "access_model": "Sensitive dataset publication", + "status": "protobuf_contract", + "wire_method": "StorageDiagnosticsPublishBenchmark", + "request_type": "BenchmarkReportRequest", + "response_type": "ReportMutationReply", + "permission": "storage.diagnostics.publish", + "wire_service": "ResourceHost" + }, + { + "route": "/gamenode.plugin.v1.StorageDiagnostics/PublishSmart", + "request_policy": "Typed device/time/availability/health and normalized supported metrics", + "response_policy": "Typed report id/revision/status", + "extension_or_opaque_policy": "Namespaced vendor SMART attributes/annotations, with declared units/schema", + "access_model": "Sensitive dataset publication", + "status": "protobuf_contract", + "wire_method": "StorageDiagnosticsPublishSmart", + "request_type": "SmartReportRequest", + "response_type": "ReportMutationReply", + "permission": "storage.diagnostics.publish", + "wire_service": "ResourceHost" + }, + { + "route": "/gamenode.plugin.v1.StorageDiagnostics/List", + "request_policy": "Typed scope/id, approved projection, pagination or cursor", + "response_policy": "Typed benchmark/SMART report, provenance, revision and page/event envelope", + "extension_or_opaque_policy": "Approved vendor/report extensions only", + "access_model": "Sensitive source/recipient projection", + "status": "protobuf_contract", + "wire_service": "StorageDiagnostics", + "wire_method": "List", + "request_type": "DiagnosticListRequest", + "response_type": "DiagnosticListReply", + "streaming": false, + "permission": "storage.diagnostics.read" + }, + { + "route": "/gamenode.plugin.v1.StorageDiagnostics/Get", + "request_policy": "Typed scope/id, approved projection, pagination or cursor", + "response_policy": "Typed benchmark/SMART report, provenance, revision and page/event envelope", + "extension_or_opaque_policy": "Approved vendor/report extensions only", + "access_model": "Sensitive source/recipient projection", + "status": "protobuf_contract", + "wire_service": "StorageDiagnostics", + "wire_method": "Get", + "request_type": "DiagnosticGetRequest", + "response_type": "DiagnosticGetReply", + "streaming": false, + "permission": "storage.diagnostics.read" + }, + { + "route": "/gamenode.plugin.v1.StorageDiagnostics/Watch", + "request_policy": "Typed scope/id, approved projection, pagination or cursor", + "response_policy": "Typed benchmark/SMART report, provenance, revision and page/event envelope", + "extension_or_opaque_policy": "Approved vendor/report extensions only", + "access_model": "Sensitive source/recipient projection", + "status": "protobuf_contract", + "wire_service": "StorageDiagnostics", + "wire_method": "Watch", + "request_type": "DiagnosticWatchRequest", + "response_type": "DiagnosticEvent", + "streaming": true, + "permission": "storage.diagnostics.read" + }, + { + "route": "/gamenode.plugin.v1.Computer/PublishHardware", + "request_policy": "Typed computer context, CPU/GPU/RAM/OS/driver observations and durability", + "response_policy": "Typed record id/revision/status", + "extension_or_opaque_policy": "Namespaced device/vendor supplemental observations; private identifiers stay excluded", + "access_model": "Sensitive publication", + "status": "protobuf_contract", + "wire_method": "ComputerPublishHardware", + "request_type": "HardwareReportRequest", + "response_type": "ReportMutationReply", + "permission": "computer.hardware.publish", + "wire_service": "ResourceHost" + }, + { + "route": "/gamenode.plugin.v1.Computer/List", + "request_policy": "Typed scope/id, approved projection, pagination or cursor", + "response_policy": "Typed hardware report, provenance, revision and page/event envelope", + "extension_or_opaque_policy": "Approved hardware/vendor extension fields", + "access_model": "Sensitive source/recipient projection", + "status": "protobuf_contract", + "wire_service": "Computer", + "wire_method": "List", + "request_type": "ComputerListRequest", + "response_type": "ComputerListReply", + "streaming": false, + "permission": "computer.hardware.read" + }, + { + "route": "/gamenode.plugin.v1.Computer/Get", + "request_policy": "Typed scope/id, approved projection, pagination or cursor", + "response_policy": "Typed hardware report, provenance, revision and page/event envelope", + "extension_or_opaque_policy": "Approved hardware/vendor extension fields", + "access_model": "Sensitive source/recipient projection", + "status": "protobuf_contract", + "wire_service": "Computer", + "wire_method": "Get", + "request_type": "ComputerGetRequest", + "response_type": "ComputerGetReply", + "streaming": false, + "permission": "computer.hardware.read" + }, + { + "route": "/gamenode.plugin.v1.Computer/Watch", + "request_policy": "Typed scope/id, approved projection, pagination or cursor", + "response_policy": "Typed hardware report, provenance, revision and page/event envelope", + "extension_or_opaque_policy": "Approved hardware/vendor extension fields", + "access_model": "Sensitive source/recipient projection", + "status": "protobuf_contract", + "wire_service": "Computer", + "wire_method": "Watch", + "request_type": "ComputerWatchRequest", + "response_type": "ComputerEvent", + "streaming": true, + "permission": "computer.hardware.read" + }, + { + "route": "/gamenode.plugin.v1.GamePresence/Publish", + "request_policy": "Typed game/session, state fields, sequence/time/TTL", + "response_policy": "Typed accepted/id/expiry", + "extension_or_opaque_policy": "Namespaced game-specific status fields only", + "access_model": "Sensitive publication", + "status": "protobuf_contract", + "wire_method": "GamePresencePublish", + "request_type": "PresencePublishRequest", + "response_type": "ReportMutationReply", + "permission": "game.presence.publish", + "wire_service": "ResourceHost" + }, + { + "route": "/gamenode.plugin.v1.GamePresence/Clear", + "request_policy": "Typed owned game/session/record and sequence", + "response_policy": "Typed cleared/stale outcome", + "extension_or_opaque_policy": "None", + "access_model": "Own presence", + "status": "protobuf_contract", + "wire_method": "GamePresenceClear", + "request_type": "PresenceClearRequest", + "response_type": "MutationReply", + "permission": "game.presence.publish", + "wire_service": "ResourceHost" + }, + { + "route": "/gamenode.plugin.v1.GamePresence/List", + "request_policy": "Typed scope/id, approved projection, pagination or cursor", + "response_policy": "Typed presence record, provenance, revision and page/event envelope", + "extension_or_opaque_policy": "Approved game-specific extension fields", + "access_model": "Sensitive source/recipient projection", + "status": "protobuf_contract", + "wire_service": "GamePresence", + "wire_method": "List", + "request_type": "PresenceListRequest", + "response_type": "PresenceListReply", + "streaming": false, + "permission": "game.presence.read" + }, + { + "route": "/gamenode.plugin.v1.GamePresence/Get", + "request_policy": "Typed scope/id, approved projection, pagination or cursor", + "response_policy": "Typed presence record, provenance, revision and page/event envelope", + "extension_or_opaque_policy": "Approved game-specific extension fields", + "access_model": "Sensitive source/recipient projection", + "status": "protobuf_contract", + "wire_service": "GamePresence", + "wire_method": "Get", + "request_type": "PresenceGetRequest", + "response_type": "PresenceGetReply", + "streaming": false, + "permission": "game.presence.read" + }, + { + "route": "/gamenode.plugin.v1.GamePresence/Watch", + "request_policy": "Typed scope/id, approved projection, pagination or cursor", + "response_policy": "Typed presence record, provenance, revision and page/event envelope", + "extension_or_opaque_policy": "Approved game-specific extension fields", + "access_model": "Sensitive source/recipient projection", + "status": "protobuf_contract", + "wire_service": "GamePresence", + "wire_method": "Watch", + "request_type": "PresenceWatchRequest", + "response_type": "PresenceEvent", + "streaming": true, + "permission": "game.presence.read" + }, + { + "route": "/gamenode.plugin.v1.GamePerformance/PublishSamples", + "request_policy": "Typed game/computer/session/series, FPS/CPU/RAM samples, units, sequence and durability", + "response_policy": "Typed accepted/dropped/backpressure/retained interval", + "extension_or_opaque_policy": "Namespaced supplemental metrics with declared units; never replace standard metrics", + "access_model": "Sensitive publication", + "status": "protobuf_contract", + "wire_method": "GamePerformancePublishSamples", + "request_type": "PerformanceSamplesRequest", + "response_type": "ReportMutationReply", + "permission": "game.performance.publish", + "wire_service": "ResourceHost" + }, + { + "route": "/gamenode.plugin.v1.GamePerformance/EndSeries", + "request_policy": "Typed series/sequence/end time", + "response_policy": "Typed series status and coverage", + "extension_or_opaque_policy": "None", + "access_model": "Own series", + "status": "protobuf_contract", + "wire_method": "GamePerformanceEndSeries", + "request_type": "PerformanceEndSeriesRequest", + "response_type": "MutationReply", + "permission": "game.performance.publish", + "wire_service": "ResourceHost" + }, + { + "route": "/gamenode.plugin.v1.GamePerformance/List", + "request_policy": "Typed scope/id, approved projection, `common_data_categories`, pagination or cursor", + "response_policy": "Typed performance series/sample, provenance, revision and page/event envelope", + "extension_or_opaque_policy": "Approved supplemental metric fields", + "access_model": "Common performance-history category for standard metrics; sensitive review for excluded fields", + "status": "protobuf_contract", + "wire_service": "GamePerformance", + "wire_method": "List", + "request_type": "PerformanceListRequest", + "response_type": "PerformanceListReply", + "streaming": false, + "permission": "game.performance.read" + }, + { + "route": "/gamenode.plugin.v1.GamePerformance/Get", + "request_policy": "Typed scope/id, approved projection, `common_data_categories`, pagination or cursor", + "response_policy": "Typed performance series/sample, provenance, revision and page/event envelope", + "extension_or_opaque_policy": "Approved supplemental metric fields", + "access_model": "Common performance-history category for standard metrics; sensitive review for excluded fields", + "status": "protobuf_contract", + "wire_service": "GamePerformance", + "wire_method": "Get", + "request_type": "PerformanceGetRequest", + "response_type": "PerformanceGetReply", + "streaming": false, + "permission": "game.performance.read" + }, + { + "route": "/gamenode.plugin.v1.GamePerformance/Watch", + "request_policy": "Typed scope/id, approved projection, `common_data_categories`, pagination or cursor", + "response_policy": "Typed performance series/sample, provenance, revision and page/event envelope", + "extension_or_opaque_policy": "Approved supplemental metric fields", + "access_model": "Common performance-history category for standard metrics; sensitive review for excluded fields", + "status": "protobuf_contract", + "wire_service": "GamePerformance", + "wire_method": "Watch", + "request_type": "PerformanceWatchRequest", + "response_type": "PerformanceEvent", + "streaming": true, + "permission": "game.performance.read" + }, + { + "route": "/gamenode.plugin.v1.GamePerformance/QuerySeries", + "request_policy": "Typed series/time window/resolution, `common_data_categories`, page", + "response_policy": "Typed retained samples/coverage", + "extension_or_opaque_policy": "Approved supplemental sample fields only", + "access_model": "Common performance-history category for standard metrics; sensitive review for excluded fields", + "status": "protobuf_contract", + "wire_service": "GamePerformance", + "wire_method": "QuerySeries", + "request_type": "PerformanceQuerySeriesRequest", + "response_type": "PerformanceQuerySeriesReply", + "streaming": false, + "permission": "game.performance.read" + }, + { + "route": "/gamenode.plugin.v1.GamePerformance/Aggregate", + "request_policy": "Typed series/time window, standard metric, aggregation and `common_data_categories`", + "response_policy": "Typed metric result, units, coverage and provenance", + "extension_or_opaque_policy": "None in computation; opaque unknown metrics are not automatically aggregated", + "access_model": "Common performance-history category for standard metrics; sensitive review for excluded fields", + "status": "protobuf_contract", + "wire_service": "GamePerformance", + "wire_method": "Aggregate", + "request_type": "PerformanceAggregateRequest", + "response_type": "PerformanceAggregateReply", + "streaming": false, + "permission": "game.performance.read" + }, + { + "route": "/gamenode.plugin.v1.Data/Publish", + "request_policy": "Typed declared custom dataset/schema/version/resource/time/durability envelope", + "response_policy": "Typed record id/revision/status", + "extension_or_opaque_policy": "Struct payload for declared custom data; cannot publish to a built-in domain using this route", + "access_model": "Explicit custom publication scope", + "status": "protobuf_contract", + "wire_method": "DataPublish", + "request_type": "DataPublishRequest", + "response_type": "DataMutationReply", + "permission": "data.publish or domain-specific publish grant; storage.persist for durable mode", + "wire_service": "ResourceHost" + }, + { + "route": "/gamenode.plugin.v1.Data/List", + "request_policy": "Typed scope/id, approved projection, pagination or cursor", + "response_policy": "Typed projected typed domain or declared custom dataset envelope, provenance, revision and page/event envelope", + "extension_or_opaque_policy": "Struct for approved custom payload/extensions only", + "access_model": "Sensitive/custom policy; catalog aliases cannot bypass domain scopes", + "status": "protobuf_contract", + "wire_method": "DataList", + "request_type": "DataListRequest", + "response_type": "DataListReply", + "permission": "declared dataset/category read grant; common inclusion is per-query opt-in", + "wire_service": "ResourceHost" + }, + { + "route": "/gamenode.plugin.v1.Data/Get", + "request_policy": "Typed scope/id, approved projection, pagination or cursor", + "response_policy": "Typed projected typed domain or declared custom dataset envelope, provenance, revision and page/event envelope", + "extension_or_opaque_policy": "Struct for approved custom payload/extensions only", + "access_model": "Sensitive/custom policy; catalog aliases cannot bypass domain scopes", + "status": "protobuf_contract", + "wire_method": "DataGet", + "request_type": "DataGetRequest", + "response_type": "DataGetReply", + "permission": "declared dataset/category read grant; common inclusion is per-query opt-in", + "wire_service": "ResourceHost" + }, + { + "route": "/gamenode.plugin.v1.Data/Watch", + "request_policy": "Typed scope/id, approved projection, pagination or cursor", + "response_policy": "Typed projected typed domain or declared custom dataset envelope, provenance, revision and page/event envelope", + "extension_or_opaque_policy": "Struct for approved custom payload/extensions only", + "access_model": "Sensitive/custom policy; catalog aliases cannot bypass domain scopes", + "status": "protobuf_contract", + "wire_method": "DataWatch", + "request_type": "DataWatchRequest", + "response_type": "DataEvent", + "permission": "declared dataset/category read grant; common inclusion is per-query opt-in", + "wire_service": "ResourceHost" + }, + { + "route": "/gamenode.plugin.v1.Persistence/GetUsage", + "request_policy": "Typed own logical selectors/cursor; constrained retention for SetRetentionPolicy", + "response_policy": "Typed accounting/entries/job/deletion result or effective policy", + "extension_or_opaque_policy": "None; no custom predicate/script or physical paths", + "access_model": "storage.persist; own namespace only", + "status": "protobuf_contract", + "wire_method": "PersistenceGetUsage", + "request_type": "PersistenceUsageRequest", + "response_type": "PersistenceUsageReply", + "permission": "storage.persist (own namespace)", + "wire_service": "ResourceHost" + }, + { + "route": "/gamenode.plugin.v1.Persistence/ListEntries", + "request_policy": "Typed own logical selectors/cursor; constrained retention for SetRetentionPolicy", + "response_policy": "Typed accounting/entries/job/deletion result or effective policy", + "extension_or_opaque_policy": "None; no custom predicate/script or physical paths", + "access_model": "storage.persist; own namespace only", + "status": "protobuf_contract", + "wire_method": "PersistenceListEntries", + "request_type": "PersistenceListRequest", + "response_type": "PersistenceListReply", + "permission": "storage.persist (own namespace)", + "wire_service": "ResourceHost" + }, + { + "route": "/gamenode.plugin.v1.Persistence/DeleteEntries", + "request_policy": "Typed own logical selectors/cursor; constrained retention for SetRetentionPolicy", + "response_policy": "Typed accounting/entries/job/deletion result or effective policy", + "extension_or_opaque_policy": "None; no custom predicate/script or physical paths", + "access_model": "storage.persist; own namespace only", + "status": "protobuf_contract", + "wire_method": "PersistenceDeleteEntries", + "request_type": "PersistenceDeleteRequest", + "response_type": "MutationReply", + "permission": "storage.persist (own namespace)", + "wire_service": "ResourceHost" + }, + { + "route": "/gamenode.plugin.v1.Persistence/Clear", + "request_policy": "Typed own logical selectors/cursor; constrained retention for SetRetentionPolicy", + "response_policy": "Typed accounting/entries/job/deletion result or effective policy", + "extension_or_opaque_policy": "None; no custom predicate/script or physical paths", + "access_model": "storage.persist; own namespace only", + "status": "protobuf_contract", + "wire_method": "PersistenceClear", + "request_type": "PersistenceClearRequest", + "response_type": "MutationReply", + "permission": "storage.persist (own namespace)", + "wire_service": "ResourceHost" + }, + { + "route": "/gamenode.plugin.v1.Persistence/SetRetentionPolicy", + "request_policy": "Typed own logical selectors/cursor; constrained retention for SetRetentionPolicy", + "response_policy": "Typed accounting/entries/job/deletion result or effective policy", + "extension_or_opaque_policy": "None; no custom predicate/script or physical paths", + "access_model": "storage.persist; own namespace only", + "status": "protobuf_contract", + "wire_method": "PersistenceSetRetentionPolicy", + "request_type": "RetentionPolicyRequest", + "response_type": "MutationReply", + "permission": "storage.persist (own namespace)", + "wire_service": "ResourceHost" + }, + { + "route": "/gamenode.plugin.v1.Tools/List", + "request_policy": "Typed catalog/game/resource/revision and pagination", + "response_policy": "Typed catalog/detail", + "extension_or_opaque_policy": "Descriptive catalog/vendor extension metadata only", + "access_model": "Domain catalog scope", + "status": "protobuf_contract", + "wire_method": "ToolsList", + "request_type": "ToolsListRequest", + "response_type": "ToolsListReply", + "permission": "tools.read", + "wire_service": "ResourceHost" + }, + { + "route": "/gamenode.plugin.v1.Tools/RequestApply", + "request_policy": "Typed catalog/game/resource/revision and plan/user intent", + "response_policy": "Typed plan/job/outcome", + "extension_or_opaque_policy": "None; no Struct executable recipe", + "access_model": "Approved domain operation", + "status": "protobuf_contract", + "wire_method": "ToolsRequestApply", + "request_type": "ToolApplyRequest", + "response_type": "JobReply", + "permission": "tools.apply", + "wire_service": "ResourceHost" + }, + { + "route": "/gamenode.plugin.v1.Tools/RequestRemove", + "request_policy": "Typed catalog/game/resource/revision and plan/user intent", + "response_policy": "Typed plan/job/outcome", + "extension_or_opaque_policy": "None; no Struct executable recipe", + "access_model": "Approved domain operation", + "status": "protobuf_contract", + "wire_method": "ToolsRequestRemove", + "request_type": "ToolRemoveRequest", + "response_type": "JobReply", + "permission": "tools.remove", + "wire_service": "ResourceHost" + }, + { + "route": "/gamenode.plugin.v1.Ports/List", + "request_policy": "Typed catalog/game/resource/revision and pagination", + "response_policy": "Typed catalog/detail", + "extension_or_opaque_policy": "Descriptive catalog/vendor extension metadata only", + "access_model": "Domain catalog scope", + "status": "protobuf_contract", + "wire_method": "PortsList", + "request_type": "PortsListRequest", + "response_type": "PortsListReply", + "permission": "ports.read", + "wire_service": "ResourceHost" + }, + { + "route": "/gamenode.plugin.v1.Ports/Detail", + "request_policy": "Typed catalog/game/resource/revision and pagination", + "response_policy": "Typed catalog/detail", + "extension_or_opaque_policy": "Descriptive catalog/vendor extension metadata only", + "access_model": "Domain catalog scope", + "status": "protobuf_contract", + "wire_method": "PortsDetail", + "request_type": "PortDetailRequest", + "response_type": "PortDetailReply", + "permission": "ports.read", + "wire_service": "ResourceHost" + }, + { + "route": "/gamenode.plugin.v1.Ports/RequestInstall", + "request_policy": "Typed catalog/game/resource/revision and plan/user intent", + "response_policy": "Typed plan/job/outcome", + "extension_or_opaque_policy": "None; no Struct executable recipe", + "access_model": "Approved domain operation", + "status": "protobuf_contract", + "wire_method": "PortsRequestInstall", + "request_type": "PortInstallRequest", + "response_type": "JobReply", + "permission": "ports.install", + "wire_service": "ResourceHost" + }, + { + "route": "/gamenode.plugin.v1.Jobs/Get", + "request_policy": "Typed owned job id and cursor for Watch", + "response_policy": "Typed status/progress/result or cancellation outcome", + "extension_or_opaque_policy": "Result may contain originating endpoint data extensions; never dynamic job execution", + "access_model": "Caller-owned jobs and underlying grant", + "status": "protobuf_contract", + "wire_method": "JobsGet", + "request_type": "JobGetRequest", + "response_type": "JobReply", + "permission": "underlying operation grant (caller-owned job)", + "wire_service": "ResourceHost" + }, + { + "route": "/gamenode.plugin.v1.Jobs/Watch", + "request_policy": "Typed owned job id and cursor for Watch", + "response_policy": "Typed status/progress/result or cancellation outcome", + "extension_or_opaque_policy": "Result may contain originating endpoint data extensions; never dynamic job execution", + "access_model": "Caller-owned jobs and underlying grant", + "status": "protobuf_contract", + "wire_method": "JobsWatch", + "request_type": "JobWatchRequest", + "response_type": "JobEvent", + "permission": "underlying operation grant (caller-owned job)", + "wire_service": "ResourceHost" + }, + { + "route": "/gamenode.plugin.v1.Jobs/Cancel", + "request_policy": "Typed owned job id and cursor for Watch", + "response_policy": "Typed status/progress/result or cancellation outcome", + "extension_or_opaque_policy": "Result may contain originating endpoint data extensions; never dynamic job execution", + "access_model": "Caller-owned jobs and underlying grant", + "status": "protobuf_contract", + "wire_method": "JobsCancel", + "request_type": "JobCancelRequest", + "response_type": "JobReply", + "permission": "underlying operation grant (caller-owned job)", + "wire_service": "ResourceHost" + } + ], + "exchange_event_families": [ + { + "family": "Ready", + "fields": "typed session readiness and negotiated scope", + "extension_policy": "none", + "access": "authenticated plugin session" + }, + { + "family": "AccountStatus", + "fields": "typed account identity/state, timestamps and secret-storage status", + "extension_policy": "non-secret descriptive annotations only through projected records", + "access": "own provider account" + }, + { + "family": "CatalogChunk", + "fields": "typed category, index and game id/name records", + "extension_policy": "designated descriptive catalog metadata only when negotiated", + "access": "own provider catalog operation" + }, + { + "family": "Result.discovery", + "fields": "typed operation disposition and discovery record identity", + "extension_policy": "designated descriptive record extension only when negotiated", + "access": "own provider discovery operation" + }, + { + "family": "Result.counter", + "fields": "typed game id, seconds and last-played timestamp", + "extension_policy": "none for metric authority", + "access": "own provider playtime.counter" + }, + { + "family": "Result.login", + "fields": "typed login outcome and bounded approved cookie/page-probe result", + "extension_policy": "none; secret-bearing values excluded from export", + "access": "own authenticated login operation" + }, + { + "family": "Result.settings", + "fields": "closed typed form schema, revisions and typed submitted values", + "extension_policy": "none; executable UI and arbitrary Struct denied", + "access": "ui.settings" + }, + { + "family": "Result.configuration", + "fields": "typed session/profile/window handles and lifecycle outcome", + "extension_policy": "none; plugin-owned UI is external to wire payload", + "access": "ui.configure" + }, + { + "family": "runtime session event/result", + "fields": "typed game/content/instance/session/sequence/time/lifecycle and correlated outcome", + "extension_policy": "descriptive extensions cannot establish gameplay", + "access": "game.sessions.report; approved game/runtime scope", + "event_message": "RuntimeSessionReport", + "result_message": "RuntimeSessionResult", + "permission": "game.sessions.report; approved game/installation/runtime scope", + "correlation": "correlation_id; typed accepted/rejected outcome" + } + ] +} diff --git a/crates/plugin-protocol/contracts/resource_host.json b/crates/plugin-protocol/contracts/resource_host.json new file mode 100644 index 000000000..4053c8acf --- /dev/null +++ b/crates/plugin-protocol/contracts/resource_host.json @@ -0,0 +1,2300 @@ +{ + "api": "1.6", + "service": "ResourceHost", + "unknown_route": "UNIMPLEMENTED", + "routes": [ + { + "method": "LibraryList", + "request": "LibraryListRequest", + "response": "LibraryListReply", + "streaming": false, + "owner": "authenticated caller/plugin; host owns global facts and attribution", + "permission": "library.read", + "semantics": [ + "cursor/page_size fields are available; host enforces method-specific bounds and opaque cursors", + "Uses operation-specific typed fields; mutations require expected_revision and idempotency_key, while list/get/watch use bounded cursors and typed projections." + ], + "contract": { + "operation_owner": "authenticated plugin session; host owns cross-plugin attribution and global facts", + "resource_owner": "caller-owned records by default; foreign shared records require the named grant and explicit scope", + "pagination": { + "supported": true, + "max_page_size": 200, + "cursor": "opaque, caller/session scoped" + }, + "revision": { + "read": "response carries the observed revision where applicable", + "mutation": "expected_revision required for existing mutable resources; conflict returns MUTATION_OUTCOME_REVISION_CONFLICT" + }, + "idempotency": { + "required": false, + "key_scope": "authenticated plugin plus operation", + "retry": "same key returns the original committed outcome" + }, + "quota": "enforced per method and owner; byte-bearing methods additionally enforce max_bytes and package/session limits", + "commit_authorization": "recheck permission, resource scope and grant revision immediately before side effects" + } + }, + { + "method": "LibraryGet", + "request": "LibraryGetRequest", + "response": "LibraryGetReply", + "streaming": false, + "owner": "authenticated caller/plugin; host owns global facts and attribution", + "permission": "library.read", + "semantics": [ + "Uses operation-specific typed fields; mutations require expected_revision and idempotency_key, while list/get/watch use bounded cursors and typed projections." + ], + "contract": { + "operation_owner": "authenticated plugin session; host owns cross-plugin attribution and global facts", + "resource_owner": "caller-owned records by default; foreign shared records require the named grant and explicit scope", + "pagination": { + "supported": false, + "max_page_size": 200, + "cursor": "opaque, caller/session scoped" + }, + "revision": { + "read": "response carries the observed revision where applicable", + "mutation": "expected_revision required for existing mutable resources; conflict returns MUTATION_OUTCOME_REVISION_CONFLICT" + }, + "idempotency": { + "required": false, + "key_scope": "authenticated plugin plus operation", + "retry": "same key returns the original committed outcome" + }, + "quota": "enforced per method and owner; byte-bearing methods additionally enforce max_bytes and package/session limits", + "commit_authorization": "recheck permission, resource scope and grant revision immediately before side effects" + } + }, + { + "method": "LibraryWatch", + "request": "LibraryWatchRequest", + "response": "LibraryEvent", + "streaming": true, + "owner": "authenticated caller/plugin; host owns global facts and attribution", + "permission": "library.read", + "semantics": [ + "Uses operation-specific typed fields; mutations require expected_revision and idempotency_key, while list/get/watch use bounded cursors and typed projections." + ], + "contract": { + "operation_owner": "authenticated plugin session; host owns cross-plugin attribution and global facts", + "resource_owner": "caller-owned records by default; foreign shared records require the named grant and explicit scope", + "pagination": { + "supported": false, + "max_page_size": 200, + "cursor": "opaque, caller/session scoped" + }, + "revision": { + "read": "response carries the observed revision where applicable", + "mutation": "expected_revision required for existing mutable resources; conflict returns MUTATION_OUTCOME_REVISION_CONFLICT" + }, + "idempotency": { + "required": false, + "key_scope": "authenticated plugin plus operation", + "retry": "same key returns the original committed outcome" + }, + "quota": "enforced per method and owner; byte-bearing methods additionally enforce max_bytes and package/session limits", + "commit_authorization": "recheck permission, resource scope and grant revision immediately before side effects" + } + }, + { + "method": "MetadataUpdate", + "request": "MetadataUpdateRequest", + "response": "MutationReply", + "streaming": false, + "owner": "authenticated caller/plugin; host owns global facts and attribution", + "permission": "library.metadata.write", + "semantics": [ + "host-issued operation_id; idempotency_key; expected_revision where applicable; recheck authorization at commit", + "Uses operation-specific typed fields; mutations require expected_revision and idempotency_key, while list/get/watch use bounded cursors and typed projections." + ], + "contract": { + "operation_owner": "authenticated plugin session; host owns cross-plugin attribution and global facts", + "resource_owner": "caller-owned records by default; foreign shared records require the named grant and explicit scope", + "pagination": { + "supported": false, + "max_page_size": 200, + "cursor": "opaque, caller/session scoped" + }, + "revision": { + "read": "response carries the observed revision where applicable", + "mutation": "expected_revision required for existing mutable resources; conflict returns MUTATION_OUTCOME_REVISION_CONFLICT" + }, + "idempotency": { + "required": true, + "key_scope": "authenticated plugin plus operation", + "retry": "same key returns the original committed outcome" + }, + "quota": "enforced per method and owner; byte-bearing methods additionally enforce max_bytes and package/session limits", + "commit_authorization": "recheck permission, resource scope and grant revision immediately before side effects" + } + }, + { + "method": "FavoritesList", + "request": "FavoritesListRequest", + "response": "FavoritesListReply", + "streaming": false, + "owner": "authenticated caller/plugin; host owns global facts and attribution", + "permission": "favorites.read", + "semantics": [ + "Uses operation-specific typed fields; mutations require expected_revision and idempotency_key, while list/get/watch use bounded cursors and typed projections." + ], + "contract": { + "operation_owner": "authenticated plugin session; host owns cross-plugin attribution and global facts", + "resource_owner": "caller-owned records by default; foreign shared records require the named grant and explicit scope", + "pagination": { + "supported": true, + "max_page_size": 200, + "cursor": "opaque, caller/session scoped" + }, + "revision": { + "read": "response carries the observed revision where applicable", + "mutation": "expected_revision required for existing mutable resources; conflict returns MUTATION_OUTCOME_REVISION_CONFLICT" + }, + "idempotency": { + "required": false, + "key_scope": "authenticated plugin plus operation", + "retry": "same key returns the original committed outcome" + }, + "quota": "enforced per method and owner; byte-bearing methods additionally enforce max_bytes and package/session limits", + "commit_authorization": "recheck permission, resource scope and grant revision immediately before side effects" + } + }, + { + "method": "FavoritesSet", + "request": "FavoritesSetRequest", + "response": "MutationReply", + "streaming": false, + "owner": "authenticated caller/plugin; host owns global facts and attribution", + "permission": "favorites.write", + "semantics": [ + "host-issued operation_id; idempotency_key; expected_revision where applicable; recheck authorization at commit", + "Uses operation-specific typed fields; mutations require expected_revision and idempotency_key, while list/get/watch use bounded cursors and typed projections." + ], + "contract": { + "operation_owner": "authenticated plugin session; host owns cross-plugin attribution and global facts", + "resource_owner": "caller-owned records by default; foreign shared records require the named grant and explicit scope", + "pagination": { + "supported": false, + "max_page_size": 200, + "cursor": "opaque, caller/session scoped" + }, + "revision": { + "read": "response carries the observed revision where applicable", + "mutation": "expected_revision required for existing mutable resources; conflict returns MUTATION_OUTCOME_REVISION_CONFLICT" + }, + "idempotency": { + "required": true, + "key_scope": "authenticated plugin plus operation", + "retry": "same key returns the original committed outcome" + }, + "quota": "enforced per method and owner; byte-bearing methods additionally enforce max_bytes and package/session limits", + "commit_authorization": "recheck permission, resource scope and grant revision immediately before side effects" + } + }, + { + "method": "MatchingSearch", + "request": "MatchingSearchRequest", + "response": "MatchingSearchReply", + "streaming": false, + "owner": "authenticated caller/plugin; host owns global facts and attribution", + "permission": "matching.read", + "semantics": [ + "Uses operation-specific typed fields; mutations require expected_revision and idempotency_key, while list/get/watch use bounded cursors and typed projections." + ], + "contract": { + "operation_owner": "authenticated plugin session; host owns cross-plugin attribution and global facts", + "resource_owner": "caller-owned records by default; foreign shared records require the named grant and explicit scope", + "pagination": { + "supported": true, + "max_page_size": 200, + "cursor": "opaque, caller/session scoped" + }, + "revision": { + "read": "response carries the observed revision where applicable", + "mutation": "expected_revision required for existing mutable resources; conflict returns MUTATION_OUTCOME_REVISION_CONFLICT" + }, + "idempotency": { + "required": false, + "key_scope": "authenticated plugin plus operation", + "retry": "same key returns the original committed outcome" + }, + "quota": "enforced per method and owner; byte-bearing methods additionally enforce max_bytes and package/session limits", + "commit_authorization": "recheck permission, resource scope and grant revision immediately before side effects" + } + }, + { + "method": "MatchingAssign", + "request": "MatchingAssignRequest", + "response": "MutationReply", + "streaming": false, + "owner": "authenticated caller/plugin; host owns global facts and attribution", + "permission": "matching.write", + "semantics": [ + "host-issued operation_id; idempotency_key; expected_revision where applicable; recheck authorization at commit", + "Uses operation-specific typed fields; mutations require expected_revision and idempotency_key, while list/get/watch use bounded cursors and typed projections." + ], + "contract": { + "operation_owner": "authenticated plugin session; host owns cross-plugin attribution and global facts", + "resource_owner": "caller-owned records by default; foreign shared records require the named grant and explicit scope", + "pagination": { + "supported": false, + "max_page_size": 200, + "cursor": "opaque, caller/session scoped" + }, + "revision": { + "read": "response carries the observed revision where applicable", + "mutation": "expected_revision required for existing mutable resources; conflict returns MUTATION_OUTCOME_REVISION_CONFLICT" + }, + "idempotency": { + "required": true, + "key_scope": "authenticated plugin plus operation", + "retry": "same key returns the original committed outcome" + }, + "quota": "enforced per method and owner; byte-bearing methods additionally enforce max_bytes and package/session limits", + "commit_authorization": "recheck permission, resource scope and grant revision immediately before side effects" + } + }, + { + "method": "ArtworkRead", + "request": "ArtworkReadRequest", + "response": "ArtworkReadReply", + "streaming": false, + "owner": "authenticated caller/plugin; host owns global facts and attribution", + "permission": "artwork.read", + "semantics": [ + "Uses operation-specific typed fields; mutations require expected_revision and idempotency_key, while list/get/watch use bounded cursors and typed projections." + ], + "contract": { + "operation_owner": "authenticated plugin session; host owns cross-plugin attribution and global facts", + "resource_owner": "caller-owned records by default; foreign shared records require the named grant and explicit scope", + "pagination": { + "supported": false, + "max_page_size": 200, + "cursor": "opaque, caller/session scoped" + }, + "revision": { + "read": "response carries the observed revision where applicable", + "mutation": "expected_revision required for existing mutable resources; conflict returns MUTATION_OUTCOME_REVISION_CONFLICT" + }, + "idempotency": { + "required": false, + "key_scope": "authenticated plugin plus operation", + "retry": "same key returns the original committed outcome" + }, + "quota": "enforced per method and owner; byte-bearing methods additionally enforce max_bytes and package/session limits", + "commit_authorization": "recheck permission, resource scope and grant revision immediately before side effects" + } + }, + { + "method": "ArtworkSet", + "request": "ArtworkSetRequest", + "response": "MutationReply", + "streaming": false, + "owner": "authenticated caller/plugin; host owns global facts and attribution", + "permission": "artwork.write", + "semantics": [ + "host-issued operation_id; idempotency_key; expected_revision where applicable; recheck authorization at commit", + "Uses operation-specific typed fields; mutations require expected_revision and idempotency_key, while list/get/watch use bounded cursors and typed projections." + ], + "contract": { + "operation_owner": "authenticated plugin session; host owns cross-plugin attribution and global facts", + "resource_owner": "caller-owned records by default; foreign shared records require the named grant and explicit scope", + "pagination": { + "supported": false, + "max_page_size": 200, + "cursor": "opaque, caller/session scoped" + }, + "revision": { + "read": "response carries the observed revision where applicable", + "mutation": "expected_revision required for existing mutable resources; conflict returns MUTATION_OUTCOME_REVISION_CONFLICT" + }, + "idempotency": { + "required": true, + "key_scope": "authenticated plugin plus operation", + "retry": "same key returns the original committed outcome" + }, + "quota": "enforced per method and owner; byte-bearing methods additionally enforce max_bytes and package/session limits", + "commit_authorization": "recheck permission, resource scope and grant revision immediately before side effects" + } + }, + { + "method": "GamesRequestLaunch", + "request": "GameLaunchRequest", + "response": "GameLaunchReply", + "streaming": false, + "owner": "authenticated caller/plugin; host owns global facts and attribution", + "permission": "game.launch", + "semantics": [ + "host-issued operation_id; idempotency_key; expected_revision where applicable; recheck authorization at commit", + "uses approved detected launch target and stored parameters; no per-call overrides" + ], + "contract": { + "operation_owner": "authenticated plugin session; host owns cross-plugin attribution and global facts", + "resource_owner": "caller-owned records by default; foreign shared records require the named grant and explicit scope", + "pagination": { + "supported": false, + "max_page_size": 200, + "cursor": "opaque, caller/session scoped" + }, + "revision": { + "read": "response carries the observed revision where applicable", + "mutation": "expected_revision required for existing mutable resources; conflict returns MUTATION_OUTCOME_REVISION_CONFLICT" + }, + "idempotency": { + "required": true, + "key_scope": "authenticated plugin plus operation", + "retry": "same key returns the original committed outcome" + }, + "quota": "enforced per method and owner; byte-bearing methods additionally enforce max_bytes and package/session limits", + "commit_authorization": "recheck permission, resource scope and grant revision immediately before side effects" + } + }, + { + "method": "GamesProposeCustomLaunch", + "request": "CustomLaunchRequest", + "response": "CustomLaunchReply", + "streaming": false, + "owner": "authenticated caller/plugin; host owns global facts and attribution", + "permission": "game.custom_launch", + "semantics": [ + "host-issued operation_id; idempotency_key; expected_revision where applicable; recheck authorization at commit", + "separate game.custom_launch grant and explicit reviewed recipe; never aliases game.launch" + ], + "contract": { + "operation_owner": "authenticated plugin session; host owns cross-plugin attribution and global facts", + "resource_owner": "caller-owned records by default; foreign shared records require the named grant and explicit scope", + "pagination": { + "supported": false, + "max_page_size": 200, + "cursor": "opaque, caller/session scoped" + }, + "revision": { + "read": "response carries the observed revision where applicable", + "mutation": "expected_revision required for existing mutable resources; conflict returns MUTATION_OUTCOME_REVISION_CONFLICT" + }, + "idempotency": { + "required": true, + "key_scope": "authenticated plugin plus operation", + "retry": "same key returns the original committed outcome" + }, + "quota": "enforced per method and owner; byte-bearing methods additionally enforce max_bytes and package/session limits", + "commit_authorization": "recheck permission, resource scope and grant revision immediately before side effects" + } + }, + { + "method": "GamesRequestCustomLaunch", + "request": "CustomLaunchRequest", + "response": "CustomLaunchReply", + "streaming": false, + "owner": "authenticated caller/plugin; host owns global facts and attribution", + "permission": "game.custom_launch", + "semantics": [ + "host-issued operation_id; idempotency_key; expected_revision where applicable; recheck authorization at commit", + "separate game.custom_launch grant and explicit reviewed recipe; never aliases game.launch" + ], + "contract": { + "operation_owner": "authenticated plugin session; host owns cross-plugin attribution and global facts", + "resource_owner": "caller-owned records by default; foreign shared records require the named grant and explicit scope", + "pagination": { + "supported": false, + "max_page_size": 200, + "cursor": "opaque, caller/session scoped" + }, + "revision": { + "read": "response carries the observed revision where applicable", + "mutation": "expected_revision required for existing mutable resources; conflict returns MUTATION_OUTCOME_REVISION_CONFLICT" + }, + "idempotency": { + "required": true, + "key_scope": "authenticated plugin plus operation", + "retry": "same key returns the original committed outcome" + }, + "quota": "enforced per method and owner; byte-bearing methods additionally enforce max_bytes and package/session limits", + "commit_authorization": "recheck permission, resource scope and grant revision immediately before side effects" + } + }, + { + "method": "GamesRemoveCustomLaunch", + "request": "CustomLaunchRemoveRequest", + "response": "MutationReply", + "streaming": false, + "owner": "authenticated caller/plugin; host owns global facts and attribution", + "permission": "game.custom_launch", + "semantics": [ + "host-issued operation_id; idempotency_key; expected_revision where applicable; recheck authorization at commit", + "separate game.custom_launch grant and explicit reviewed recipe; never aliases game.launch", + "Typed request/response fields define operation inputs, outputs, and mutation outcomes; host validates ownership and authorization at commit.", + "Typed request/response fields define operation inputs, outputs, pagination or mutation outcomes; host validates ownership and authorization at commit." + ], + "contract": { + "operation_owner": "authenticated plugin session; host owns cross-plugin attribution and global facts", + "resource_owner": "caller-owned records by default; foreign shared records require the named grant and explicit scope", + "pagination": { + "supported": false, + "max_page_size": 200, + "cursor": "opaque, caller/session scoped" + }, + "revision": { + "read": "response carries the observed revision where applicable", + "mutation": "expected_revision required for existing mutable resources; conflict returns MUTATION_OUTCOME_REVISION_CONFLICT" + }, + "idempotency": { + "required": true, + "key_scope": "authenticated plugin plus operation", + "retry": "same key returns the original committed outcome" + }, + "quota": "enforced per method and owner; byte-bearing methods additionally enforce max_bytes and package/session limits", + "commit_authorization": "recheck permission, resource scope and grant revision immediately before side effects" + } + }, + { + "method": "GamesRequestInstall", + "request": "GameInstallRequest", + "response": "JobReply", + "streaming": false, + "owner": "authenticated caller/plugin; host owns global facts and attribution", + "permission": "games.install", + "semantics": [ + "host-issued operation_id; idempotency_key; expected_revision where applicable; recheck authorization at commit", + "Typed request/response fields define operation inputs, outputs, and mutation outcomes; host validates ownership and authorization at commit.", + "Typed request/response fields define operation inputs, outputs, pagination or mutation outcomes; host validates ownership and authorization at commit." + ], + "contract": { + "operation_owner": "authenticated plugin session; host owns cross-plugin attribution and global facts", + "resource_owner": "caller-owned records by default; foreign shared records require the named grant and explicit scope", + "pagination": { + "supported": false, + "max_page_size": 200, + "cursor": "opaque, caller/session scoped" + }, + "revision": { + "read": "response carries the observed revision where applicable", + "mutation": "expected_revision required for existing mutable resources; conflict returns MUTATION_OUTCOME_REVISION_CONFLICT" + }, + "idempotency": { + "required": true, + "key_scope": "authenticated plugin plus operation", + "retry": "same key returns the original committed outcome" + }, + "quota": "enforced per method and owner; byte-bearing methods additionally enforce max_bytes and package/session limits", + "commit_authorization": "recheck permission, resource scope and grant revision immediately before side effects" + } + }, + { + "method": "StorageGet", + "request": "StorageGetRequest", + "response": "StorageGetReply", + "streaming": false, + "owner": "authenticated caller/plugin; host owns global facts and attribution", + "permission": "storage.read", + "semantics": [ + "Typed request/response fields define operation inputs, outputs, and mutation outcomes; host validates ownership and authorization at commit.", + "Typed request/response fields define operation inputs, outputs, pagination or mutation outcomes; host validates ownership and authorization at commit." + ], + "contract": { + "operation_owner": "authenticated plugin session; host owns cross-plugin attribution and global facts", + "resource_owner": "caller-owned records by default; foreign shared records require the named grant and explicit scope", + "pagination": { + "supported": false, + "max_page_size": 200, + "cursor": "opaque, caller/session scoped" + }, + "revision": { + "read": "response carries the observed revision where applicable", + "mutation": "expected_revision required for existing mutable resources; conflict returns MUTATION_OUTCOME_REVISION_CONFLICT" + }, + "idempotency": { + "required": false, + "key_scope": "authenticated plugin plus operation", + "retry": "same key returns the original committed outcome" + }, + "quota": "enforced per method and owner; byte-bearing methods additionally enforce max_bytes and package/session limits", + "commit_authorization": "recheck permission, resource scope and grant revision immediately before side effects" + } + }, + { + "method": "StoragePut", + "request": "StoragePutRequest", + "response": "StorageMutationReply", + "streaming": false, + "owner": "authenticated caller/plugin; host owns global facts and attribution", + "permission": "storage.write + storage.persist (durable)", + "semantics": [ + "host-issued operation_id; idempotency_key; expected_revision where applicable; recheck authorization at commit", + "quota applies; durable mode additionally requires storage.persist", + "Typed request/response fields define operation inputs, outputs, and mutation outcomes; host validates ownership and authorization at commit.", + "Typed request/response fields define operation inputs, outputs, pagination or mutation outcomes; host validates ownership and authorization at commit." + ], + "contract": { + "operation_owner": "authenticated plugin session; host owns cross-plugin attribution and global facts", + "resource_owner": "caller-owned records by default; foreign shared records require the named grant and explicit scope", + "pagination": { + "supported": false, + "max_page_size": 200, + "cursor": "opaque, caller/session scoped" + }, + "revision": { + "read": "response carries the observed revision where applicable", + "mutation": "expected_revision required for existing mutable resources; conflict returns MUTATION_OUTCOME_REVISION_CONFLICT" + }, + "idempotency": { + "required": true, + "key_scope": "authenticated plugin plus operation", + "retry": "same key returns the original committed outcome" + }, + "quota": "enforced per method and owner; byte-bearing methods additionally enforce max_bytes and package/session limits", + "commit_authorization": "recheck permission, resource scope and grant revision immediately before side effects" + } + }, + { + "method": "StorageDelete", + "request": "StorageDeleteRequest", + "response": "MutationReply", + "streaming": false, + "owner": "authenticated caller/plugin; host owns global facts and attribution", + "permission": "storage.delete", + "semantics": [ + "host-issued operation_id; idempotency_key; expected_revision where applicable; recheck authorization at commit", + "Typed request/response fields define operation inputs, outputs, and mutation outcomes; host validates ownership and authorization at commit.", + "Typed request/response fields define operation inputs, outputs, pagination or mutation outcomes; host validates ownership and authorization at commit." + ], + "contract": { + "operation_owner": "authenticated plugin session; host owns cross-plugin attribution and global facts", + "resource_owner": "caller-owned records by default; foreign shared records require the named grant and explicit scope", + "pagination": { + "supported": false, + "max_page_size": 200, + "cursor": "opaque, caller/session scoped" + }, + "revision": { + "read": "response carries the observed revision where applicable", + "mutation": "expected_revision required for existing mutable resources; conflict returns MUTATION_OUTCOME_REVISION_CONFLICT" + }, + "idempotency": { + "required": true, + "key_scope": "authenticated plugin plus operation", + "retry": "same key returns the original committed outcome" + }, + "quota": "enforced per method and owner; byte-bearing methods additionally enforce max_bytes and package/session limits", + "commit_authorization": "recheck permission, resource scope and grant revision immediately before side effects" + } + }, + { + "method": "FilesRequestAccess", + "request": "FilesRequestAccessRequest", + "response": "FileAccessReply", + "streaming": false, + "owner": "authenticated caller/plugin; host owns global facts and attribution", + "permission": "files.read/write/delete (user-approved scope)", + "semantics": [ + "Typed request/response fields define operation inputs, outputs, and mutation outcomes; host validates ownership and authorization at commit.", + "Typed request/response fields define operation inputs, outputs, pagination or mutation outcomes; host validates ownership and authorization at commit." + ], + "contract": { + "operation_owner": "authenticated plugin session; host owns cross-plugin attribution and global facts", + "resource_owner": "caller-owned records by default; foreign shared records require the named grant and explicit scope", + "pagination": { + "supported": false, + "max_page_size": 200, + "cursor": "opaque, caller/session scoped" + }, + "revision": { + "read": "response carries the observed revision where applicable", + "mutation": "expected_revision required for existing mutable resources; conflict returns MUTATION_OUTCOME_REVISION_CONFLICT" + }, + "idempotency": { + "required": true, + "key_scope": "authenticated plugin plus operation", + "retry": "same key returns the original committed outcome" + }, + "quota": "enforced per method and owner; byte-bearing methods additionally enforce max_bytes and package/session limits", + "commit_authorization": "recheck permission, resource scope and grant revision immediately before side effects" + } + }, + { + "method": "FilesList", + "request": "FilesListRequest", + "response": "FilesListReply", + "streaming": false, + "owner": "authenticated caller/plugin; host owns global facts and attribution", + "permission": "files.read", + "semantics": [ + "cursor/page_size fields are available; host enforces method-specific bounds and opaque cursors", + "Typed request/response fields define operation inputs, outputs, and mutation outcomes; host validates ownership and authorization at commit.", + "Typed request/response fields define operation inputs, outputs, pagination or mutation outcomes; host validates ownership and authorization at commit." + ], + "contract": { + "operation_owner": "authenticated plugin session; host owns cross-plugin attribution and global facts", + "resource_owner": "caller-owned records by default; foreign shared records require the named grant and explicit scope", + "pagination": { + "supported": true, + "max_page_size": 200, + "cursor": "opaque, caller/session scoped" + }, + "revision": { + "read": "response carries the observed revision where applicable", + "mutation": "expected_revision required for existing mutable resources; conflict returns MUTATION_OUTCOME_REVISION_CONFLICT" + }, + "idempotency": { + "required": false, + "key_scope": "authenticated plugin plus operation", + "retry": "same key returns the original committed outcome" + }, + "quota": "enforced per method and owner; byte-bearing methods additionally enforce max_bytes and package/session limits", + "commit_authorization": "recheck permission, resource scope and grant revision immediately before side effects" + } + }, + { + "method": "FilesRead", + "request": "FilesReadRequest", + "response": "FileReadReply", + "streaming": false, + "owner": "authenticated caller/plugin; host owns global facts and attribution", + "permission": "files.read", + "semantics": [ + "Typed request/response fields define operation inputs, outputs, and mutation outcomes; host validates ownership and authorization at commit.", + "Typed request/response fields define operation inputs, outputs, pagination or mutation outcomes; host validates ownership and authorization at commit." + ], + "contract": { + "operation_owner": "authenticated plugin session; host owns cross-plugin attribution and global facts", + "resource_owner": "caller-owned records by default; foreign shared records require the named grant and explicit scope", + "pagination": { + "supported": false, + "max_page_size": 200, + "cursor": "opaque, caller/session scoped" + }, + "revision": { + "read": "response carries the observed revision where applicable", + "mutation": "expected_revision required for existing mutable resources; conflict returns MUTATION_OUTCOME_REVISION_CONFLICT" + }, + "idempotency": { + "required": false, + "key_scope": "authenticated plugin plus operation", + "retry": "same key returns the original committed outcome" + }, + "quota": "enforced per method and owner; byte-bearing methods additionally enforce max_bytes and package/session limits", + "commit_authorization": "recheck permission, resource scope and grant revision immediately before side effects" + } + }, + { + "method": "FilesWrite", + "request": "FilesWriteRequest", + "response": "MutationReply", + "streaming": false, + "owner": "authenticated caller/plugin; host owns global facts and attribution", + "permission": "files.write", + "semantics": [ + "host-issued operation_id; idempotency_key; expected_revision where applicable; recheck authorization at commit", + "Typed request/response fields define operation inputs, outputs, and mutation outcomes; host validates ownership and authorization at commit.", + "Typed request/response fields define operation inputs, outputs, pagination or mutation outcomes; host validates ownership and authorization at commit." + ], + "contract": { + "operation_owner": "authenticated plugin session; host owns cross-plugin attribution and global facts", + "resource_owner": "caller-owned records by default; foreign shared records require the named grant and explicit scope", + "pagination": { + "supported": false, + "max_page_size": 200, + "cursor": "opaque, caller/session scoped" + }, + "revision": { + "read": "response carries the observed revision where applicable", + "mutation": "expected_revision required for existing mutable resources; conflict returns MUTATION_OUTCOME_REVISION_CONFLICT" + }, + "idempotency": { + "required": true, + "key_scope": "authenticated plugin plus operation", + "retry": "same key returns the original committed outcome" + }, + "quota": "enforced per method and owner; byte-bearing methods additionally enforce max_bytes and package/session limits", + "commit_authorization": "recheck permission, resource scope and grant revision immediately before side effects" + } + }, + { + "method": "FilesDelete", + "request": "FilesDeleteRequest", + "response": "MutationReply", + "streaming": false, + "owner": "authenticated caller/plugin; host owns global facts and attribution", + "permission": "files.delete", + "semantics": [ + "host-issued operation_id; idempotency_key; expected_revision where applicable; recheck authorization at commit", + "Typed request/response fields define operation inputs, outputs, and mutation outcomes; host validates ownership and authorization at commit.", + "Typed request/response fields define operation inputs, outputs, pagination or mutation outcomes; host validates ownership and authorization at commit." + ], + "contract": { + "operation_owner": "authenticated plugin session; host owns cross-plugin attribution and global facts", + "resource_owner": "caller-owned records by default; foreign shared records require the named grant and explicit scope", + "pagination": { + "supported": false, + "max_page_size": 200, + "cursor": "opaque, caller/session scoped" + }, + "revision": { + "read": "response carries the observed revision where applicable", + "mutation": "expected_revision required for existing mutable resources; conflict returns MUTATION_OUTCOME_REVISION_CONFLICT" + }, + "idempotency": { + "required": true, + "key_scope": "authenticated plugin plus operation", + "retry": "same key returns the original committed outcome" + }, + "quota": "enforced per method and owner; byte-bearing methods additionally enforce max_bytes and package/session limits", + "commit_authorization": "recheck permission, resource scope and grant revision immediately before side effects" + } + }, + { + "method": "NetworkFetch", + "request": "NetworkFetchRequest", + "response": "NetworkFetchReply", + "streaming": false, + "owner": "authenticated caller/plugin; host owns global facts and attribution", + "permission": "network.fetch", + "semantics": [ + "host-issued operation_id; idempotency_key; expected_revision where applicable; recheck authorization at commit", + "Typed request/response fields define operation inputs, outputs, and mutation outcomes; host validates ownership and authorization at commit.", + "Typed request/response fields define operation inputs, outputs, pagination or mutation outcomes; host validates ownership and authorization at commit." + ], + "contract": { + "operation_owner": "authenticated plugin session; host owns cross-plugin attribution and global facts", + "resource_owner": "caller-owned records by default; foreign shared records require the named grant and explicit scope", + "pagination": { + "supported": false, + "max_page_size": 200, + "cursor": "opaque, caller/session scoped" + }, + "revision": { + "read": "response carries the observed revision where applicable", + "mutation": "expected_revision required for existing mutable resources; conflict returns MUTATION_OUTCOME_REVISION_CONFLICT" + }, + "idempotency": { + "required": true, + "key_scope": "authenticated plugin plus operation", + "retry": "same key returns the original committed outcome" + }, + "quota": "enforced per method and owner; byte-bearing methods additionally enforce max_bytes and package/session limits", + "commit_authorization": "recheck permission, resource scope and grant revision immediately before side effects" + } + }, + { + "method": "NotificationsPublish", + "request": "NotificationPublishRequest", + "response": "MutationReply", + "streaming": false, + "owner": "authenticated caller/plugin; host owns global facts and attribution", + "permission": "notifications.publish", + "semantics": [ + "host-issued operation_id; idempotency_key; expected_revision where applicable; recheck authorization at commit", + "Typed request/response fields define operation inputs, outputs, and mutation outcomes; host validates ownership and authorization at commit.", + "Typed request/response fields define operation inputs, outputs, pagination or mutation outcomes; host validates ownership and authorization at commit." + ], + "contract": { + "operation_owner": "authenticated plugin session; host owns cross-plugin attribution and global facts", + "resource_owner": "caller-owned records by default; foreign shared records require the named grant and explicit scope", + "pagination": { + "supported": false, + "max_page_size": 200, + "cursor": "opaque, caller/session scoped" + }, + "revision": { + "read": "response carries the observed revision where applicable", + "mutation": "expected_revision required for existing mutable resources; conflict returns MUTATION_OUTCOME_REVISION_CONFLICT" + }, + "idempotency": { + "required": true, + "key_scope": "authenticated plugin plus operation", + "retry": "same key returns the original committed outcome" + }, + "quota": "enforced per method and owner; byte-bearing methods additionally enforce max_bytes and package/session limits", + "commit_authorization": "recheck permission, resource scope and grant revision immediately before side effects" + } + }, + { + "method": "BackupsList", + "request": "BackupsListRequest", + "response": "BackupsListReply", + "streaming": false, + "owner": "authenticated caller/plugin; host owns global facts and attribution", + "permission": "backups.read", + "semantics": [ + "cursor/page_size fields are available; host enforces method-specific bounds and opaque cursors", + "Typed request/response fields define operation inputs, outputs, and mutation outcomes; host validates ownership and authorization at commit.", + "Typed request/response fields define operation inputs, outputs, pagination or mutation outcomes; host validates ownership and authorization at commit." + ], + "contract": { + "operation_owner": "authenticated plugin session; host owns cross-plugin attribution and global facts", + "resource_owner": "caller-owned records by default; foreign shared records require the named grant and explicit scope", + "pagination": { + "supported": true, + "max_page_size": 200, + "cursor": "opaque, caller/session scoped" + }, + "revision": { + "read": "response carries the observed revision where applicable", + "mutation": "expected_revision required for existing mutable resources; conflict returns MUTATION_OUTCOME_REVISION_CONFLICT" + }, + "idempotency": { + "required": false, + "key_scope": "authenticated plugin plus operation", + "retry": "same key returns the original committed outcome" + }, + "quota": "enforced per method and owner; byte-bearing methods additionally enforce max_bytes and package/session limits", + "commit_authorization": "recheck permission, resource scope and grant revision immediately before side effects" + } + }, + { + "method": "BackupsRequestCreate", + "request": "BackupCreateRequest", + "response": "JobReply", + "streaming": false, + "owner": "authenticated caller/plugin; host owns global facts and attribution", + "permission": "backups.create", + "semantics": [ + "host-issued operation_id; idempotency_key; expected_revision where applicable; recheck authorization at commit", + "Typed request/response fields define operation inputs, outputs, and mutation outcomes; host validates ownership and authorization at commit.", + "Typed request/response fields define operation inputs, outputs, pagination or mutation outcomes; host validates ownership and authorization at commit." + ], + "contract": { + "operation_owner": "authenticated plugin session; host owns cross-plugin attribution and global facts", + "resource_owner": "caller-owned records by default; foreign shared records require the named grant and explicit scope", + "pagination": { + "supported": false, + "max_page_size": 200, + "cursor": "opaque, caller/session scoped" + }, + "revision": { + "read": "response carries the observed revision where applicable", + "mutation": "expected_revision required for existing mutable resources; conflict returns MUTATION_OUTCOME_REVISION_CONFLICT" + }, + "idempotency": { + "required": true, + "key_scope": "authenticated plugin plus operation", + "retry": "same key returns the original committed outcome" + }, + "quota": "enforced per method and owner; byte-bearing methods additionally enforce max_bytes and package/session limits", + "commit_authorization": "recheck permission, resource scope and grant revision immediately before side effects" + } + }, + { + "method": "BackupsRequestRestore", + "request": "BackupRestoreRequest", + "response": "JobReply", + "streaming": false, + "owner": "authenticated caller/plugin; host owns global facts and attribution", + "permission": "backups.restore", + "semantics": [ + "host-issued operation_id; idempotency_key; expected_revision where applicable; recheck authorization at commit", + "Typed request/response fields define operation inputs, outputs, and mutation outcomes; host validates ownership and authorization at commit.", + "Typed request/response fields define operation inputs, outputs, pagination or mutation outcomes; host validates ownership and authorization at commit." + ], + "contract": { + "operation_owner": "authenticated plugin session; host owns cross-plugin attribution and global facts", + "resource_owner": "caller-owned records by default; foreign shared records require the named grant and explicit scope", + "pagination": { + "supported": false, + "max_page_size": 200, + "cursor": "opaque, caller/session scoped" + }, + "revision": { + "read": "response carries the observed revision where applicable", + "mutation": "expected_revision required for existing mutable resources; conflict returns MUTATION_OUTCOME_REVISION_CONFLICT" + }, + "idempotency": { + "required": true, + "key_scope": "authenticated plugin plus operation", + "retry": "same key returns the original committed outcome" + }, + "quota": "enforced per method and owner; byte-bearing methods additionally enforce max_bytes and package/session limits", + "commit_authorization": "recheck permission, resource scope and grant revision immediately before side effects" + } + }, + { + "method": "LibrariesList", + "request": "DomainListRequest", + "response": "LibrariesListReply", + "streaming": false, + "owner": "authenticated caller/plugin; host owns global facts and attribution", + "permission": "library.roots.read", + "semantics": [ + "cursor/page_size fields are available; host enforces method-specific bounds and opaque cursors", + "Typed request/response fields define operation inputs, outputs, and mutation outcomes; host validates ownership and authorization at commit.", + "Typed request/response fields define operation inputs, outputs, pagination or mutation outcomes; host validates ownership and authorization at commit." + ], + "contract": { + "operation_owner": "authenticated plugin session; host owns cross-plugin attribution and global facts", + "resource_owner": "caller-owned records by default; foreign shared records require the named grant and explicit scope", + "pagination": { + "supported": true, + "max_page_size": 200, + "cursor": "opaque, caller/session scoped" + }, + "revision": { + "read": "response carries the observed revision where applicable", + "mutation": "expected_revision required for existing mutable resources; conflict returns MUTATION_OUTCOME_REVISION_CONFLICT" + }, + "idempotency": { + "required": false, + "key_scope": "authenticated plugin plus operation", + "retry": "same key returns the original committed outcome" + }, + "quota": "enforced per method and owner; byte-bearing methods additionally enforce max_bytes and package/session limits", + "commit_authorization": "recheck permission, resource scope and grant revision immediately before side effects" + } + }, + { + "method": "LibrariesGet", + "request": "DomainGetRequest", + "response": "LibraryRecordReply", + "streaming": false, + "owner": "authenticated caller/plugin; host owns global facts and attribution", + "permission": "library.roots.read", + "semantics": [ + "Typed request/response fields define operation inputs, outputs, and mutation outcomes; host validates ownership and authorization at commit.", + "Typed request/response fields define operation inputs, outputs, pagination or mutation outcomes; host validates ownership and authorization at commit." + ], + "contract": { + "operation_owner": "authenticated plugin session; host owns cross-plugin attribution and global facts", + "resource_owner": "caller-owned records by default; foreign shared records require the named grant and explicit scope", + "pagination": { + "supported": false, + "max_page_size": 200, + "cursor": "opaque, caller/session scoped" + }, + "revision": { + "read": "response carries the observed revision where applicable", + "mutation": "expected_revision required for existing mutable resources; conflict returns MUTATION_OUTCOME_REVISION_CONFLICT" + }, + "idempotency": { + "required": false, + "key_scope": "authenticated plugin plus operation", + "retry": "same key returns the original committed outcome" + }, + "quota": "enforced per method and owner; byte-bearing methods additionally enforce max_bytes and package/session limits", + "commit_authorization": "recheck permission, resource scope and grant revision immediately before side effects" + } + }, + { + "method": "LibrariesWatch", + "request": "DomainWatchRequest", + "response": "LibraryRecordEvent", + "streaming": true, + "owner": "authenticated caller/plugin; host owns global facts and attribution", + "permission": "library.roots.read", + "semantics": [ + "Typed request/response fields define operation inputs, outputs, and mutation outcomes; host validates ownership and authorization at commit.", + "Typed request/response fields define operation inputs, outputs, pagination or mutation outcomes; host validates ownership and authorization at commit." + ], + "contract": { + "operation_owner": "authenticated plugin session; host owns cross-plugin attribution and global facts", + "resource_owner": "caller-owned records by default; foreign shared records require the named grant and explicit scope", + "pagination": { + "supported": false, + "max_page_size": 200, + "cursor": "opaque, caller/session scoped" + }, + "revision": { + "read": "response carries the observed revision where applicable", + "mutation": "expected_revision required for existing mutable resources; conflict returns MUTATION_OUTCOME_REVISION_CONFLICT" + }, + "idempotency": { + "required": false, + "key_scope": "authenticated plugin plus operation", + "retry": "same key returns the original committed outcome" + }, + "quota": "enforced per method and owner; byte-bearing methods additionally enforce max_bytes and package/session limits", + "commit_authorization": "recheck permission, resource scope and grant revision immediately before side effects" + } + }, + { + "method": "LibrariesCreate", + "request": "LibraryCreateRequest", + "response": "LibraryMutationReply", + "streaming": false, + "owner": "authenticated caller/plugin; host owns global facts and attribution", + "permission": "library.roots.create", + "semantics": [ + "host-issued operation_id; idempotency_key; expected_revision where applicable; recheck authorization at commit", + "Typed request/response fields define operation inputs, outputs, and mutation outcomes; host validates ownership and authorization at commit.", + "Typed request/response fields define operation inputs, outputs, pagination or mutation outcomes; host validates ownership and authorization at commit." + ], + "contract": { + "operation_owner": "authenticated plugin session; host owns cross-plugin attribution and global facts", + "resource_owner": "caller-owned records by default; foreign shared records require the named grant and explicit scope", + "pagination": { + "supported": false, + "max_page_size": 200, + "cursor": "opaque, caller/session scoped" + }, + "revision": { + "read": "response carries the observed revision where applicable", + "mutation": "expected_revision required for existing mutable resources; conflict returns MUTATION_OUTCOME_REVISION_CONFLICT" + }, + "idempotency": { + "required": true, + "key_scope": "authenticated plugin plus operation", + "retry": "same key returns the original committed outcome" + }, + "quota": "enforced per method and owner; byte-bearing methods additionally enforce max_bytes and package/session limits", + "commit_authorization": "recheck permission, resource scope and grant revision immediately before side effects" + } + }, + { + "method": "LibrariesUpdate", + "request": "LibraryUpdateRequest", + "response": "LibraryMutationReply", + "streaming": false, + "owner": "authenticated caller/plugin; host owns global facts and attribution", + "permission": "library.roots.update", + "semantics": [ + "host-issued operation_id; idempotency_key; expected_revision where applicable; recheck authorization at commit", + "Typed request/response fields define operation inputs, outputs, and mutation outcomes; host validates ownership and authorization at commit.", + "Typed request/response fields define operation inputs, outputs, pagination or mutation outcomes; host validates ownership and authorization at commit." + ], + "contract": { + "operation_owner": "authenticated plugin session; host owns cross-plugin attribution and global facts", + "resource_owner": "caller-owned records by default; foreign shared records require the named grant and explicit scope", + "pagination": { + "supported": false, + "max_page_size": 200, + "cursor": "opaque, caller/session scoped" + }, + "revision": { + "read": "response carries the observed revision where applicable", + "mutation": "expected_revision required for existing mutable resources; conflict returns MUTATION_OUTCOME_REVISION_CONFLICT" + }, + "idempotency": { + "required": true, + "key_scope": "authenticated plugin plus operation", + "retry": "same key returns the original committed outcome" + }, + "quota": "enforced per method and owner; byte-bearing methods additionally enforce max_bytes and package/session limits", + "commit_authorization": "recheck permission, resource scope and grant revision immediately before side effects" + } + }, + { + "method": "LibrariesRemove", + "request": "DomainRemoveRequest", + "response": "MutationReply", + "streaming": false, + "owner": "authenticated caller/plugin; host owns global facts and attribution", + "permission": "library.roots.delete", + "semantics": [ + "host-issued operation_id; idempotency_key; expected_revision where applicable; recheck authorization at commit", + "Typed request/response fields define operation inputs, outputs, and mutation outcomes; host validates ownership and authorization at commit.", + "Typed request/response fields define operation inputs, outputs, pagination or mutation outcomes; host validates ownership and authorization at commit." + ], + "contract": { + "operation_owner": "authenticated plugin session; host owns cross-plugin attribution and global facts", + "resource_owner": "caller-owned records by default; foreign shared records require the named grant and explicit scope", + "pagination": { + "supported": false, + "max_page_size": 200, + "cursor": "opaque, caller/session scoped" + }, + "revision": { + "read": "response carries the observed revision where applicable", + "mutation": "expected_revision required for existing mutable resources; conflict returns MUTATION_OUTCOME_REVISION_CONFLICT" + }, + "idempotency": { + "required": true, + "key_scope": "authenticated plugin plus operation", + "retry": "same key returns the original committed outcome" + }, + "quota": "enforced per method and owner; byte-bearing methods additionally enforce max_bytes and package/session limits", + "commit_authorization": "recheck permission, resource scope and grant revision immediately before side effects" + } + }, + { + "method": "LibrariesAddRoot", + "request": "LibraryRootAddRequest", + "response": "LibraryMutationReply", + "streaming": false, + "owner": "authenticated caller/plugin; host owns global facts and attribution", + "permission": "library.roots.create", + "semantics": [ + "host-issued operation_id; idempotency_key; expected_revision where applicable; recheck authorization at commit", + "Typed request/response fields define operation inputs, outputs, and mutation outcomes; host validates ownership and authorization at commit.", + "Typed request/response fields define operation inputs, outputs, pagination or mutation outcomes; host validates ownership and authorization at commit." + ], + "contract": { + "operation_owner": "authenticated plugin session; host owns cross-plugin attribution and global facts", + "resource_owner": "caller-owned records by default; foreign shared records require the named grant and explicit scope", + "pagination": { + "supported": false, + "max_page_size": 200, + "cursor": "opaque, caller/session scoped" + }, + "revision": { + "read": "response carries the observed revision where applicable", + "mutation": "expected_revision required for existing mutable resources; conflict returns MUTATION_OUTCOME_REVISION_CONFLICT" + }, + "idempotency": { + "required": true, + "key_scope": "authenticated plugin plus operation", + "retry": "same key returns the original committed outcome" + }, + "quota": "enforced per method and owner; byte-bearing methods additionally enforce max_bytes and package/session limits", + "commit_authorization": "recheck permission, resource scope and grant revision immediately before side effects" + } + }, + { + "method": "LibrariesUpdateRoot", + "request": "LibraryRootUpdateRequest", + "response": "LibraryMutationReply", + "streaming": false, + "owner": "authenticated caller/plugin; host owns global facts and attribution", + "permission": "library.roots.update", + "semantics": [ + "host-issued operation_id; idempotency_key; expected_revision where applicable; recheck authorization at commit", + "Typed request/response fields define operation inputs, outputs, and mutation outcomes; host validates ownership and authorization at commit.", + "Typed request/response fields define operation inputs, outputs, pagination or mutation outcomes; host validates ownership and authorization at commit." + ], + "contract": { + "operation_owner": "authenticated plugin session; host owns cross-plugin attribution and global facts", + "resource_owner": "caller-owned records by default; foreign shared records require the named grant and explicit scope", + "pagination": { + "supported": false, + "max_page_size": 200, + "cursor": "opaque, caller/session scoped" + }, + "revision": { + "read": "response carries the observed revision where applicable", + "mutation": "expected_revision required for existing mutable resources; conflict returns MUTATION_OUTCOME_REVISION_CONFLICT" + }, + "idempotency": { + "required": true, + "key_scope": "authenticated plugin plus operation", + "retry": "same key returns the original committed outcome" + }, + "quota": "enforced per method and owner; byte-bearing methods additionally enforce max_bytes and package/session limits", + "commit_authorization": "recheck permission, resource scope and grant revision immediately before side effects" + } + }, + { + "method": "LibrariesRemoveRoot", + "request": "LibraryRootRemoveRequest", + "response": "MutationReply", + "streaming": false, + "owner": "authenticated caller/plugin; host owns global facts and attribution", + "permission": "library.roots.delete", + "semantics": [ + "host-issued operation_id; idempotency_key; expected_revision where applicable; recheck authorization at commit", + "Typed request/response fields define operation inputs, outputs, and mutation outcomes; host validates ownership and authorization at commit.", + "Typed request/response fields define operation inputs, outputs, pagination or mutation outcomes; host validates ownership and authorization at commit." + ], + "contract": { + "operation_owner": "authenticated plugin session; host owns cross-plugin attribution and global facts", + "resource_owner": "caller-owned records by default; foreign shared records require the named grant and explicit scope", + "pagination": { + "supported": false, + "max_page_size": 200, + "cursor": "opaque, caller/session scoped" + }, + "revision": { + "read": "response carries the observed revision where applicable", + "mutation": "expected_revision required for existing mutable resources; conflict returns MUTATION_OUTCOME_REVISION_CONFLICT" + }, + "idempotency": { + "required": true, + "key_scope": "authenticated plugin plus operation", + "retry": "same key returns the original committed outcome" + }, + "quota": "enforced per method and owner; byte-bearing methods additionally enforce max_bytes and package/session limits", + "commit_authorization": "recheck permission, resource scope and grant revision immediately before side effects" + } + }, + { + "method": "RuntimesList", + "request": "DomainListRequest", + "response": "RuntimesListReply", + "streaming": false, + "owner": "authenticated caller/plugin; host owns global facts and attribution", + "permission": "game.runtime.read", + "semantics": [ + "cursor/page_size fields are available; host enforces method-specific bounds and opaque cursors", + "Typed request/response fields define operation inputs, outputs, and mutation outcomes; host validates ownership and authorization at commit.", + "Typed request/response fields define operation inputs, outputs, pagination or mutation outcomes; host validates ownership and authorization at commit." + ], + "contract": { + "operation_owner": "authenticated plugin session; host owns cross-plugin attribution and global facts", + "resource_owner": "caller-owned records by default; foreign shared records require the named grant and explicit scope", + "pagination": { + "supported": true, + "max_page_size": 200, + "cursor": "opaque, caller/session scoped" + }, + "revision": { + "read": "response carries the observed revision where applicable", + "mutation": "expected_revision required for existing mutable resources; conflict returns MUTATION_OUTCOME_REVISION_CONFLICT" + }, + "idempotency": { + "required": false, + "key_scope": "authenticated plugin plus operation", + "retry": "same key returns the original committed outcome" + }, + "quota": "enforced per method and owner; byte-bearing methods additionally enforce max_bytes and package/session limits", + "commit_authorization": "recheck permission, resource scope and grant revision immediately before side effects" + } + }, + { + "method": "RuntimesGet", + "request": "DomainGetRequest", + "response": "RuntimeRecordReply", + "streaming": false, + "owner": "authenticated caller/plugin; host owns global facts and attribution", + "permission": "game.runtime.read", + "semantics": [ + "Typed request/response fields define operation inputs, outputs, and mutation outcomes; host validates ownership and authorization at commit.", + "Typed request/response fields define operation inputs, outputs, pagination or mutation outcomes; host validates ownership and authorization at commit." + ], + "contract": { + "operation_owner": "authenticated plugin session; host owns cross-plugin attribution and global facts", + "resource_owner": "caller-owned records by default; foreign shared records require the named grant and explicit scope", + "pagination": { + "supported": false, + "max_page_size": 200, + "cursor": "opaque, caller/session scoped" + }, + "revision": { + "read": "response carries the observed revision where applicable", + "mutation": "expected_revision required for existing mutable resources; conflict returns MUTATION_OUTCOME_REVISION_CONFLICT" + }, + "idempotency": { + "required": false, + "key_scope": "authenticated plugin plus operation", + "retry": "same key returns the original committed outcome" + }, + "quota": "enforced per method and owner; byte-bearing methods additionally enforce max_bytes and package/session limits", + "commit_authorization": "recheck permission, resource scope and grant revision immediately before side effects" + } + }, + { + "method": "RuntimesWatch", + "request": "DomainWatchRequest", + "response": "RuntimeRecordEvent", + "streaming": true, + "owner": "authenticated caller/plugin; host owns global facts and attribution", + "permission": "game.runtime.read", + "semantics": [ + "Typed request/response fields define operation inputs, outputs, and mutation outcomes; host validates ownership and authorization at commit.", + "Typed request/response fields define operation inputs, outputs, pagination or mutation outcomes; host validates ownership and authorization at commit." + ], + "contract": { + "operation_owner": "authenticated plugin session; host owns cross-plugin attribution and global facts", + "resource_owner": "caller-owned records by default; foreign shared records require the named grant and explicit scope", + "pagination": { + "supported": false, + "max_page_size": 200, + "cursor": "opaque, caller/session scoped" + }, + "revision": { + "read": "response carries the observed revision where applicable", + "mutation": "expected_revision required for existing mutable resources; conflict returns MUTATION_OUTCOME_REVISION_CONFLICT" + }, + "idempotency": { + "required": false, + "key_scope": "authenticated plugin plus operation", + "retry": "same key returns the original committed outcome" + }, + "quota": "enforced per method and owner; byte-bearing methods additionally enforce max_bytes and package/session limits", + "commit_authorization": "recheck permission, resource scope and grant revision immediately before side effects" + } + }, + { + "method": "RuntimesRequestAccess", + "request": "RuntimeRequestAccessRequest", + "response": "RuntimeMutationReply", + "streaming": false, + "owner": "authenticated caller/plugin; host owns the executable inventory and the approved program", + "permission": "game.runtime.create", + "semantics": [ + "host-issued operation_id; idempotency_key; expected_revision where applicable; recheck authorization at commit", + "The extension supplies a runtime spec with an empty executable_handle plus text executable/desktop hints; the host shows its picker and the user approves one exact program", + "Suggestions come only from host-owned installed-program inventory (PackageKit on Linux, the registry/Start Menu list on Windows); third-party providers never contribute candidates and manual Browse always remains", + "The host validates the regular executable, records its identity, size and SHA-256 in a durable approval and creates the owned runtime; the reply carries no path or handle and never falls back to another path", + "A valid owned runtime for the same name/platform/formats is returned without prompting; a declined picker creates nothing, and a changed executable requires fresh approval" + ], + "contract": { + "operation_owner": "authenticated plugin session; host owns cross-plugin attribution and global facts", + "resource_owner": "caller-owned records by default; foreign shared records require the named grant and explicit scope", + "pagination": { + "supported": false, + "max_page_size": 200, + "cursor": "opaque, caller/session scoped" + }, + "revision": { + "read": "response carries the observed revision where applicable", + "mutation": "expected_revision required for existing mutable resources; conflict returns MUTATION_OUTCOME_REVISION_CONFLICT" + }, + "idempotency": { + "required": true, + "key_scope": "authenticated plugin plus operation", + "retry": "same key returns the original committed outcome" + }, + "quota": "enforced per method and owner; byte-bearing methods additionally enforce max_bytes and package/session limits", + "commit_authorization": "recheck permission, resource scope and grant revision immediately before side effects" + } + }, + { + "method": "RuntimesRegister", + "request": "RuntimeRegisterRequest", + "response": "RuntimeMutationReply", + "streaming": false, + "owner": "authenticated caller/plugin; host owns global facts and attribution", + "permission": "game.runtime.create", + "semantics": [ + "host-issued operation_id; idempotency_key; expected_revision where applicable; recheck authorization at commit", + "RuntimeRecord stores typed platform, supported formats and ordered literal/content_path argv tokens; executable_handle must resolve to an approved file resource and registration never installs software", + "Typed request/response fields define operation inputs, outputs, and mutation outcomes; host validates ownership and authorization at commit.", + "Typed request/response fields define operation inputs, outputs, pagination or mutation outcomes; host validates ownership and authorization at commit." + ], + "contract": { + "operation_owner": "authenticated plugin session; host owns cross-plugin attribution and global facts", + "resource_owner": "caller-owned records by default; foreign shared records require the named grant and explicit scope", + "pagination": { + "supported": false, + "max_page_size": 200, + "cursor": "opaque, caller/session scoped" + }, + "revision": { + "read": "response carries the observed revision where applicable", + "mutation": "expected_revision required for existing mutable resources; conflict returns MUTATION_OUTCOME_REVISION_CONFLICT" + }, + "idempotency": { + "required": true, + "key_scope": "authenticated plugin plus operation", + "retry": "same key returns the original committed outcome" + }, + "quota": "enforced per method and owner; byte-bearing methods additionally enforce max_bytes and package/session limits", + "commit_authorization": "recheck permission, resource scope and grant revision immediately before side effects" + } + }, + { + "method": "RuntimesUpdate", + "request": "RuntimeUpdateRequest", + "response": "RuntimeMutationReply", + "streaming": false, + "owner": "authenticated caller/plugin; host owns global facts and attribution", + "permission": "game.runtime.update", + "semantics": [ + "host-issued operation_id; idempotency_key; expected_revision where applicable; recheck authorization at commit", + "field_mask selects typed runtime fields; executable_handle is revalidated and argv templates remain structured tokens, never shell text", + "Typed request/response fields define operation inputs, outputs, and mutation outcomes; host validates ownership and authorization at commit.", + "Typed request/response fields define operation inputs, outputs, pagination or mutation outcomes; host validates ownership and authorization at commit." + ], + "contract": { + "operation_owner": "authenticated plugin session; host owns cross-plugin attribution and global facts", + "resource_owner": "caller-owned records by default; foreign shared records require the named grant and explicit scope", + "pagination": { + "supported": false, + "max_page_size": 200, + "cursor": "opaque, caller/session scoped" + }, + "revision": { + "read": "response carries the observed revision where applicable", + "mutation": "expected_revision required for existing mutable resources; conflict returns MUTATION_OUTCOME_REVISION_CONFLICT" + }, + "idempotency": { + "required": true, + "key_scope": "authenticated plugin plus operation", + "retry": "same key returns the original committed outcome" + }, + "quota": "enforced per method and owner; byte-bearing methods additionally enforce max_bytes and package/session limits", + "commit_authorization": "recheck permission, resource scope and grant revision immediately before side effects" + } + }, + { + "method": "RuntimesRemove", + "request": "DomainRemoveRequest", + "response": "MutationReply", + "streaming": false, + "owner": "authenticated caller/plugin; host owns global facts and attribution", + "permission": "game.runtime.delete", + "semantics": [ + "host-issued operation_id; idempotency_key; expected_revision where applicable; recheck authorization at commit", + "Typed request/response fields define operation inputs, outputs, and mutation outcomes; host validates ownership and authorization at commit.", + "Typed request/response fields define operation inputs, outputs, pagination or mutation outcomes; host validates ownership and authorization at commit." + ], + "contract": { + "operation_owner": "authenticated plugin session; host owns cross-plugin attribution and global facts", + "resource_owner": "caller-owned records by default; foreign shared records require the named grant and explicit scope", + "pagination": { + "supported": false, + "max_page_size": 200, + "cursor": "opaque, caller/session scoped" + }, + "revision": { + "read": "response carries the observed revision where applicable", + "mutation": "expected_revision required for existing mutable resources; conflict returns MUTATION_OUTCOME_REVISION_CONFLICT" + }, + "idempotency": { + "required": true, + "key_scope": "authenticated plugin plus operation", + "retry": "same key returns the original committed outcome" + }, + "quota": "enforced per method and owner; byte-bearing methods additionally enforce max_bytes and package/session limits", + "commit_authorization": "recheck permission, resource scope and grant revision immediately before side effects" + } + }, + { + "method": "GamesRegisterContent", + "request": "ContentRegistrationRequest", + "response": "MutationReply", + "streaming": false, + "owner": "authenticated caller/plugin; host owns global facts and attribution", + "permission": "library.discovery", + "semantics": [ + "host-issued operation_id; idempotency_key; expected_revision where applicable; recheck authorization at commit", + "content_id is host-issued and stable across content relocation; content_handle is a session-bound approved reference that is revalidated on update", + "Typed request/response fields define operation inputs, outputs, and mutation outcomes; host validates ownership and authorization at commit.", + "Typed request/response fields define operation inputs, outputs, pagination or mutation outcomes; host validates ownership and authorization at commit." + ], + "contract": { + "operation_owner": "authenticated plugin session; host owns cross-plugin attribution and global facts", + "resource_owner": "caller-owned records by default; foreign shared records require the named grant and explicit scope", + "pagination": { + "supported": false, + "max_page_size": 200, + "cursor": "opaque, caller/session scoped" + }, + "revision": { + "read": "response carries the observed revision where applicable", + "mutation": "expected_revision required for existing mutable resources; conflict returns MUTATION_OUTCOME_REVISION_CONFLICT" + }, + "idempotency": { + "required": true, + "key_scope": "authenticated plugin plus operation", + "retry": "same key returns the original committed outcome" + }, + "quota": "enforced per method and owner; byte-bearing methods additionally enforce max_bytes and package/session limits", + "commit_authorization": "recheck permission, resource scope and grant revision immediately before side effects" + } + }, + { + "method": "StorageDiagnosticsPublishBenchmark", + "request": "BenchmarkReportRequest", + "response": "ReportMutationReply", + "streaming": false, + "owner": "authenticated caller/plugin; host owns global facts and attribution", + "permission": "storage.diagnostics.publish", + "semantics": [ + "host-issued operation_id; idempotency_key; expected_revision where applicable; recheck authorization at commit", + "Typed request/response fields define operation inputs, outputs, and mutation outcomes; host validates ownership and authorization at commit.", + "Typed request/response fields define operation inputs, outputs, pagination or mutation outcomes; host validates ownership and authorization at commit." + ], + "contract": { + "operation_owner": "authenticated plugin session; host owns cross-plugin attribution and global facts", + "resource_owner": "caller-owned records by default; foreign shared records require the named grant and explicit scope", + "pagination": { + "supported": false, + "max_page_size": 200, + "cursor": "opaque, caller/session scoped" + }, + "revision": { + "read": "response carries the observed revision where applicable", + "mutation": "expected_revision required for existing mutable resources; conflict returns MUTATION_OUTCOME_REVISION_CONFLICT" + }, + "idempotency": { + "required": true, + "key_scope": "authenticated plugin plus operation", + "retry": "same key returns the original committed outcome" + }, + "quota": "enforced per method and owner; byte-bearing methods additionally enforce max_bytes and package/session limits", + "commit_authorization": "recheck permission, resource scope and grant revision immediately before side effects" + } + }, + { + "method": "StorageDiagnosticsPublishSmart", + "request": "SmartReportRequest", + "response": "ReportMutationReply", + "streaming": false, + "owner": "authenticated caller/plugin; host owns global facts and attribution", + "permission": "storage.diagnostics.publish", + "semantics": [ + "host-issued operation_id; idempotency_key; expected_revision where applicable; recheck authorization at commit", + "Typed request/response fields define operation inputs, outputs, and mutation outcomes; host validates ownership and authorization at commit.", + "Typed request/response fields define operation inputs, outputs, pagination or mutation outcomes; host validates ownership and authorization at commit." + ], + "contract": { + "operation_owner": "authenticated plugin session; host owns cross-plugin attribution and global facts", + "resource_owner": "caller-owned records by default; foreign shared records require the named grant and explicit scope", + "pagination": { + "supported": false, + "max_page_size": 200, + "cursor": "opaque, caller/session scoped" + }, + "revision": { + "read": "response carries the observed revision where applicable", + "mutation": "expected_revision required for existing mutable resources; conflict returns MUTATION_OUTCOME_REVISION_CONFLICT" + }, + "idempotency": { + "required": true, + "key_scope": "authenticated plugin plus operation", + "retry": "same key returns the original committed outcome" + }, + "quota": "enforced per method and owner; byte-bearing methods additionally enforce max_bytes and package/session limits", + "commit_authorization": "recheck permission, resource scope and grant revision immediately before side effects" + } + }, + { + "method": "ComputerPublishHardware", + "request": "HardwareReportRequest", + "response": "ReportMutationReply", + "streaming": false, + "owner": "authenticated caller/plugin; host owns global facts and attribution", + "permission": "computer.hardware.publish", + "semantics": [ + "host-issued operation_id; idempotency_key; expected_revision where applicable; recheck authorization at commit", + "Typed request/response fields define operation inputs, outputs, and mutation outcomes; host validates ownership and authorization at commit.", + "Typed request/response fields define operation inputs, outputs, pagination or mutation outcomes; host validates ownership and authorization at commit." + ], + "contract": { + "operation_owner": "authenticated plugin session; host owns cross-plugin attribution and global facts", + "resource_owner": "caller-owned records by default; foreign shared records require the named grant and explicit scope", + "pagination": { + "supported": false, + "max_page_size": 200, + "cursor": "opaque, caller/session scoped" + }, + "revision": { + "read": "response carries the observed revision where applicable", + "mutation": "expected_revision required for existing mutable resources; conflict returns MUTATION_OUTCOME_REVISION_CONFLICT" + }, + "idempotency": { + "required": true, + "key_scope": "authenticated plugin plus operation", + "retry": "same key returns the original committed outcome" + }, + "quota": "enforced per method and owner; byte-bearing methods additionally enforce max_bytes and package/session limits", + "commit_authorization": "recheck permission, resource scope and grant revision immediately before side effects" + } + }, + { + "method": "GamePresencePublish", + "request": "PresencePublishRequest", + "response": "ReportMutationReply", + "streaming": false, + "owner": "authenticated caller/plugin; host owns global facts and attribution", + "permission": "game.presence.publish", + "semantics": [ + "host-issued operation_id; idempotency_key; expected_revision where applicable; recheck authorization at commit", + "Typed request/response fields define operation inputs, outputs, and mutation outcomes; host validates ownership and authorization at commit.", + "Typed request/response fields define operation inputs, outputs, pagination or mutation outcomes; host validates ownership and authorization at commit." + ], + "contract": { + "operation_owner": "authenticated plugin session; host owns cross-plugin attribution and global facts", + "resource_owner": "caller-owned records by default; foreign shared records require the named grant and explicit scope", + "pagination": { + "supported": false, + "max_page_size": 200, + "cursor": "opaque, caller/session scoped" + }, + "revision": { + "read": "response carries the observed revision where applicable", + "mutation": "expected_revision required for existing mutable resources; conflict returns MUTATION_OUTCOME_REVISION_CONFLICT" + }, + "idempotency": { + "required": true, + "key_scope": "authenticated plugin plus operation", + "retry": "same key returns the original committed outcome" + }, + "quota": "enforced per method and owner; byte-bearing methods additionally enforce max_bytes and package/session limits", + "commit_authorization": "recheck permission, resource scope and grant revision immediately before side effects" + } + }, + { + "method": "GamePresenceClear", + "request": "PresenceClearRequest", + "response": "MutationReply", + "streaming": false, + "owner": "authenticated caller/plugin; host owns global facts and attribution", + "permission": "game.presence.publish", + "semantics": [ + "host-issued operation_id; idempotency_key; expected_revision where applicable; recheck authorization at commit", + "Typed request/response fields define operation inputs, outputs, and mutation outcomes; host validates ownership and authorization at commit.", + "Typed request/response fields define operation inputs, outputs, pagination or mutation outcomes; host validates ownership and authorization at commit." + ], + "contract": { + "operation_owner": "authenticated plugin session; host owns cross-plugin attribution and global facts", + "resource_owner": "caller-owned records by default; foreign shared records require the named grant and explicit scope", + "pagination": { + "supported": false, + "max_page_size": 200, + "cursor": "opaque, caller/session scoped" + }, + "revision": { + "read": "response carries the observed revision where applicable", + "mutation": "expected_revision required for existing mutable resources; conflict returns MUTATION_OUTCOME_REVISION_CONFLICT" + }, + "idempotency": { + "required": true, + "key_scope": "authenticated plugin plus operation", + "retry": "same key returns the original committed outcome" + }, + "quota": "enforced per method and owner; byte-bearing methods additionally enforce max_bytes and package/session limits", + "commit_authorization": "recheck permission, resource scope and grant revision immediately before side effects" + } + }, + { + "method": "GamePerformancePublishSamples", + "request": "PerformanceSamplesRequest", + "response": "ReportMutationReply", + "streaming": false, + "owner": "authenticated caller/plugin; host owns global facts and attribution", + "permission": "game.performance.publish", + "semantics": [ + "host-issued operation_id; idempotency_key; expected_revision where applicable; recheck authorization at commit", + "Typed request/response fields define operation inputs, outputs, and mutation outcomes; host validates ownership and authorization at commit.", + "Typed request/response fields define operation inputs, outputs, pagination or mutation outcomes; host validates ownership and authorization at commit." + ], + "contract": { + "operation_owner": "authenticated plugin session; host owns cross-plugin attribution and global facts", + "resource_owner": "caller-owned records by default; foreign shared records require the named grant and explicit scope", + "pagination": { + "supported": false, + "max_page_size": 200, + "cursor": "opaque, caller/session scoped" + }, + "revision": { + "read": "response carries the observed revision where applicable", + "mutation": "expected_revision required for existing mutable resources; conflict returns MUTATION_OUTCOME_REVISION_CONFLICT" + }, + "idempotency": { + "required": true, + "key_scope": "authenticated plugin plus operation", + "retry": "same key returns the original committed outcome" + }, + "quota": "enforced per method and owner; byte-bearing methods additionally enforce max_bytes and package/session limits", + "commit_authorization": "recheck permission, resource scope and grant revision immediately before side effects" + } + }, + { + "method": "GamePerformanceEndSeries", + "request": "PerformanceEndSeriesRequest", + "response": "MutationReply", + "streaming": false, + "owner": "authenticated caller/plugin; host owns global facts and attribution", + "permission": "game.performance.publish", + "semantics": [ + "host-issued operation_id; idempotency_key; expected_revision where applicable; recheck authorization at commit", + "Typed request/response fields define operation inputs, outputs, and mutation outcomes; host validates ownership and authorization at commit.", + "Typed request/response fields define operation inputs, outputs, pagination or mutation outcomes; host validates ownership and authorization at commit." + ], + "contract": { + "operation_owner": "authenticated plugin session; host owns cross-plugin attribution and global facts", + "resource_owner": "caller-owned records by default; foreign shared records require the named grant and explicit scope", + "pagination": { + "supported": false, + "max_page_size": 200, + "cursor": "opaque, caller/session scoped" + }, + "revision": { + "read": "response carries the observed revision where applicable", + "mutation": "expected_revision required for existing mutable resources; conflict returns MUTATION_OUTCOME_REVISION_CONFLICT" + }, + "idempotency": { + "required": true, + "key_scope": "authenticated plugin plus operation", + "retry": "same key returns the original committed outcome" + }, + "quota": "enforced per method and owner; byte-bearing methods additionally enforce max_bytes and package/session limits", + "commit_authorization": "recheck permission, resource scope and grant revision immediately before side effects" + } + }, + { + "method": "DataPublish", + "request": "DataPublishRequest", + "response": "DataMutationReply", + "streaming": false, + "owner": "authenticated caller/plugin; host owns global facts and attribution", + "permission": "data.publish or domain-specific publish grant; storage.persist for durable mode", + "semantics": [ + "host-issued operation_id; idempotency_key; expected_revision where applicable; recheck authorization at commit", + "private/session-only by default; durable mode requires storage.persist; producer does not grant recipient read access", + "Typed request/response fields define operation inputs, outputs, and mutation outcomes; host validates ownership and authorization at commit.", + "Typed request/response fields define operation inputs, outputs, pagination or mutation outcomes; host validates ownership and authorization at commit." + ], + "contract": { + "operation_owner": "authenticated plugin session; host owns cross-plugin attribution and global facts", + "resource_owner": "caller-owned records by default; foreign shared records require the named grant and explicit scope", + "pagination": { + "supported": false, + "max_page_size": 200, + "cursor": "opaque, caller/session scoped" + }, + "revision": { + "read": "response carries the observed revision where applicable", + "mutation": "expected_revision required for existing mutable resources; conflict returns MUTATION_OUTCOME_REVISION_CONFLICT" + }, + "idempotency": { + "required": true, + "key_scope": "authenticated plugin plus operation", + "retry": "same key returns the original committed outcome" + }, + "quota": "enforced per method and owner; byte-bearing methods additionally enforce max_bytes and package/session limits", + "commit_authorization": "recheck permission, resource scope and grant revision immediately before side effects" + } + }, + { + "method": "DataGet", + "request": "DataGetRequest", + "response": "DataGetReply", + "streaming": false, + "owner": "authenticated caller/plugin; host owns global facts and attribution", + "permission": "declared dataset/category read grant; common inclusion is per-query opt-in", + "semantics": [ + "common records excluded unless explicitly requested; category selector grant checked", + "Typed request/response fields define operation inputs, outputs, and mutation outcomes; host validates ownership and authorization at commit.", + "Typed request/response fields define operation inputs, outputs, pagination or mutation outcomes; host validates ownership and authorization at commit." + ], + "contract": { + "operation_owner": "authenticated plugin session; host owns cross-plugin attribution and global facts", + "resource_owner": "caller-owned records by default; foreign shared records require the named grant and explicit scope", + "pagination": { + "supported": false, + "max_page_size": 200, + "cursor": "opaque, caller/session scoped" + }, + "revision": { + "read": "response carries the observed revision where applicable", + "mutation": "expected_revision required for existing mutable resources; conflict returns MUTATION_OUTCOME_REVISION_CONFLICT" + }, + "idempotency": { + "required": false, + "key_scope": "authenticated plugin plus operation", + "retry": "same key returns the original committed outcome" + }, + "quota": "enforced per method and owner; byte-bearing methods additionally enforce max_bytes and package/session limits", + "commit_authorization": "recheck permission, resource scope and grant revision immediately before side effects" + } + }, + { + "method": "DataList", + "request": "DataListRequest", + "response": "DataListReply", + "streaming": false, + "owner": "authenticated caller/plugin; host owns global facts and attribution", + "permission": "declared dataset/category read grant; common inclusion is per-query opt-in", + "semantics": [ + "cursor/page_size fields are available; host enforces method-specific bounds and opaque cursors", + "common records excluded unless explicitly requested; category selector grant checked", + "Typed request/response fields define operation inputs, outputs, and mutation outcomes; host validates ownership and authorization at commit.", + "Typed request/response fields define operation inputs, outputs, pagination or mutation outcomes; host validates ownership and authorization at commit." + ], + "contract": { + "operation_owner": "authenticated plugin session; host owns cross-plugin attribution and global facts", + "resource_owner": "caller-owned records by default; foreign shared records require the named grant and explicit scope", + "pagination": { + "supported": true, + "max_page_size": 200, + "cursor": "opaque, caller/session scoped" + }, + "revision": { + "read": "response carries the observed revision where applicable", + "mutation": "expected_revision required for existing mutable resources; conflict returns MUTATION_OUTCOME_REVISION_CONFLICT" + }, + "idempotency": { + "required": false, + "key_scope": "authenticated plugin plus operation", + "retry": "same key returns the original committed outcome" + }, + "quota": "enforced per method and owner; byte-bearing methods additionally enforce max_bytes and package/session limits", + "commit_authorization": "recheck permission, resource scope and grant revision immediately before side effects" + } + }, + { + "method": "DataWatch", + "request": "DataWatchRequest", + "response": "DataEvent", + "streaming": true, + "owner": "authenticated caller/plugin; host owns global facts and attribution", + "permission": "declared dataset/category read grant; common inclusion is per-query opt-in", + "semantics": [ + "common records excluded unless explicitly requested; category selector grant checked", + "Typed request/response fields define operation inputs, outputs, and mutation outcomes; host validates ownership and authorization at commit.", + "Typed request/response fields define operation inputs, outputs, pagination or mutation outcomes; host validates ownership and authorization at commit." + ], + "contract": { + "operation_owner": "authenticated plugin session; host owns cross-plugin attribution and global facts", + "resource_owner": "caller-owned records by default; foreign shared records require the named grant and explicit scope", + "pagination": { + "supported": false, + "max_page_size": 200, + "cursor": "opaque, caller/session scoped" + }, + "revision": { + "read": "response carries the observed revision where applicable", + "mutation": "expected_revision required for existing mutable resources; conflict returns MUTATION_OUTCOME_REVISION_CONFLICT" + }, + "idempotency": { + "required": false, + "key_scope": "authenticated plugin plus operation", + "retry": "same key returns the original committed outcome" + }, + "quota": "enforced per method and owner; byte-bearing methods additionally enforce max_bytes and package/session limits", + "commit_authorization": "recheck permission, resource scope and grant revision immediately before side effects" + } + }, + { + "method": "PersistenceGetUsage", + "request": "PersistenceUsageRequest", + "response": "PersistenceUsageReply", + "streaming": false, + "owner": "authenticated caller/plugin; host owns global facts and attribution", + "permission": "storage.persist (own namespace)", + "semantics": [ + "Typed request/response fields define operation inputs, outputs, and mutation outcomes; host validates ownership and authorization at commit.", + "Typed request/response fields define operation inputs, outputs, pagination or mutation outcomes; host validates ownership and authorization at commit." + ], + "contract": { + "operation_owner": "authenticated plugin session; host owns cross-plugin attribution and global facts", + "resource_owner": "caller-owned records by default; foreign shared records require the named grant and explicit scope", + "pagination": { + "supported": false, + "max_page_size": 200, + "cursor": "opaque, caller/session scoped" + }, + "revision": { + "read": "response carries the observed revision where applicable", + "mutation": "expected_revision required for existing mutable resources; conflict returns MUTATION_OUTCOME_REVISION_CONFLICT" + }, + "idempotency": { + "required": false, + "key_scope": "authenticated plugin plus operation", + "retry": "same key returns the original committed outcome" + }, + "quota": "enforced per method and owner; byte-bearing methods additionally enforce max_bytes and package/session limits", + "commit_authorization": "recheck permission, resource scope and grant revision immediately before side effects" + } + }, + { + "method": "PersistenceListEntries", + "request": "PersistenceListRequest", + "response": "PersistenceListReply", + "streaming": false, + "owner": "authenticated caller/plugin; host owns global facts and attribution", + "permission": "storage.persist (own namespace)", + "semantics": [ + "cursor/page_size fields are available; host enforces method-specific bounds and opaque cursors", + "Typed request/response fields define operation inputs, outputs, and mutation outcomes; host validates ownership and authorization at commit.", + "Typed request/response fields define operation inputs, outputs, pagination or mutation outcomes; host validates ownership and authorization at commit." + ], + "contract": { + "operation_owner": "authenticated plugin session; host owns cross-plugin attribution and global facts", + "resource_owner": "caller-owned records by default; foreign shared records require the named grant and explicit scope", + "pagination": { + "supported": true, + "max_page_size": 200, + "cursor": "opaque, caller/session scoped" + }, + "revision": { + "read": "response carries the observed revision where applicable", + "mutation": "expected_revision required for existing mutable resources; conflict returns MUTATION_OUTCOME_REVISION_CONFLICT" + }, + "idempotency": { + "required": false, + "key_scope": "authenticated plugin plus operation", + "retry": "same key returns the original committed outcome" + }, + "quota": "enforced per method and owner; byte-bearing methods additionally enforce max_bytes and package/session limits", + "commit_authorization": "recheck permission, resource scope and grant revision immediately before side effects" + } + }, + { + "method": "PersistenceDeleteEntries", + "request": "PersistenceDeleteRequest", + "response": "MutationReply", + "streaming": false, + "owner": "authenticated caller/plugin; host owns global facts and attribution", + "permission": "storage.persist (own namespace)", + "semantics": [ + "host-issued operation_id; idempotency_key; expected_revision where applicable; recheck authorization at commit", + "Typed request/response fields define operation inputs, outputs, and mutation outcomes; host validates ownership and authorization at commit.", + "Typed request/response fields define operation inputs, outputs, pagination or mutation outcomes; host validates ownership and authorization at commit." + ], + "contract": { + "operation_owner": "authenticated plugin session; host owns cross-plugin attribution and global facts", + "resource_owner": "caller-owned records by default; foreign shared records require the named grant and explicit scope", + "pagination": { + "supported": false, + "max_page_size": 200, + "cursor": "opaque, caller/session scoped" + }, + "revision": { + "read": "response carries the observed revision where applicable", + "mutation": "expected_revision required for existing mutable resources; conflict returns MUTATION_OUTCOME_REVISION_CONFLICT" + }, + "idempotency": { + "required": true, + "key_scope": "authenticated plugin plus operation", + "retry": "same key returns the original committed outcome" + }, + "quota": "enforced per method and owner; byte-bearing methods additionally enforce max_bytes and package/session limits", + "commit_authorization": "recheck permission, resource scope and grant revision immediately before side effects" + } + }, + { + "method": "PersistenceClear", + "request": "PersistenceClearRequest", + "response": "MutationReply", + "streaming": false, + "owner": "authenticated caller/plugin; host owns global facts and attribution", + "permission": "storage.persist (own namespace)", + "semantics": [ + "host-issued operation_id; idempotency_key; expected_revision where applicable; recheck authorization at commit", + "Typed request/response fields define operation inputs, outputs, and mutation outcomes; host validates ownership and authorization at commit.", + "Typed request/response fields define operation inputs, outputs, pagination or mutation outcomes; host validates ownership and authorization at commit." + ], + "contract": { + "operation_owner": "authenticated plugin session; host owns cross-plugin attribution and global facts", + "resource_owner": "caller-owned records by default; foreign shared records require the named grant and explicit scope", + "pagination": { + "supported": false, + "max_page_size": 200, + "cursor": "opaque, caller/session scoped" + }, + "revision": { + "read": "response carries the observed revision where applicable", + "mutation": "expected_revision required for existing mutable resources; conflict returns MUTATION_OUTCOME_REVISION_CONFLICT" + }, + "idempotency": { + "required": true, + "key_scope": "authenticated plugin plus operation", + "retry": "same key returns the original committed outcome" + }, + "quota": "enforced per method and owner; byte-bearing methods additionally enforce max_bytes and package/session limits", + "commit_authorization": "recheck permission, resource scope and grant revision immediately before side effects" + } + }, + { + "method": "PersistenceSetRetentionPolicy", + "request": "RetentionPolicyRequest", + "response": "MutationReply", + "streaming": false, + "owner": "authenticated caller/plugin; host owns global facts and attribution", + "permission": "storage.persist (own namespace)", + "semantics": [ + "host-issued operation_id; idempotency_key; expected_revision where applicable; recheck authorization at commit", + "Typed request/response fields define operation inputs, outputs, and mutation outcomes; host validates ownership and authorization at commit.", + "Typed request/response fields define operation inputs, outputs, pagination or mutation outcomes; host validates ownership and authorization at commit." + ], + "contract": { + "operation_owner": "authenticated plugin session; host owns cross-plugin attribution and global facts", + "resource_owner": "caller-owned records by default; foreign shared records require the named grant and explicit scope", + "pagination": { + "supported": false, + "max_page_size": 200, + "cursor": "opaque, caller/session scoped" + }, + "revision": { + "read": "response carries the observed revision where applicable", + "mutation": "expected_revision required for existing mutable resources; conflict returns MUTATION_OUTCOME_REVISION_CONFLICT" + }, + "idempotency": { + "required": true, + "key_scope": "authenticated plugin plus operation", + "retry": "same key returns the original committed outcome" + }, + "quota": "enforced per method and owner; byte-bearing methods additionally enforce max_bytes and package/session limits", + "commit_authorization": "recheck permission, resource scope and grant revision immediately before side effects" + } + }, + { + "method": "ToolsList", + "request": "ToolsListRequest", + "response": "ToolsListReply", + "streaming": false, + "owner": "authenticated caller/plugin; host owns global facts and attribution", + "permission": "tools.read", + "semantics": [ + "cursor/page_size fields are available; host enforces method-specific bounds and opaque cursors", + "Typed request/response fields define operation inputs, outputs, and mutation outcomes; host validates ownership and authorization at commit.", + "Typed request/response fields define operation inputs, outputs, pagination or mutation outcomes; host validates ownership and authorization at commit." + ], + "contract": { + "operation_owner": "authenticated plugin session; host owns cross-plugin attribution and global facts", + "resource_owner": "caller-owned records by default; foreign shared records require the named grant and explicit scope", + "pagination": { + "supported": true, + "max_page_size": 200, + "cursor": "opaque, caller/session scoped" + }, + "revision": { + "read": "response carries the observed revision where applicable", + "mutation": "expected_revision required for existing mutable resources; conflict returns MUTATION_OUTCOME_REVISION_CONFLICT" + }, + "idempotency": { + "required": false, + "key_scope": "authenticated plugin plus operation", + "retry": "same key returns the original committed outcome" + }, + "quota": "enforced per method and owner; byte-bearing methods additionally enforce max_bytes and package/session limits", + "commit_authorization": "recheck permission, resource scope and grant revision immediately before side effects" + } + }, + { + "method": "ToolsRequestApply", + "request": "ToolApplyRequest", + "response": "JobReply", + "streaming": false, + "owner": "authenticated caller/plugin; host owns global facts and attribution", + "permission": "tools.apply", + "semantics": [ + "host-issued operation_id; idempotency_key; expected_revision where applicable; recheck authorization at commit", + "Typed request/response fields define operation inputs, outputs, and mutation outcomes; host validates ownership and authorization at commit.", + "Typed request/response fields define operation inputs, outputs, pagination or mutation outcomes; host validates ownership and authorization at commit." + ], + "contract": { + "operation_owner": "authenticated plugin session; host owns cross-plugin attribution and global facts", + "resource_owner": "caller-owned records by default; foreign shared records require the named grant and explicit scope", + "pagination": { + "supported": false, + "max_page_size": 200, + "cursor": "opaque, caller/session scoped" + }, + "revision": { + "read": "response carries the observed revision where applicable", + "mutation": "expected_revision required for existing mutable resources; conflict returns MUTATION_OUTCOME_REVISION_CONFLICT" + }, + "idempotency": { + "required": true, + "key_scope": "authenticated plugin plus operation", + "retry": "same key returns the original committed outcome" + }, + "quota": "enforced per method and owner; byte-bearing methods additionally enforce max_bytes and package/session limits", + "commit_authorization": "recheck permission, resource scope and grant revision immediately before side effects" + } + }, + { + "method": "ToolsRequestRemove", + "request": "ToolRemoveRequest", + "response": "JobReply", + "streaming": false, + "owner": "authenticated caller/plugin; host owns global facts and attribution", + "permission": "tools.remove", + "semantics": [ + "host-issued operation_id; idempotency_key; expected_revision where applicable; recheck authorization at commit", + "Typed request/response fields define operation inputs, outputs, and mutation outcomes; host validates ownership and authorization at commit.", + "Typed request/response fields define operation inputs, outputs, pagination or mutation outcomes; host validates ownership and authorization at commit." + ], + "contract": { + "operation_owner": "authenticated plugin session; host owns cross-plugin attribution and global facts", + "resource_owner": "caller-owned records by default; foreign shared records require the named grant and explicit scope", + "pagination": { + "supported": false, + "max_page_size": 200, + "cursor": "opaque, caller/session scoped" + }, + "revision": { + "read": "response carries the observed revision where applicable", + "mutation": "expected_revision required for existing mutable resources; conflict returns MUTATION_OUTCOME_REVISION_CONFLICT" + }, + "idempotency": { + "required": true, + "key_scope": "authenticated plugin plus operation", + "retry": "same key returns the original committed outcome" + }, + "quota": "enforced per method and owner; byte-bearing methods additionally enforce max_bytes and package/session limits", + "commit_authorization": "recheck permission, resource scope and grant revision immediately before side effects" + } + }, + { + "method": "PortsList", + "request": "PortsListRequest", + "response": "PortsListReply", + "streaming": false, + "owner": "authenticated caller/plugin; host owns global facts and attribution", + "permission": "ports.read", + "semantics": [ + "cursor/page_size fields are available; host enforces method-specific bounds and opaque cursors", + "Typed request/response fields define operation inputs, outputs, and mutation outcomes; host validates ownership and authorization at commit.", + "Typed request/response fields define operation inputs, outputs, pagination or mutation outcomes; host validates ownership and authorization at commit." + ], + "contract": { + "operation_owner": "authenticated plugin session; host owns cross-plugin attribution and global facts", + "resource_owner": "caller-owned records by default; foreign shared records require the named grant and explicit scope", + "pagination": { + "supported": true, + "max_page_size": 200, + "cursor": "opaque, caller/session scoped" + }, + "revision": { + "read": "response carries the observed revision where applicable", + "mutation": "expected_revision required for existing mutable resources; conflict returns MUTATION_OUTCOME_REVISION_CONFLICT" + }, + "idempotency": { + "required": false, + "key_scope": "authenticated plugin plus operation", + "retry": "same key returns the original committed outcome" + }, + "quota": "enforced per method and owner; byte-bearing methods additionally enforce max_bytes and package/session limits", + "commit_authorization": "recheck permission, resource scope and grant revision immediately before side effects" + } + }, + { + "method": "PortsDetail", + "request": "PortDetailRequest", + "response": "PortDetailReply", + "streaming": false, + "owner": "authenticated caller/plugin; host owns global facts and attribution", + "permission": "ports.read", + "semantics": [ + "Typed request/response fields define operation inputs, outputs, and mutation outcomes; host validates ownership and authorization at commit.", + "Typed request/response fields define operation inputs, outputs, pagination or mutation outcomes; host validates ownership and authorization at commit." + ], + "contract": { + "operation_owner": "authenticated plugin session; host owns cross-plugin attribution and global facts", + "resource_owner": "caller-owned records by default; foreign shared records require the named grant and explicit scope", + "pagination": { + "supported": false, + "max_page_size": 200, + "cursor": "opaque, caller/session scoped" + }, + "revision": { + "read": "response carries the observed revision where applicable", + "mutation": "expected_revision required for existing mutable resources; conflict returns MUTATION_OUTCOME_REVISION_CONFLICT" + }, + "idempotency": { + "required": false, + "key_scope": "authenticated plugin plus operation", + "retry": "same key returns the original committed outcome" + }, + "quota": "enforced per method and owner; byte-bearing methods additionally enforce max_bytes and package/session limits", + "commit_authorization": "recheck permission, resource scope and grant revision immediately before side effects" + } + }, + { + "method": "PortsRequestInstall", + "request": "PortInstallRequest", + "response": "JobReply", + "streaming": false, + "owner": "authenticated caller/plugin; host owns global facts and attribution", + "permission": "ports.install", + "semantics": [ + "host-issued operation_id; idempotency_key; expected_revision where applicable; recheck authorization at commit", + "Typed request/response fields define operation inputs, outputs, and mutation outcomes; host validates ownership and authorization at commit.", + "Typed request/response fields define operation inputs, outputs, pagination or mutation outcomes; host validates ownership and authorization at commit." + ], + "contract": { + "operation_owner": "authenticated plugin session; host owns cross-plugin attribution and global facts", + "resource_owner": "caller-owned records by default; foreign shared records require the named grant and explicit scope", + "pagination": { + "supported": false, + "max_page_size": 200, + "cursor": "opaque, caller/session scoped" + }, + "revision": { + "read": "response carries the observed revision where applicable", + "mutation": "expected_revision required for existing mutable resources; conflict returns MUTATION_OUTCOME_REVISION_CONFLICT" + }, + "idempotency": { + "required": true, + "key_scope": "authenticated plugin plus operation", + "retry": "same key returns the original committed outcome" + }, + "quota": "enforced per method and owner; byte-bearing methods additionally enforce max_bytes and package/session limits", + "commit_authorization": "recheck permission, resource scope and grant revision immediately before side effects" + } + }, + { + "method": "JobsGet", + "request": "JobGetRequest", + "response": "JobReply", + "streaming": false, + "owner": "authenticated caller/plugin; host owns global facts and attribution", + "permission": "underlying operation grant (caller-owned job)", + "semantics": [ + "caller-owned job; terminal outcome and cancellation semantics are host-defined", + "Typed request/response fields define operation inputs, outputs, and mutation outcomes; host validates ownership and authorization at commit.", + "Typed request/response fields define operation inputs, outputs, pagination or mutation outcomes; host validates ownership and authorization at commit." + ], + "contract": { + "operation_owner": "authenticated plugin session; host owns cross-plugin attribution and global facts", + "resource_owner": "caller-owned records by default; foreign shared records require the named grant and explicit scope", + "pagination": { + "supported": false, + "max_page_size": 200, + "cursor": "opaque, caller/session scoped" + }, + "revision": { + "read": "response carries the observed revision where applicable", + "mutation": "expected_revision required for existing mutable resources; conflict returns MUTATION_OUTCOME_REVISION_CONFLICT" + }, + "idempotency": { + "required": false, + "key_scope": "authenticated plugin plus operation", + "retry": "same key returns the original committed outcome" + }, + "quota": "enforced per method and owner; byte-bearing methods additionally enforce max_bytes and package/session limits", + "commit_authorization": "recheck permission, resource scope and grant revision immediately before side effects" + } + }, + { + "method": "JobsWatch", + "request": "JobWatchRequest", + "response": "JobEvent", + "streaming": true, + "owner": "authenticated caller/plugin; host owns global facts and attribution", + "permission": "underlying operation grant (caller-owned job)", + "semantics": [ + "caller-owned job; terminal outcome and cancellation semantics are host-defined", + "Typed request/response fields define operation inputs, outputs, and mutation outcomes; host validates ownership and authorization at commit.", + "Typed request/response fields define operation inputs, outputs, pagination or mutation outcomes; host validates ownership and authorization at commit." + ], + "contract": { + "operation_owner": "authenticated plugin session; host owns cross-plugin attribution and global facts", + "resource_owner": "caller-owned records by default; foreign shared records require the named grant and explicit scope", + "pagination": { + "supported": false, + "max_page_size": 200, + "cursor": "opaque, caller/session scoped" + }, + "revision": { + "read": "response carries the observed revision where applicable", + "mutation": "expected_revision required for existing mutable resources; conflict returns MUTATION_OUTCOME_REVISION_CONFLICT" + }, + "idempotency": { + "required": false, + "key_scope": "authenticated plugin plus operation", + "retry": "same key returns the original committed outcome" + }, + "quota": "enforced per method and owner; byte-bearing methods additionally enforce max_bytes and package/session limits", + "commit_authorization": "recheck permission, resource scope and grant revision immediately before side effects" + } + }, + { + "method": "JobsCancel", + "request": "JobCancelRequest", + "response": "JobReply", + "streaming": false, + "owner": "authenticated caller/plugin; host owns global facts and attribution", + "permission": "underlying operation grant (caller-owned job)", + "semantics": [ + "host-issued operation_id; idempotency_key; expected_revision where applicable; recheck authorization at commit", + "caller-owned job; terminal outcome and cancellation semantics are host-defined", + "Typed request/response fields define operation inputs, outputs, and mutation outcomes; host validates ownership and authorization at commit.", + "Typed request/response fields define operation inputs, outputs, pagination or mutation outcomes; host validates ownership and authorization at commit." + ], + "contract": { + "operation_owner": "authenticated plugin session; host owns cross-plugin attribution and global facts", + "resource_owner": "caller-owned records by default; foreign shared records require the named grant and explicit scope", + "pagination": { + "supported": false, + "max_page_size": 200, + "cursor": "opaque, caller/session scoped" + }, + "revision": { + "read": "response carries the observed revision where applicable", + "mutation": "expected_revision required for existing mutable resources; conflict returns MUTATION_OUTCOME_REVISION_CONFLICT" + }, + "idempotency": { + "required": true, + "key_scope": "authenticated plugin plus operation", + "retry": "same key returns the original committed outcome" + }, + "quota": "enforced per method and owner; byte-bearing methods additionally enforce max_bytes and package/session limits", + "commit_authorization": "recheck permission, resource scope and grant revision immediately before side effects" + } + } + ] +} diff --git a/crates/plugin-protocol/proto/plugin.proto b/crates/plugin-protocol/proto/plugin.proto index c5d30d578..989350b20 100644 --- a/crates/plugin-protocol/proto/plugin.proto +++ b/crates/plugin-protocol/proto/plugin.proto @@ -1,9 +1,15 @@ syntax = "proto3"; package gamenode.plugin.v1; +import "google/protobuf/struct.proto"; + service PluginHost { rpc OpenSession (OpenSessionRequest) returns (OpenSessionReply); rpc SubmitDiscovery (SubmitDiscoveryRequest) returns (SubmitDiscoveryReply); + // Authenticated control-plane methods; they never require data permissions. + rpc DescribeApi (DescribeApiRequest) returns (DescribeApiReply); + rpc GetPermissions (GetPermissionsRequest) returns (GetPermissionsReply); + rpc WatchPermissionChanges (WatchPermissionChangesRequest) returns (stream PermissionChange); } message OpenSessionRequest { @@ -13,6 +19,14 @@ message OpenSessionRequest { uint32 api_minor = 4; bytes session_credential = 5; repeated string requested_capabilities = 6; + // API 1.6+: range and feature fields. Empty range preserves API 1.1–1.5 behavior. + uint32 min_api_major = 7; + uint32 min_api_minor = 8; + uint32 max_api_major = 9; + uint32 max_api_minor = 10; + repeated FeatureRequest features = 11; + SessionKind session_kind = 12; + optional TargetGameContext target_game = 13; } message OpenSessionReply { @@ -20,6 +34,143 @@ message OpenSessionReply { repeated string granted_capabilities = 2; uint32 api_major = 3; uint32 api_minor = 4; + repeated FeatureStatus features = 5; + SupportWindow support_window = 6; + // API 1.6+: the host-issued context for plugin-initiated resource calls + // (ResourceHost). It is bound to this session, its kind and target game and + // the active profile; it carries no authority beyond the session's grants. + // Absent for sessions that negotiated an earlier minor. + ServiceContext resource_context = 7; +} + +enum SessionKind { + SESSION_KIND_UNSPECIFIED = 0; + SESSION_KIND_PROVIDER = 1; + SESSION_KIND_EXTENSION = 2; +} + +message TargetGameContext { + string game_id = 1; + string installation_id = 2; + string profile_id = 3; + string revision = 4; +} + +message FeatureRequest { + string id = 1; + bool required = 2; +} + +enum FeatureAvailability { + FEATURE_AVAILABILITY_UNSPECIFIED = 0; + FEATURE_AVAILABILITY_SUPPORTED = 1; + FEATURE_AVAILABILITY_UNSUPPORTED = 2; + FEATURE_AVAILABILITY_DENIED = 3; +} + +message FeatureStatus { + string id = 1; + FeatureAvailability availability = 2; + uint32 introduced_minor = 3; +} + +message SupportWindow { + uint32 minimum_api_minor = 1; + uint32 maximum_api_minor = 2; + optional int64 support_ends_at = 3; + string policy = 4; +} + +message ApiFeature { + string id = 1; + uint32 introduced_minor = 2; + repeated string permissions = 3; + bool optional = 4; + string availability = 5; +} + +message ApiMethod { + string service = 1; + string method = 2; + uint32 introduced_minor = 3; + repeated string permissions = 4; + string ownership = 5; + uint32 max_page_size = 6; + uint64 quota_bytes = 7; + bool idempotent = 8; +} + +message DescribeApiRequest { + string session_id = 1; + bytes session_credential = 2; +} +message DescribeApiReply { + uint32 api_major = 1; + uint32 api_minor = 2; + SupportWindow support_window = 3; + repeated ApiFeature features = 4; + repeated ApiMethod methods = 5; +} + +message GetPermissionsRequest { + string session_id = 1; + bytes session_credential = 2; +} +message PermissionGrant { + string permission_id = 1; + string state = 2; + string scope = 3; + string reason = 4; + uint64 revision = 5; +} +message GetPermissionsReply { + uint64 revision = 1; + repeated PermissionGrant grants = 2; +} +message WatchPermissionChangesRequest { + string session_id = 1; + bytes session_credential = 2; + uint64 after_revision = 3; +} +message PermissionChange { + uint64 revision = 1; + repeated PermissionGrant grants = 2; + bool revoked = 3; +} + +enum DenialReason { + DENIAL_REASON_UNSPECIFIED = 0; + DENIAL_REASON_NOT_GRANTED = 1; + DENIAL_REASON_REVOKED = 2; + DENIAL_REASON_SCOPE_DENIED = 3; + DENIAL_REASON_REQUIRED_PERMISSION_MISSING = 4; +} +message DenialDetail { + DenialReason reason = 1; + string permission_id = 2; + uint64 grant_revision = 3; +} + +// A launch target a provider detected for one of its own games (API 1.6). It is additive to +// `DeclareActions`: the legacy URI-only declaration keeps its bytes and semantics, and a +// detected target is only registered, never started, by submitting it. An executable target is +// relative to the record's install folder and needs the user's approval before Play can run it. +message DetectedExecutable { + // Path relative to the record's install folder. Absolute paths, `..` and control characters + // are rejected by the host. + string path = 1; + // Literal arguments, in launch order. Never a shell string. + repeated string arguments = 2; + // Folder relative to the install folder; empty means the install folder itself. + string working_directory = 3; +} + +message DetectedTarget { + oneof target { + // A URI the provider's own client handles. + string uri = 1; + DetectedExecutable executable = 2; + } } message DiscoveryRecord { @@ -27,6 +178,8 @@ message DiscoveryRecord { string name = 2; string install_dir = 3; map fields = 4; + // Optional typed target. Registration alone never starts a process. + DetectedTarget target = 5; } message DiscoveryResult { @@ -70,6 +223,729 @@ service ProviderHost { rpc DeclareActions (ActionRequest) returns (ActionReply); } +// API 1.6 resource surface. Every request is scoped to a host-issued session +// and operation; implementations must recheck grants/revisions at commit. +service ResourceHost { + rpc LibraryList (LibraryListRequest) returns (LibraryListReply); + rpc LibraryGet (LibraryGetRequest) returns (LibraryGetReply); + rpc LibraryWatch (LibraryWatchRequest) returns (stream LibraryEvent); + rpc MetadataUpdate (MetadataUpdateRequest) returns (MutationReply); + rpc FavoritesList (FavoritesListRequest) returns (FavoritesListReply); + rpc FavoritesSet (FavoritesSetRequest) returns (MutationReply); + rpc MatchingSearch (MatchingSearchRequest) returns (MatchingSearchReply); + rpc MatchingAssign (MatchingAssignRequest) returns (MutationReply); + rpc ArtworkRead (ArtworkReadRequest) returns (ArtworkReadReply); + rpc ArtworkSet (ArtworkSetRequest) returns (MutationReply); + rpc GamesRequestLaunch (GameLaunchRequest) returns (GameLaunchReply); + rpc GamesProposeCustomLaunch (CustomLaunchRequest) returns (CustomLaunchReply); + rpc GamesRequestCustomLaunch (CustomLaunchRequest) returns (CustomLaunchReply); + rpc GamesRemoveCustomLaunch (CustomLaunchRemoveRequest) returns (MutationReply); + rpc GamesRequestInstall (GameInstallRequest) returns (JobReply); + rpc StorageGet (StorageGetRequest) returns (StorageGetReply); + rpc StoragePut (StoragePutRequest) returns (StorageMutationReply); + rpc StorageDelete (StorageDeleteRequest) returns (MutationReply); + rpc FilesRequestAccess (FilesRequestAccessRequest) returns (FileAccessReply); + rpc FilesList (FilesListRequest) returns (FilesListReply); + rpc FilesRead (FilesReadRequest) returns (FileReadReply); + rpc FilesWrite (FilesWriteRequest) returns (MutationReply); + rpc FilesDelete (FilesDeleteRequest) returns (MutationReply); + rpc NetworkFetch (NetworkFetchRequest) returns (NetworkFetchReply); + rpc NotificationsPublish (NotificationPublishRequest) returns (MutationReply); + rpc BackupsList (BackupsListRequest) returns (BackupsListReply); + rpc BackupsRequestCreate (BackupCreateRequest) returns (JobReply); + rpc BackupsRequestRestore (BackupRestoreRequest) returns (JobReply); + rpc LibrariesList (DomainListRequest) returns (LibrariesListReply); + rpc LibrariesGet (DomainGetRequest) returns (LibraryRecordReply); + rpc LibrariesWatch (DomainWatchRequest) returns (stream LibraryRecordEvent); + rpc LibrariesCreate (LibraryCreateRequest) returns (LibraryMutationReply); + rpc LibrariesUpdate (LibraryUpdateRequest) returns (LibraryMutationReply); + rpc LibrariesRemove (DomainRemoveRequest) returns (MutationReply); + rpc LibrariesAddRoot (LibraryRootAddRequest) returns (LibraryMutationReply); + rpc LibrariesUpdateRoot (LibraryRootUpdateRequest) returns (LibraryMutationReply); + rpc LibrariesRemoveRoot (LibraryRootRemoveRequest) returns (MutationReply); + rpc RuntimesList (DomainListRequest) returns (RuntimesListReply); + rpc RuntimesGet (DomainGetRequest) returns (RuntimeRecordReply); + rpc RuntimesWatch (DomainWatchRequest) returns (stream RuntimeRecordEvent); + rpc RuntimesRequestAccess (RuntimeRequestAccessRequest) returns (RuntimeMutationReply); + rpc RuntimesRegister (RuntimeRegisterRequest) returns (RuntimeMutationReply); + rpc RuntimesUpdate (RuntimeUpdateRequest) returns (RuntimeMutationReply); + rpc RuntimesRemove (DomainRemoveRequest) returns (MutationReply); + rpc GamesRegisterContent (ContentRegistrationRequest) returns (MutationReply); + rpc StorageDiagnosticsPublishBenchmark (BenchmarkReportRequest) returns (ReportMutationReply); + rpc StorageDiagnosticsPublishSmart (SmartReportRequest) returns (ReportMutationReply); + rpc ComputerPublishHardware (HardwareReportRequest) returns (ReportMutationReply); + rpc GamePresencePublish (PresencePublishRequest) returns (ReportMutationReply); + rpc GamePresenceClear (PresenceClearRequest) returns (MutationReply); + rpc GamePerformancePublishSamples (PerformanceSamplesRequest) returns (ReportMutationReply); + rpc GamePerformanceEndSeries (PerformanceEndSeriesRequest) returns (MutationReply); + rpc DataPublish (DataPublishRequest) returns (DataMutationReply); + rpc DataGet (DataGetRequest) returns (DataGetReply); + rpc DataList (DataListRequest) returns (DataListReply); + rpc DataWatch (DataWatchRequest) returns (stream DataEvent); + rpc PersistenceGetUsage (PersistenceUsageRequest) returns (PersistenceUsageReply); + rpc PersistenceListEntries (PersistenceListRequest) returns (PersistenceListReply); + rpc PersistenceDeleteEntries (PersistenceDeleteRequest) returns (MutationReply); + rpc PersistenceClear (PersistenceClearRequest) returns (MutationReply); + rpc PersistenceSetRetentionPolicy (RetentionPolicyRequest) returns (MutationReply); + rpc ToolsList (ToolsListRequest) returns (ToolsListReply); + rpc ToolsRequestApply (ToolApplyRequest) returns (JobReply); + rpc ToolsRequestRemove (ToolRemoveRequest) returns (JobReply); + rpc PortsList (PortsListRequest) returns (PortsListReply); + rpc PortsDetail (PortDetailRequest) returns (PortDetailReply); + rpc PortsRequestInstall (PortInstallRequest) returns (JobReply); + rpc JobsGet (JobGetRequest) returns (JobReply); + rpc JobsWatch (JobWatchRequest) returns (stream JobEvent); + rpc JobsCancel (JobCancelRequest) returns (JobReply); +} + +service Saves { + rpc ListProfiles (SaveProfileListRequest) returns (SaveProfileListReply); + rpc GetProfile (SaveProfileGetRequest) returns (SaveProfileReply); + rpc CreateProfile (SaveProfileCreateRequest) returns (SaveProfileMutationReply); + rpc UpdateProfile (SaveProfileUpdateRequest) returns (SaveProfileMutationReply); + rpc RemoveProfile (SaveProfileRemoveRequest) returns (SaveProfileMutationReply); +} + +service Locations { + rpc Inspect (LocationInspectRequest) returns (LocationInspectReply); + rpc GetSize (LocationSizeRequest) returns (LocationSizeReply); + rpc GetAccess (LocationAccessRequest) returns (LocationAccessReply); + rpc GetLastModified (LocationLastModifiedRequest) returns (LocationLastModifiedReply); + rpc GetFingerprint (LocationFingerprintRequest) returns (LocationFingerprintReply); + rpc Compare (LocationCompareRequest) returns (LocationCompareReply); + rpc WatchAvailability (LocationAvailabilityWatchRequest) returns (stream LocationAvailabilityEvent); +} + +service StorageDiagnostics { + rpc List (DiagnosticListRequest) returns (DiagnosticListReply); + rpc Get (DiagnosticGetRequest) returns (DiagnosticGetReply); + rpc Watch (DiagnosticWatchRequest) returns (stream DiagnosticEvent); +} + +service Computer { + rpc List (ComputerListRequest) returns (ComputerListReply); + rpc Get (ComputerGetRequest) returns (ComputerGetReply); + rpc Watch (ComputerWatchRequest) returns (stream ComputerEvent); +} + +service GamePresence { + rpc List (PresenceListRequest) returns (PresenceListReply); + rpc Get (PresenceGetRequest) returns (PresenceGetReply); + rpc Watch (PresenceWatchRequest) returns (stream PresenceEvent); +} + +service GamePerformance { + rpc List (PerformanceListRequest) returns (PerformanceListReply); + rpc Get (PerformanceGetRequest) returns (PerformanceGetReply); + rpc Watch (PerformanceWatchRequest) returns (stream PerformanceEvent); + rpc QuerySeries (PerformanceQuerySeriesRequest) returns (PerformanceQuerySeriesReply); + rpc Aggregate (PerformanceAggregateRequest) returns (PerformanceAggregateReply); +} + +// Typed operation messages for the API 1.6 services. Common identity, +// revision, pagination and idempotency values remain explicit protobuf fields. +message CustomLaunchRemoveRequest { MutationContext mutation = 1; string game_id = 2; string recipe_id = 3; } +message GameInstallRequest { ServiceContext context = 1; string game_id = 2; string installation_id = 3; string user_intent_id = 4; string idempotency_key = 5; } +message StorageGetRequest { ServiceContext context = 1; string key = 2; } +message StoragePutRequest { MutationContext mutation = 1; string key = 2; bytes value = 3; StorageDurability durability = 4; uint64 ttl_seconds = 5; } +message StorageDeleteRequest { MutationContext mutation = 1; string key = 2; } +enum StorageDurability { STORAGE_DURABILITY_UNSPECIFIED = 0; STORAGE_DURABILITY_SESSION_ONLY = 1; STORAGE_DURABILITY_PERSISTENT = 2; } +// A key lives in exactly one durability at a time. `durability` is the one the value has now and +// `expires_at` its Unix-seconds expiry (0 when it never expires); both are unset when +// `found` is false. In a put reply, `usage_bytes` and `quota_bytes` describe the namespace of +// the durability that was written, and `revision` is the key's new revision (the current one on a +// conflict). A key's revision is 0 while it does not exist, and is the `expected_revision` of +// the next put or delete. +message StorageGetReply { bytes value = 1; uint64 revision = 2; bool found = 3; StorageDurability durability = 4; int64 expires_at = 5; } +message StorageMutationReply { uint64 revision = 1; uint64 usage_bytes = 2; uint64 quota_bytes = 3; MutationOutcome outcome = 4; StorageDurability durability = 5; int64 expires_at = 6; } +// Where a plugin thinks the folder for `kind` ("save" or "prefix") usually is. The plugin names no +// path of its own authority: `location` is a suggestion the user may take or ignore, shown as +// declared by the plugin and not verified, and a declaration alone grants nothing. `location` is +// either an absolute path or starts with one of the placeholders `{home}`, `{documents}`, +// `{appdata}` and `{localappdata}` (Windows) or `{xdg_data}` and `{xdg_config}` (Linux), which +// the host expands, optionally followed by `/`-separated plain names (no `..`). Order is priority: +// within one `kind`, earlier is preferred. A suggestion that cannot apply on this system (a +// placeholder or a drive path of another system, or a system folder that does not exist) is +// dropped without an error, so one list can serve every platform; an unknown placeholder, a +// relative path, `..`, an overlong or malformed text, an unknown or `installation` kind, or +// more than 8 suggestions for one kind is INVALID_ARGUMENT. `description` is one line of plain +// text (at most 120 bytes) shown with the suggestion. Nothing is ever said back about which +// suggestions exist, were shown or were chosen. +message DeclaredLocation { string kind = 1; string location = 2; string description = 3; } +message FilesRequestAccessRequest { MutationContext mutation = 1; string game_id = 2; string installation_id = 3; repeated string requested_operations = 4; repeated string resource_kinds = 5; repeated DeclaredLocation declared_locations = 6; } +message FileHandle { string handle = 1; string display_name = 2; string resource_kind = 3; bool writable = 4; } +message FileAccessReply { repeated FileHandle handles = 1; } +message FilesListRequest { ServiceContext context = 1; string directory_handle = 2; string cursor = 3; uint32 page_size = 4; } +message FilesListReply { repeated FileEntry entries = 1; string next_cursor = 2; } +message FileEntry { string handle = 1; string name = 2; bool directory = 3; uint64 size_bytes = 4; int64 modified_at = 5; } +message FilesReadRequest { ServiceContext context = 1; string file_handle = 2; uint64 offset = 3; uint64 max_bytes = 4; } +message FileReadReply { bytes contents = 1; uint64 next_offset = 2; bool eof = 3; } +// File access is limited to a folder the user approved for this plugin and one installation of a +// game (FilesRequestAccess). Handles are opaque and bound to the session that received them. +// With `name` empty, `file_handle` is an existing file and `contents` go at `offset` (which may not +// pass the end of the file); with `truncate` the file ends where the write does. With `name` set, +// `file_handle` is a directory handle and the file `name` (one plain component) is created, or +// overwritten, inside it. The reply's `resource_id` is the handle of the written file. +message FilesWriteRequest { MutationContext mutation = 1; string file_handle = 2; uint64 offset = 3; bytes contents = 4; bool truncate = 5; string name = 6; } +message FilesDeleteRequest { MutationContext mutation = 1; string file_handle = 2; } +message NetworkFetchRequest { ServiceContext context = 1; string url = 2; string method = 3; map headers = 4; bytes body = 5; uint64 max_response_bytes = 6; uint32 timeout_ms = 7; } +message NetworkFetchReply { uint32 status_code = 1; map headers = 2; bytes body = 3; string final_origin = 4; } +// Plain text only, shown by Core as coming from the plugin. `title` and `body` are in `locale` (a +// language tag such as "en" or "pt-BR", or empty when unspecified); `translations` are optional +// versions in other locales, each with a distinct non-empty `locale`. Core shows the one that +// matches the user's language, then the same language without a region, then `title`/`body`. +// `severity` is empty or one of "info", "success", "warning", "error". Core renders every text as +// plain text: nothing in it is markup, a link or an action. `expected_revision` must be 0. +message NotificationTranslation { string locale = 1; string title = 2; string body = 3; } +message NotificationPublishRequest { MutationContext mutation = 1; string title = 2; string body = 3; string locale = 4; string severity = 5; repeated NotificationTranslation translations = 6; } +message BackupsListRequest { PageRequest page = 1; string game_id = 2; string profile_id = 3; } +message BackupCreateRequest { MutationContext mutation = 1; string game_id = 2; string profile_id = 3; string reason = 4; } +message BackupRestoreRequest { MutationContext mutation = 1; string backup_id = 2; string game_id = 3; string profile_id = 4; string user_intent_id = 5; } +message BackupsListReply { repeated BackupRecord backups = 1; string next_cursor = 2; } +message BackupRecord { string backup_id = 1; string game_id = 2; int64 created_at = 3; uint64 size_bytes = 4; string state = 5; } +message JobReply { string job_id = 1; JobState state = 2; string result_code = 3; string message = 4; uint64 revision = 5; } +enum JobState { JOB_STATE_UNSPECIFIED = 0; JOB_STATE_QUEUED = 1; JOB_STATE_RUNNING = 2; JOB_STATE_SUCCEEDED = 3; JOB_STATE_FAILED = 4; JOB_STATE_CANCELLED = 5; } +message DomainListRequest { PageRequest page = 1; string kind = 2; string owner_filter = 3; } +message DomainGetRequest { ServiceContext context = 1; string resource_id = 2; uint64 expected_revision = 3; CommonDataSelector shared_records = 4; } +message DomainWatchRequest { ServiceContext context = 1; uint64 after_revision = 2; string resource_id = 3; CommonDataSelector shared_records = 4; } +message DomainRemoveRequest { MutationContext mutation = 1; string resource_id = 2; } +message LibraryCreateRequest { MutationContext mutation = 1; string name = 2; string description = 3; } +message LibraryUpdateRequest { MutationContext mutation = 1; string library_id = 2; string name = 3; string description = 4; repeated string field_mask = 5; } +message LibraryRootAddRequest { MutationContext mutation = 1; string library_id = 2; string approved_root_handle = 3; string display_name = 4; repeated DeclaredLocation declared_locations = 5; } +message LibraryRootUpdateRequest { MutationContext mutation = 1; string library_id = 2; string root_id = 3; string approved_root_handle = 4; string display_name = 5; repeated DeclaredLocation declared_locations = 6; repeated string field_mask = 7; bool watching = 8; } +message LibraryRootRemoveRequest { MutationContext mutation = 1; string library_id = 2; string root_id = 3; } +message LibraryRecord { string id = 1; string name = 2; string creator_plugin_id = 3; repeated string root_ids = 4; uint64 revision = 5; string description = 6; repeated LibraryRootRecord roots = 7; } +message LibraryRootRecord { string id = 1; string display_name = 2; bool watching = 3; InspectionAvailability availability = 4; reserved 5; string approved_root_handle = 6; string discovery_state = 7; } +message LibrariesListReply { repeated LibraryRecord libraries = 1; string next_cursor = 2; uint64 revision = 3; } +message LibraryRecordReply { LibraryRecord library = 1; uint64 revision = 2; } +message LibraryRecordEvent { uint64 revision = 1; string event_type = 2; LibraryRecord library = 3; } +message LibraryMutationReply { string resource_id = 1; uint64 revision = 2; MutationOutcome outcome = 3; } +message RuntimeRegisterRequest { MutationContext mutation = 1; RuntimeRecord runtime = 2; } +// Asks the host to let the user choose, validate and approve one exact executable as a runtime. +// `runtime.executable_handle` must be empty: the plugin supplies a spec and text hints only, never +// a path or a handle. The host shows its picker, validates the chosen program, creates the owned +// runtime and answers with an ordinary runtime record whose executable handle stays empty. A +// valid existing owned runtime for the same name/platform/formats is returned without a prompt. +// Declining the picker creates nothing. The request is idempotent for its key. +message RuntimeAccessHints { + repeated string executable_names = 1; + repeated string desktop_ids = 2; +} +message RuntimeRequestAccessRequest { + MutationContext mutation = 1; + RuntimeRecord runtime = 2; + RuntimeAccessHints hints = 3; +} +message RuntimeUpdateRequest { + MutationContext mutation = 1; + RuntimeRecord runtime = 2; + repeated string field_mask = 3; + ExtensionPatch extension_patch = 4; +} +message RuntimeMutationReply { RuntimeRecord runtime = 1; MutationOutcome outcome = 2; } +message RuntimeRecordReply { RuntimeRecord runtime = 1; uint64 revision = 2; } +message RuntimeRecordEvent { uint64 revision = 1; string event_type = 2; RuntimeRecord runtime = 3; } +message RuntimesListReply { repeated RuntimeRecord runtimes = 1; string next_cursor = 2; uint64 revision = 3; } +message ContentRegistrationRequest { MutationContext mutation = 1; string game_id = 2; string installation_id = 3; string content_handle = 4; string content_kind = 5; string runtime_id = 6; repeated string supported_platforms = 7; string content_id = 8; } +message ReportMutationReply { + string report_id = 1; + uint64 revision = 2; + MutationOutcome outcome = 3; + // Used by bounded batch publishers to report accepted/dropped samples and retry guidance. + uint32 accepted_samples = 4; + uint32 dropped_samples = 5; + uint32 retry_after_ms = 6; + int64 retained_from = 7; + int64 retained_to = 8; +} +enum DiagnosticValueState { DIAGNOSTIC_VALUE_STATE_UNSPECIFIED = 0; DIAGNOSTIC_VALUE_STATE_AVAILABLE = 1; DIAGNOSTIC_VALUE_STATE_UNAVAILABLE = 2; DIAGNOSTIC_VALUE_STATE_UNSUPPORTED = 3; DIAGNOSTIC_VALUE_STATE_ACCESS_DENIED = 4; DIAGNOSTIC_VALUE_STATE_ERROR = 5; } +message BenchmarkReportRequest { MutationContext mutation = 1; string volume_handle = 2; string tool_name = 3; string tool_version = 4; map measurements = 5; string units = 6; int64 observed_at = 7; map measurement_units = 8; map measurement_states = 9; google.protobuf.Struct conditions = 10; } +message SmartReportRequest { MutationContext mutation = 1; string volume_handle = 2; string device_model = 3; string firmware = 4; map attributes = 5; int64 observed_at = 6; map attribute_units = 7; map attribute_states = 8; google.protobuf.Struct conditions = 9; } +message HardwareReportRequest { MutationContext mutation = 1; string computer_id = 2; string schema_id = 3; uint32 schema_version = 4; google.protobuf.Struct observations = 5; int64 observed_at = 6; } +message PresencePublishRequest { MutationContext mutation = 1; string game_id = 2; string session_id = 3; google.protobuf.Struct details = 4; uint64 ttl_seconds = 5; } +message PresenceClearRequest { MutationContext mutation = 1; string game_id = 2; string session_id = 3; } +enum PerformanceFpsMethod { PERFORMANCE_FPS_METHOD_UNSPECIFIED = 0; PERFORMANCE_FPS_METHOD_INSTANTANEOUS = 1; PERFORMANCE_FPS_METHOD_FRAME_COUNT_WINDOW = 2; PERFORMANCE_FPS_METHOD_FRAME_TIME_DERIVED = 3; } +enum PerformanceFpsStatistic { PERFORMANCE_FPS_STATISTIC_UNSPECIFIED = 0; PERFORMANCE_FPS_STATISTIC_INSTANTANEOUS = 1; PERFORMANCE_FPS_STATISTIC_AVERAGE = 2; PERFORMANCE_FPS_STATISTIC_MINIMUM = 3; PERFORMANCE_FPS_STATISTIC_MAXIMUM = 4; PERFORMANCE_FPS_STATISTIC_PERCENTILE = 5; } +enum PerformanceMeasurementQuality { PERFORMANCE_MEASUREMENT_QUALITY_UNSPECIFIED = 0; PERFORMANCE_MEASUREMENT_QUALITY_MEASURED = 1; PERFORMANCE_MEASUREMENT_QUALITY_ESTIMATED = 2; } +enum PerformanceCpuScope { PERFORMANCE_CPU_SCOPE_UNSPECIFIED = 0; PERFORMANCE_CPU_SCOPE_PROCESS = 1; PERFORMANCE_CPU_SCOPE_SYSTEM = 2; } +enum PerformanceCpuNormalization { PERFORMANCE_CPU_NORMALIZATION_UNSPECIFIED = 0; PERFORMANCE_CPU_NORMALIZATION_WHOLE_MACHINE_PERCENT = 1; PERFORMANCE_CPU_NORMALIZATION_PER_CORE_PERCENT = 2; } +enum PerformanceMemoryKind { PERFORMANCE_MEMORY_KIND_UNSPECIFIED = 0; PERFORMANCE_MEMORY_KIND_WORKING_SET_BYTES = 1; PERFORMANCE_MEMORY_KIND_RESIDENT_BYTES = 2; } +message PerformanceSample { + // Unix milliseconds, preserving the cadence allowed by sample_interval_ms (down to 100 ms). + int64 observed_at = 1; + // Always frames/second; fps_method/fps_statistic describe the collection window and statistic. + double frames_per_second = 2; + // Percent; scope and normalization are declared once for the series. + double cpu_percent = 3; + // Bytes of working set or resident memory as declared by the series. + uint64 memory_bytes = 4; + // Positive and increasing within one series. Gaps remain visible as dropped samples. + uint64 sequence = 5; + uint32 sampling_window_ms = 6; + PerformanceFpsMethod fps_method = 7; + PerformanceFpsStatistic fps_statistic = 8; + optional double fps_percentile = 9; + optional double frames_per_second_min = 10; + optional double frames_per_second_max = 11; + PerformanceMeasurementQuality quality = 12; +} +message PerformanceSamplesRequest { + MutationContext mutation = 1; + string series_id = 2; + string game_id = 3; + string computer_id = 4; + repeated PerformanceSample samples = 5; + string runtime_id = 6; + string runtime_recipe_revision = 7; + string source = 8; + string tool_name = 9; + string tool_version = 10; + uint32 sample_interval_ms = 11; + PerformanceCpuScope cpu_scope = 12; + PerformanceCpuNormalization cpu_normalization = 13; + PerformanceMemoryKind memory_kind = 14; + string memory_source = 15; + string fps_unit = 16; + string cpu_unit = 17; + string memory_unit = 18; +} +message PerformanceEndSeriesRequest { MutationContext mutation = 1; string series_id = 2; int64 ended_at = 3; uint64 expected_last_sequence = 4; } +message DataPublishRequest { MutationContext mutation = 1; string dataset_id = 2; string schema_id = 3; uint32 schema_version = 4; google.protobuf.Struct value = 5; StorageDurability durability = 6; uint64 ttl_seconds = 7; bytes opaque_payload = 8; string resource_id = 9; int64 observed_at = 10; uint64 sequence = 11; string source_observation_id = 12; } +// `durability` reports the mode the host actually used; a reply never names a mode the record +// does not have, and a durable mode is never a session-only downgrade. `expires_at` is the +// record's Unix-seconds expiry (0 when it does not expire). +message DataMutationReply { string record_id = 1; uint64 revision = 2; int64 expires_at = 3; MutationOutcome outcome = 4; StorageDurability durability = 5; } +message DataGetRequest { ServiceContext context = 1; string dataset_id = 2; string record_id = 3; CommonDataSelector common_data_categories = 4; } +message DataListRequest { PageRequest page = 1; string dataset_id = 2; string filter = 3; CommonDataSelector common_data_categories = 4; } +message DataWatchRequest { ServiceContext context = 1; string dataset_id = 2; uint64 after_revision = 3; CommonDataSelector common_data_categories = 4; } +// `durability` is additive: older readers ignore it and read the rest of the record unchanged, +// while a newer reader reports the mode the record actually has. Session-retained records keep +// the value session-only. +message DataRecord { string record_id = 1; string dataset_id = 2; string publisher_id = 3; uint64 revision = 4; google.protobuf.Struct value = 5; string schema_id = 6; uint32 schema_version = 7; bytes opaque_payload = 8; DataProvenance provenance = 9; string resource_id = 10; int64 observed_at = 11; int64 received_at = 12; int64 expires_at = 13; uint64 sequence = 14; string source_observation_id = 15; StorageDurability durability = 16; } +// Host-assigned provenance for published data and common domain projections. +message DataProvenance { string producer_plugin_id = 1; string declared_developer = 2; string origin = 3; string publisher_fingerprint = 4; string package_version = 5; bytes package_digest = 6; string resource_id = 7; int64 observed_at = 8; int64 received_at = 9; repeated string source_record_ids = 10; } +message DataGetReply { DataRecord record = 1; } +message DataListReply { repeated DataRecord records = 1; string next_cursor = 2; uint64 revision = 3; } +message DataEvent { uint64 revision = 1; string event_type = 2; DataRecord record = 3; } +message PersistenceUsageRequest { ServiceContext context = 1; } +// `categories` and `physical_bytes_namespace_wide` are additive accounting detail. Only the +// `private` category counts against `quota_bytes`; `physical_bytes` is the SQLite page allocation +// of the whole namespace database, whose metadata and free pages are shared across categories. +message PersistenceCategoryUsage { string category = 1; uint64 records = 2; uint64 logical_bytes = 3; uint64 protected_records = 4; } +message PersistenceUsageReply { uint64 logical_bytes = 1; uint64 physical_bytes = 2; uint64 quota_bytes = 3; repeated PersistenceCategoryUsage categories = 4; bool physical_bytes_namespace_wide = 5; } +message PersistenceListRequest { PageRequest page = 1; string category = 2; } +message PersistenceListReply { repeated PersistenceEntry entries = 1; string next_cursor = 2; } +message PersistenceEntry { string entry_id = 1; string category = 2; string logical_key = 3; uint64 size_bytes = 4; int64 last_used_at = 5; bool user_protected = 6; } +message PersistenceDeleteRequest { MutationContext mutation = 1; repeated string entry_ids = 2; } +message PersistenceClearRequest { MutationContext mutation = 1; string category = 2; } +message RetentionPolicyRequest { MutationContext mutation = 1; string category = 2; uint64 max_age_seconds = 3; uint64 max_bytes = 4; } +message PersistenceMutationReply { uint64 reclaimed_bytes = 1; uint64 revision = 2; MutationOutcome outcome = 3; } +message ToolsListRequest { PageRequest page = 1; string game_id = 2; string platform = 3; } +message ToolApplyRequest { MutationContext mutation = 1; string tool_id = 2; string game_id = 3; string user_intent_id = 4; } +message ToolRemoveRequest { MutationContext mutation = 1; string tool_id = 2; string game_id = 3; string user_intent_id = 4; } +message ToolsListReply { repeated ToolRecord tools = 1; string next_cursor = 2; } +message ToolRecord { string tool_id = 1; string name = 2; string version = 3; string availability = 4; } +message PortsListRequest { PageRequest page = 1; string platform = 2; string query = 3; } +message PortDetailRequest { ServiceContext context = 1; string port_id = 2; } +message PortInstallRequest { MutationContext mutation = 1; string port_id = 2; string game_id = 3; repeated string supplied_file_handles = 4; string user_intent_id = 5; } +message PortsListReply { repeated PortRecord ports = 1; string next_cursor = 2; } +message PortDetailReply { PortRecord port = 1; } +message PortRecord { string port_id = 1; string name = 2; string platform = 3; string availability = 4; } +message JobGetRequest { ServiceContext context = 1; string job_id = 2; } +message JobWatchRequest { ServiceContext context = 1; string job_id = 2; uint64 after_sequence = 3; } +message JobCancelRequest { MutationContext mutation = 1; string job_id = 2; } +message JobEvent { string job_id = 1; uint64 sequence = 2; JobState state = 3; uint32 progress_percent = 4; string result_code = 5; string message = 6; } + +// Shared mutation envelope. operation_id is host-issued; idempotency_key is +// client supplied and scoped to the authenticated plugin and operation. +message MutationContext { + ServiceContext context = 1; + string operation_id = 2; + string idempotency_key = 3; + uint64 expected_revision = 4; +} + +message PageRequest { + ServiceContext context = 1; + string cursor = 2; + uint32 page_size = 3; + CommonDataSelector common_data_categories = 4; +} +message LibraryListRequest { PageRequest page = 1; string provider_id = 2; string search = 3; } +message LibraryGetRequest { ServiceContext context = 1; string game_id = 2; string installation_id = 3; CommonDataSelector common_data_categories = 4; } +message LibraryWatchRequest { ServiceContext context = 1; uint64 after_revision = 2; string provider_id = 3; CommonDataSelector common_data_categories = 4; } +message MetadataUpdateRequest { MutationContext mutation = 1; string game_id = 2; string installation_id = 3; map display_fields = 4; } +message FavoritesListRequest { PageRequest page = 1; string profile_id = 2; } +message FavoritesSetRequest { MutationContext mutation = 1; string profile_id = 2; string game_id = 3; bool favorite = 4; } +// Catalog search by title. `platform` and `cursor` are reserved and must be empty: the catalog +// has no platform filter and a search is one bounded page (`page_size` defaults to 20, at most +// 50), so `MatchingSearchReply.next_cursor` is always empty. +message MatchingSearchRequest { ServiceContext context = 1; string query = 2; string platform = 3; uint32 page_size = 4; string cursor = 5; } +// Assigns one of the caller's own entries to a GameNode game. The entry is named by its +// `installation_id`; `provider_id` and `provider_game_id` are reserved and must be empty. +// `mutation.expected_revision` is the entry's `LibraryEntry.revision`. The reply's `resource_id` +// is the installation id and `revision` the entry's revision after the call. +message MatchingAssignRequest { MutationContext mutation = 1; string provider_id = 2; string provider_game_id = 3; string gamenode_game_id = 4; string installation_id = 5; } +// Reads the cover an own entry shows: the plugin's override, else the matched game's cover when it +// is already on the device (nothing is downloaded). `installation_id` is required; `game_id`, if +// set, must be the entry's current match. `artwork_kind` is "cover" or empty. `max_bytes` is the +// caller's budget: 0 means the 5 MiB maximum, larger values are capped to it, and an image over +// the budget is RESOURCE_EXHAUSTED rather than truncated. +message ArtworkReadRequest { ServiceContext context = 1; string game_id = 2; string installation_id = 3; string artwork_kind = 4; uint64 max_bytes = 5; } +// Sets the cover of one of the caller's own entries, or restores the game's cover when +// `encoded_image` is empty (then `media_type` must be empty too). The image is a static PNG, JPEG +// or WebP of at most 4 MiB and 4096 x 4096 pixels whose bytes match `media_type`; the host decodes, +// shrinks to fit 600 x 900 and re-encodes it, and stores its own output as that entry's cover. The +// matched game's cover and other entries are never changed. `mutation.expected_revision` is the +// entry's `LibraryEntry.artwork_revision`. The reply's `resource_id` is the installation id and +// `revision` the artwork revision after the call. +// The image comes either inline (`encoded_image`) or from a file the plugin may read +// (`file_handle`, a regular-file handle from the Files service, with `media_type` set as for +// inline bytes); giving both is INVALID_ARGUMENT. A handle needs `files.read` besides +// `artwork.write`, must come from an approval of this same installation, and its bytes are read by +// the host under the same 4 MiB bound and then decoded like inline ones. A path or a URL is never +// accepted: the handle is the only reference. +message ArtworkSetRequest { MutationContext mutation = 1; string game_id = 2; string installation_id = 3; string artwork_kind = 4; bytes encoded_image = 5; string media_type = 6; string file_handle = 7; } +message LibraryListReply { repeated LibraryEntry entries = 1; string next_cursor = 2; uint64 revision = 3; } +message LibraryGetReply { LibraryEntry entry = 1; uint64 revision = 2; } +message FavoritesListReply { repeated FavoriteEntry entries = 1; string next_cursor = 2; uint64 revision = 3; } +message MatchingSearchReply { repeated MatchCandidate candidates = 1; string next_cursor = 2; } +// `revision` is the entry's artwork revision: 0 while the cover is the game's own. +message ArtworkReadReply { bytes encoded_image = 1; string media_type = 2; uint64 byte_length = 3; uint64 revision = 4; } +message MutationReply { string resource_id = 1; uint64 revision = 2; MutationOutcome outcome = 3; } +enum MutationOutcome { MUTATION_OUTCOME_UNSPECIFIED = 0; MUTATION_OUTCOME_APPLIED = 1; MUTATION_OUTCOME_ALREADY_APPLIED = 2; MUTATION_OUTCOME_REVISION_CONFLICT = 3; MUTATION_OUTCOME_BACKPRESSURE = 4; } +// `name` is the detected name (or the matched game's name when the provider reported none); +// `display_name` is the presentation override the owning provider wrote with MetadataUpdate and is +// empty when none is set. `metadata_revision` is the revision of that override for this +// installation (0 until first written); it is the expected_revision of the next MetadataUpdate. +// `artwork_revision` is the same for the cover override ArtworkSet writes: 0 until first written, +// and the expected_revision of the next ArtworkSet. +message LibraryEntry { string game_id = 1; string installation_id = 2; string provider_id = 3; string name = 4; string version = 5; string install_state = 6; uint64 revision = 7; string display_name = 8; uint64 metadata_revision = 9; uint64 artwork_revision = 10; repeated RuntimeAvailability runtime_availability = 11; } +// Safe content/runtime availability projection; it never includes a path, handle or payload. +message RuntimeAvailability { string content_id = 1; string content_kind = 2; string runtime_id = 3; string runtime_name = 4; string platform = 5; string publisher_id = 6; uint64 revision = 7; } +message FavoriteEntry { string game_id = 1; bool favorite = 2; uint64 revision = 3; } +// A catalog game a search found. `platform` and `confidence` are reserved: the catalog carries +// neither, so both are empty. `release_year` is 0 when unknown. +message MatchCandidate { string game_id = 1; string title = 2; string platform = 3; string confidence = 4; int32 release_year = 5; } +message LibraryEvent { uint64 revision = 1; string event_type = 2; LibraryEntry entry = 3; } + +message ResourceRequest { + ServiceContext context = 1; + string resource_id = 2; + string operation_id = 3; + string idempotency_key = 4; + uint64 expected_revision = 5; + string cursor = 6; + uint32 page_size = 7; + uint64 max_bytes = 8; + string durability = 9; + bytes payload = 10; + // Deprecated API 1.6 draft fields. Kept at their original wire numbers so + // clients compiled against the draft remain wire-decodable; hosts MUST NOT + // use these untyped fields to authorize or include shared records. + bool include_common = 11 [deprecated = true]; + repeated string selected_categories = 12 [deprecated = true]; + // Omitted or empty means private/owner-visible records only. Each requested + // category is independently checked against the caller's current grant. + CommonDataSelector common_data_categories = 13; +} + +// Explicit, per-query selector for published projections. Category grants and +// selected-record grants are independently checked by the host; this selector +// never grants authority or triggers automatic reads. Sensitive/custom fields +// still require their separate sharing review, and secrets are excluded. +message CommonDataSelector { + repeated CommonDataCategory categories = 1; + // Explicit ids are independently checked against selected-record grants; + // they do not require or imply a category-wide grant. + repeated string selected_record_ids = 2; +} + +enum CommonDataCategory { + COMMON_DATA_CATEGORY_UNSPECIFIED = 0; + COMMON_DATA_CATEGORY_GAME_PATHS = 1; + COMMON_DATA_CATEGORY_GAME_PERFORMANCE_HISTORY = 2; + COMMON_DATA_CATEGORY_RUNTIME_CATALOG = 3; + COMMON_DATA_CATEGORY_CONTENT_AVAILABILITY = 4; + COMMON_DATA_CATEGORY_LIBRARY_ROOTS = 5; + COMMON_DATA_CATEGORY_SAVE_PROFILES = 6; +} + +message SaveProfileListRequest { + ServiceContext context = 1; + string game_id = 2; + string installation_id = 3; + string cursor = 4; + uint32 page_size = 5; + CommonDataSelector shared_records = 6; +} +message SaveProfileGetRequest { ServiceContext context = 1; string game_id = 2; string profile_id = 3; CommonDataSelector shared_records = 4; } +message SaveProfileCreateRequest { MutationContext mutation = 1; SaveProfile profile = 2; } +message SaveProfileUpdateRequest { MutationContext mutation = 1; string profile_id = 2; SaveProfilePatch patch = 3; } +message SaveProfileRemoveRequest { MutationContext mutation = 1; string game_id = 2; string profile_id = 3; } +message SaveProfilePatch { repeated string field_mask = 1; SaveProfile profile = 2; } +message SaveProfile { + string profile_id = 1; + string game_id = 2; + string installation_id = 3; + string name = 4; + repeated SaveDirectory directories = 5; + string runtime_id = 6; + string format_id = 7; + uint32 format_version = 8; + google.protobuf.Struct descriptive_metadata = 9; + string creator_plugin_id = 10; + uint64 revision = 11; + // Host-resolved shared emulator resources this profile uses. The caller proposes the alias and + // an approved folder handle; the host binds the backing identity, affected games and consent. + repeated SharedResourceDeclaration shared_resources = 12; +} +message SaveDirectory { string approved_resource_handle = 1; string display_name = 2; repeated string naming_patterns = 3; } +// The host accepts a declaration only as a proposal. Consent is granted through host settings, +// never by a plugin RPC, and the host revalidates the exact scope before every use. +message SharedResourceDeclaration { + // Plugin-chosen alias, 1 to 128 bytes. All profiles that share one backing resource must use + // the same alias. + string resource_id = 1; + // Opaque host-issued handle for the approved backing folder. Empty in a reply when the caller + // no longer has a standing approval or is reading another plugin's profile. + string approved_resource_handle = 2; + string display_name = 3; + // Host-computed; absent from create/update requests. + SharedResourceConsent consent = 4; +} +enum SharedResourceConsent { + SHARED_RESOURCE_CONSENT_UNSPECIFIED = 0; + SHARED_RESOURCE_CONSENT_PENDING = 1; + SHARED_RESOURCE_CONSENT_CURRENT = 2; + SHARED_RESOURCE_CONSENT_STALE = 3; +} +message SaveProfileListReply { repeated SaveProfile profiles = 1; string next_cursor = 2; uint64 revision = 3; } +message SaveProfileReply { SaveProfile profile = 1; uint64 revision = 2; } +message SaveProfileMutationReply { string profile_id = 1; uint64 revision = 2; MutationOutcome outcome = 3; } + +enum InspectionAvailability { INSPECTION_AVAILABILITY_UNSPECIFIED = 0; INSPECTION_AVAILABILITY_AVAILABLE = 1; INSPECTION_AVAILABILITY_UNMOUNTED = 2; INSPECTION_AVAILABILITY_DISCONNECTED = 3; INSPECTION_AVAILABILITY_INACCESSIBLE = 4; INSPECTION_AVAILABILITY_MISSING = 5; INSPECTION_AVAILABILITY_UNKNOWN = 6; } +message LocationInspectRequest { ServiceContext context = 1; string approved_resource_handle = 2; repeated string requested_dimensions = 3; uint32 max_entries = 4; } +message LocationInspectReply { LocationDescription location = 1; repeated LocationObservation observations = 2; repeated LocationDescription locations = 3; } +message LocationSizeRequest { ServiceContext context = 1; string approved_resource_handle = 2; uint32 max_entries = 3; } +message LocationSizeReply { uint64 logical_bytes = 1; uint64 file_count = 2; uint64 directory_count = 3; bool complete = 4; InspectionAvailability availability = 5; } +message LocationAccessRequest { ServiceContext context = 1; string approved_resource_handle = 2; repeated string entry_handles = 3; } +message LocationAccessReply { repeated LocationAccessEntry entries = 1; InspectionAvailability availability = 2; } +message LocationLastModifiedRequest { ServiceContext context = 1; string approved_resource_handle = 2; uint32 max_entries = 3; } +message LocationLastModifiedReply { repeated LocationTimestamp entries = 1; optional int64 aggregate_latest_at = 2; InspectionAvailability availability = 3; } +message LocationFingerprintRequest { ServiceContext context = 1; string approved_resource_handle = 2; string algorithm = 3; bool require_fresh = 4; uint32 max_entries = 5; string idempotency_key = 6; } +// `digest` is present only when `complete`. `observed_start_at` and `observed_end_at` are Unix +// seconds; the observation is best effort, not an atomic snapshot of the files. +message LocationFingerprintReply { string snapshot_id = 1; string algorithm = 2; bytes digest = 3; uint64 revision = 4; bool complete = 5; string consistency = 6; string job_id = 7; InspectionAvailability availability = 8; int64 observed_start_at = 9; int64 observed_end_at = 10; } +message LocationCompareRequest { ServiceContext context = 1; string before_snapshot_id = 2; string after_snapshot_id = 3; uint64 expected_revision = 4; uint32 page_size = 5; string cursor = 6; } +message LocationCompareReply { repeated LocationChange changes = 1; string next_cursor = 2; string status = 3; uint64 revision = 4; } +message LocationAvailabilityWatchRequest { ServiceContext context = 1; string approved_resource_handle = 2; uint64 after_sequence = 3; } +message LocationAvailabilityEvent { uint64 sequence = 1; string resource_id = 2; InspectionAvailability availability = 3; string volume_identity_token = 4; int64 observed_at = 5; } +message LocationDescription { string resource_id = 1; InspectionAvailability availability = 2; string volume_identity_token = 3; string mount_point = 4; string network_state = 5; string media_type = 6; uint64 capacity_bytes = 7; uint64 free_bytes = 8; int64 observed_at = 9; string attachment = 10; string interface_type = 11; string evidence = 12; } +message LocationObservation { string entry_handle = 1; string kind = 2; uint64 logical_bytes = 3; InspectionAvailability availability = 4; } +message LocationAccessEntry { string entry_handle = 1; string read_only_state = 2; string effective_access = 3; InspectionAvailability availability = 4; } +message LocationTimestamp { string entry_handle = 1; int64 modified_at = 2; string precision = 3; } +// `relative_path` is the entry's path below the compared place (for a save profile, `d/` for +// its n-th folder comes first); `entry_handle` is empty for an entry that no longer exists. +message LocationChange { string entry_handle = 1; string change_kind = 2; uint64 previous_size_bytes = 3; uint64 current_size_bytes = 4; string relative_path = 5; } + +message DiagnosticListRequest { PageRequest page = 1; string owner_plugin_id = 2; string volume_identity_token = 3; string projection_id = 4; } +message DiagnosticGetRequest { ServiceContext context = 1; string report_id = 2; string projection_id = 3; } +message DiagnosticWatchRequest { ServiceContext context = 1; string owner_plugin_id = 2; string volume_identity_token = 3; string projection_id = 4; uint64 after_revision = 5; } +message DiagnosticReport { string report_id = 1; string report_kind = 2; string owner_plugin_id = 3; string volume_identity_token = 4; string schema_id = 5; uint32 schema_version = 6; google.protobuf.Struct typed_measurements = 7; google.protobuf.Struct approved_extension = 8; int64 observed_at = 9; uint64 revision = 10; } +message DiagnosticListReply { repeated DiagnosticReport reports = 1; string next_cursor = 2; uint64 revision = 3; } +message DiagnosticGetReply { DiagnosticReport report = 1; } +message DiagnosticEvent { uint64 revision = 1; string event_type = 2; DiagnosticReport report = 3; } + +message ComputerListRequest { PageRequest page = 1; string computer_context_id = 2; string projection_id = 3; } +message ComputerGetRequest { ServiceContext context = 1; string computer_record_id = 2; string projection_id = 3; } +message ComputerWatchRequest { ServiceContext context = 1; string computer_context_id = 2; string projection_id = 3; uint64 after_revision = 4; } +message ComputerReport { string record_id = 1; string computer_context_id = 2; string owner_plugin_id = 3; string schema_id = 4; uint32 schema_version = 5; google.protobuf.Struct typed_observations = 6; google.protobuf.Struct approved_extension = 7; int64 observed_at = 8; uint64 revision = 9; } +message ComputerListReply { repeated ComputerReport reports = 1; string next_cursor = 2; uint64 revision = 3; } +message ComputerGetReply { ComputerReport report = 1; } +message ComputerEvent { uint64 revision = 1; string event_type = 2; ComputerReport report = 3; } + +message PresenceListRequest { PageRequest page = 1; string game_id = 2; string session_id = 3; string projection_id = 4; } +message PresenceGetRequest { ServiceContext context = 1; string presence_id = 2; string projection_id = 3; } +message PresenceWatchRequest { ServiceContext context = 1; string game_id = 2; string session_id = 3; string projection_id = 4; uint64 after_sequence = 5; } +message PresenceRecord { string presence_id = 1; string game_id = 2; string session_id = 3; string owner_plugin_id = 4; uint64 sequence = 5; int64 observed_at = 6; int64 expires_at = 7; google.protobuf.Struct approved_details = 8; uint64 revision = 9; } +message PresenceListReply { repeated PresenceRecord records = 1; string next_cursor = 2; uint64 revision = 3; } +message PresenceGetReply { PresenceRecord record = 1; } +message PresenceEvent { uint64 sequence = 1; string event_type = 2; PresenceRecord record = 3; } + +message PerformanceListRequest { PageRequest page = 1; string game_id = 2; string computer_context_id = 3; string projection_id = 4; } +message PerformanceGetRequest { ServiceContext context = 1; string series_id = 2; string projection_id = 3; CommonDataSelector common_data_categories = 4; } +message PerformanceWatchRequest { ServiceContext context = 1; string game_id = 2; string computer_context_id = 3; string projection_id = 4; uint64 after_sequence = 5; CommonDataSelector common_data_categories = 6; } +message PerformanceQuerySeriesRequest { ServiceContext context = 1; string series_id = 2; int64 from_time = 3; int64 to_time = 4; uint32 resolution_ms = 5; PageRequest page = 6; CommonDataSelector common_data_categories = 7; } +message PerformanceAggregateRequest { ServiceContext context = 1; string series_id = 2; int64 from_time = 3; int64 to_time = 4; string metric = 5; string aggregation = 6; CommonDataSelector common_data_categories = 7; } +message PerformanceSeries { + // Stable host-owned owner token. record_id identifies the current broker revision for + // selected-record sharing; replacement creates a new record_id. + string series_id = 1; + string game_id = 2; + string installation_id = 3; + string computer_context_id = 4; + string session_id = 5; + string owner_plugin_id = 6; + repeated PerformanceSample samples = 7; + uint64 revision = 8; + string runtime_id = 9; + string runtime_recipe_revision = 10; + string source = 11; + string tool_name = 12; + string tool_version = 13; + uint32 sample_interval_ms = 14; + PerformanceCpuScope cpu_scope = 15; + PerformanceCpuNormalization cpu_normalization = 16; + PerformanceMemoryKind memory_kind = 17; + string memory_source = 18; + int64 started_at = 19; + int64 ended_at = 20; + uint64 dropped_samples = 21; + string coverage = 22; + string provenance = 23; + string fps_unit = 24; + string cpu_unit = 25; + string memory_unit = 26; + string record_id = 27; +} +message PerformanceListReply { repeated PerformanceSeries series = 1; string next_cursor = 2; uint64 revision = 3; } +message PerformanceGetReply { PerformanceSeries series = 1; } +message PerformanceEvent { uint64 sequence = 1; string event_type = 2; PerformanceSeries series = 3; } +message PerformanceQuerySeriesReply { repeated PerformanceSample samples = 1; string next_cursor = 2; string coverage = 3; uint64 dropped_samples = 4; } +message PerformanceAggregateReply { string metric = 1; string aggregation = 2; double value = 3; string unit = 4; uint64 sample_count = 5; string coverage = 6; string provenance = 7; } +message ResourceReply { + string resource_id = 1; + uint64 revision = 2; + string next_cursor = 3; + uint64 usage_bytes = 4; + uint64 quota_bytes = 5; + string job_id = 6; + string outcome = 7; + bytes payload = 8; +} +message ResourceEvent { + uint64 revision = 1; + string resource_id = 2; + string event_type = 3; + bytes payload = 4; +} +message GameLaunchRequest { + ServiceContext context = 1; + string game_id = 2; + string installation_id = 3; + uint64 expected_revision = 4; + string user_intent_id = 5; + string idempotency_key = 6; +} +message GameLaunchReply { string job_id = 1; JobState state = 2; string refusal_code = 3; string message = 4; } +// A declared launch-time mod layer. The host cannot inspect mod files, so `id`, `name` and +// `version` are plugin-provided data shown in the reviewed plan; `revision` and the ordered +// argv/environment contributions are host-validated. Execution requests may reference only the +// recipe revision, never replace or add layers. +message CustomLaunchModLayer { + string id = 1; + string name = 2; + string version = 3; + uint64 revision = 4; + repeated string argv = 5; + map environment_set = 6; + repeated string environment_unset = 7; +} +message CustomLaunchRequest { + ServiceContext context = 1; + string game_id = 2; + string installation_id = 3; + uint64 expected_revision = 4; + string user_intent_id = 5; + string idempotency_key = 6; + string executable_handle = 7; + repeated string argv = 8; + string working_directory_handle = 9; + map environment_set = 10; + repeated string environment_unset = 11; + string runtime_handle = 12; + string recipe_id = 13; + uint64 recipe_revision = 14; + string uri = 15; + string content_id = 16; + // Proposal-only declared layers, applied after `argv`/`environment_*` in order. Empty on + // execution requests; the host resolves them from the stored reviewed recipe. + repeated CustomLaunchModLayer mod_layers = 17; +} +message CustomLaunchReply { string recipe_id = 1; uint64 recipe_revision = 2; string job_id = 3; JobState state = 4; string refusal_code = 5; string message = 6; } + +// Extensible application metadata. Typed identity, ownership, grants, revisions +// and execution fields stay outside Struct and are never inferred from it. +message ExtensionPayload { + string schema_id = 1; + uint32 schema_version = 2; + bytes schema_digest = 3; + google.protobuf.Struct data = 4; +} + +enum ExtensionFieldClassification { + EXTENSION_FIELD_CLASSIFICATION_UNSPECIFIED = 0; + EXTENSION_FIELD_CLASSIFICATION_PUBLIC = 1; + EXTENSION_FIELD_CLASSIFICATION_SENSITIVE = 2; + EXTENSION_FIELD_CLASSIFICATION_PRIVATE = 3; +} + +message ExtensionSchemaField { + string path = 1; + ExtensionFieldClassification classification = 2; +} + +// Declarative package asset; schema_json is bounded data, never executable code. +message ExtensionSchemaDescriptor { + string namespace = 1; + string schema_id = 2; + uint32 schema_version = 3; + bytes schema_digest = 4; + bytes schema_json = 5; + repeated ExtensionSchemaField fields = 6; + bool optional = 7; +} + +message ExtensionNamespacePatch { + string namespace = 1; + oneof operation { + ExtensionPayload set = 2; + bool remove = 3; + } +} + +message ExtensionPatch { + uint64 expected_revision = 1; + repeated string typed_field_mask = 2; + repeated ExtensionNamespacePatch namespaces = 3; +} + +// Example hybrid resource: exact revisions/timestamps remain typed integers. +message RuntimeArgumentTemplate { + oneof value { + string literal = 1; + ContentPathArgument content_path = 2; + } +} + +// Inserts the path of the selected, approved content item as one argv element. +message ContentPathArgument {} + +message RuntimeRecord { + string id = 1; + string name = 2; + string version = 3; + string executable_handle = 4; + repeated string supported_formats = 5; + map extensions = 6; + uint64 revision = 7; + int64 observed_at = 8; + string platform = 9; + repeated RuntimeArgumentTemplate argument_template = 10; + DataProvenance provenance = 11; +} + // Epochs and operation ids are issued by the host; clients cannot widen them. message ServiceContext { string session_id = 1; @@ -78,6 +954,8 @@ message ServiceContext { string operation_id = 4; uint64 account_epoch = 5; uint64 profile_epoch = 6; + SessionKind session_kind = 7; + optional TargetGameContext target_game = 8; } enum ProviderOperation { @@ -98,6 +976,12 @@ enum ProviderOperation { PROVIDER_OPERATION_SETTINGS_SUBMIT = 14; PROVIDER_OPERATION_SETTINGS_CANCEL = 15; PROVIDER_OPERATION_READ_ACHIEVEMENTS = 16; + // API 1.6+ (third-party). + PROVIDER_OPERATION_CONFIGURATION_OPEN = 17; + PROVIDER_OPERATION_CONFIGURATION_FOCUS = 18; + PROVIDER_OPERATION_CONFIGURATION_CLOSE = 19; + PROVIDER_OPERATION_RUNTIME_SESSION_RESULT = 20; + PROVIDER_OPERATION_RUNTIME_SESSION_CONTEXT_RESULT = 21; } message ProviderCommand { @@ -106,6 +990,9 @@ message ProviderCommand { string target_operation_id = 3; optional SettingsRequest settings = 4; optional AchievementsRequest achievements = 5; + // API 1.6+ (third-party). + optional RuntimeSessionResult runtime_session_result = 6; + optional RuntimeSessionContextResult runtime_session_context_result = 7; } message ProviderContext { @@ -334,6 +1221,8 @@ message OperationResult { optional bool focused = 11; optional SettingsReply settings = 12; repeated AchievementOutcome achievements = 13; + // API 1.6+ (third-party). + optional ConfigurationResult configuration = 14; } // One bounded batch of provider game ids whose achievements are requested. @@ -370,6 +1259,14 @@ message AchievementOutcome { } } +message ConfigurationResult { + string session_id = 1; + string profile_id = 2; + string window_id = 3; + bool accepted = 4; + string failure = 5; +} + // Optional ui.settings, negotiated independently at API 1.3. This closed schema // carries non-secret configuration only; it grants no executable UI or storage. message SettingsContext { @@ -500,5 +1397,79 @@ message ProviderEvent { AccountStatus account_status = 3; CatalogChunk catalog_chunk = 4; OperationResult result = 5; + RuntimeSessionReport runtime_session = 6; + RuntimeSessionContextRequest runtime_session_context = 7; } } + +// A request for a host-authorized game context for an already-running runtime instance. +// These identifiers are proposals; the host resolves current library and runtime bindings and +// asks the user before issuing any reporting authority. +message RuntimeSessionContextRequest { + string correlation_id = 1; + string game_id = 2; + string installation_id = 3; + string runtime_id = 4; + string runtime_instance_id = 5; + string content_id = 6; +} + +message RuntimeSessionContextResult { + string correlation_id = 1; + RuntimeSessionOutcome outcome = 2; + // An opaque host-minted context token, present only on an approved request. + string runtime_context_id = 3; + string reason = 4; + DenialDetail denial = 5; +} + +message RuntimeSessionReport { + string correlation_id = 1; + string game_id = 2; + string installation_id = 3; + string content_id = 4; + string runtime_id = 5; + string runtime_instance_id = 6; + string reporter_session_id = 7; + uint64 sequence = 8; + // Unix time in seconds. The host accepts reports up to 30 seconds stale or 5 seconds ahead; + // session expiry is calculated from host monotonic receipt time. + int64 observed_at = 9; + RuntimeSessionTransition transition = 10; + string source_observation_id = 11; + // Empty only for the extension's initial host-selected context. Other contexts require + // the opaque id returned by RuntimeSessionContextResult. + string runtime_context_id = 12; +} + +enum RuntimeSessionTransition { + RUNTIME_SESSION_TRANSITION_UNSPECIFIED = 0; + RUNTIME_SESSION_TRANSITION_IDENTIFIED = 1; + RUNTIME_SESSION_TRANSITION_STARTED = 2; + RUNTIME_SESSION_TRANSITION_PAUSED = 3; + RUNTIME_SESSION_TRANSITION_RESUMED = 4; + RUNTIME_SESSION_TRANSITION_CONTENT_CHANGED = 5; + RUNTIME_SESSION_TRANSITION_ENDED = 6; + RUNTIME_SESSION_TRANSITION_IDENTIFICATION_LOST = 7; +} + +enum RuntimeSessionOutcome { + RUNTIME_SESSION_OUTCOME_UNSPECIFIED = 0; + RUNTIME_SESSION_OUTCOME_ACCEPTED = 1; + RUNTIME_SESSION_OUTCOME_DUPLICATE = 2; + RUNTIME_SESSION_OUTCOME_REJECTED_INVALID = 3; + RUNTIME_SESSION_OUTCOME_REJECTED_UNAUTHORIZED = 4; + RUNTIME_SESSION_OUTCOME_REJECTED_STALE = 5; + RUNTIME_SESSION_OUTCOME_REJECTED_CONFLICT = 6; + RUNTIME_SESSION_OUTCOME_REJECTED_UNAVAILABLE = 7; +} + +message RuntimeSessionResult { + string correlation_id = 1; + RuntimeSessionOutcome outcome = 2; + string host_session_id = 3; + uint64 accepted_sequence = 4; + int64 accepted_at = 5; + string reason = 6; + DenialDetail denial = 7; +} diff --git a/crates/plugin-protocol/src/capability.rs b/crates/plugin-protocol/src/capability.rs index 84308d6ea..c5daa25d1 100644 --- a/crates/plugin-protocol/src/capability.rs +++ b/crates/plugin-protocol/src/capability.rs @@ -21,6 +21,178 @@ pub const ACHIEVEMENTS_API_MINOR: u32 = 4; /// cannot silently gain configuration authority when the protocol is updated. pub const SETTINGS: &str = "ui.settings"; pub const SETTINGS_API_MINOR: u32 = 3; +pub const CONFIGURE: &str = "ui.configure"; +pub const LIBRARY_READ: &str = "library.read"; +pub const LIBRARY_READ_ALL: &str = "library.read.all"; +pub const LIBRARY_METADATA_WRITE: &str = "library.metadata.write"; +pub const FAVORITES_READ: &str = "favorites.read"; +pub const FAVORITES_WRITE: &str = "favorites.write"; +pub const MATCHING_READ: &str = "matching.read"; +pub const MATCHING_WRITE: &str = "matching.write"; +pub const ARTWORK_READ: &str = "artwork.read"; +pub const ARTWORK_WRITE: &str = "artwork.write"; +pub const GAME_LAUNCH: &str = "game.launch"; +pub const GAME_CUSTOM_LAUNCH: &str = "game.custom_launch"; +pub const GAMES_INSTALL: &str = "games.install"; +pub const STORAGE_READ: &str = "storage.read"; +pub const STORAGE_WRITE: &str = "storage.write"; +pub const STORAGE_DELETE: &str = "storage.delete"; +pub const STORAGE_PERSIST: &str = "storage.persist"; +pub const FILES_READ: &str = "files.read"; +pub const FILES_WRITE: &str = "files.write"; +pub const FILES_DELETE: &str = "files.delete"; +pub const NETWORK_FETCH: &str = "network.fetch"; +pub const NOTIFICATIONS_PUBLISH: &str = "notifications.publish"; +pub const BACKUPS_READ: &str = "backups.read"; +pub const BACKUPS_CREATE: &str = "backups.create"; +pub const BACKUPS_RESTORE: &str = "backups.restore"; +pub const LIBRARY_ROOTS_READ: &str = "library.roots.read"; +pub const LIBRARY_ROOTS_CREATE: &str = "library.roots.create"; +pub const LIBRARY_ROOTS_UPDATE: &str = "library.roots.update"; +pub const LIBRARY_ROOTS_DELETE: &str = "library.roots.delete"; +pub const GAME_RUNTIME_READ: &str = "game.runtime.read"; +pub const GAME_RUNTIME_CREATE: &str = "game.runtime.create"; +pub const GAME_RUNTIME_UPDATE: &str = "game.runtime.update"; +pub const GAME_RUNTIME_DELETE: &str = "game.runtime.delete"; +pub const GAME_SAVES_READ: &str = "game.saves.read"; +pub const GAME_SAVES_CREATE: &str = "game.saves.create"; +pub const GAME_SAVES_UPDATE: &str = "game.saves.update"; +pub const GAME_SAVES_DELETE: &str = "game.saves.delete"; +pub const GAME_STORAGE_INSPECT: &str = "game.storage.inspect"; +pub const GAME_SAVES_INSPECT: &str = "game.saves.inspect"; +pub const STORAGE_DIAGNOSTICS_PUBLISH: &str = "storage.diagnostics.publish"; +pub const STORAGE_DIAGNOSTICS_READ: &str = "storage.diagnostics.read"; +pub const COMPUTER_HARDWARE_PUBLISH: &str = "computer.hardware.publish"; +pub const COMPUTER_HARDWARE_READ: &str = "computer.hardware.read"; +pub const GAME_PRESENCE_PUBLISH: &str = "game.presence.publish"; +pub const GAME_PRESENCE_READ: &str = "game.presence.read"; +pub const GAME_PERFORMANCE_PUBLISH: &str = "game.performance.publish"; +pub const GAME_PERFORMANCE_READ: &str = "game.performance.read"; +pub const GAME_SESSIONS_REPORT: &str = "game.sessions.report"; +pub const DATA_PUBLISH: &str = "data.publish"; +/// Common-data category read grants are optional and start denied for every plugin. +pub const COMMON_GAME_PATHS_READ: &str = "common.game_paths.read"; +pub const COMMON_GAME_PERFORMANCE_HISTORY_READ: &str = "common.game_performance_history.read"; +pub const COMMON_RUNTIME_CATALOG_READ: &str = "common.runtime_catalog.read"; +pub const COMMON_CONTENT_AVAILABILITY_READ: &str = "common.content_availability.read"; +pub const TOOLS_READ: &str = "tools.read"; +pub const TOOLS_APPLY: &str = "tools.apply"; +pub const TOOLS_REMOVE: &str = "tools.remove"; +pub const PORTS_READ: &str = "ports.read"; +pub const PORTS_INSTALL: &str = "ports.install"; +/// First minor of the third-party API. Minors 1–5 are the official provider baseline. +pub const THIRD_PARTY_API_MINOR: u32 = 6; + +/// Public API feature descriptors used by API 1.6 range negotiation. +pub const FEATURE_API_METADATA: &str = "api.metadata"; +pub const FEATURE_PERMISSION_WATCH: &str = "permissions.watch"; +pub const FEATURE_EXTENSION_SESSION: &str = "session.extension"; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)] +pub enum RangeNegotiationError { + #[error("no mutually supported API version")] + Version, + #[error("required feature is unavailable")] + RequiredFeature, + #[error("feature request is invalid")] + InvalidFeature, + #[error("session kind or target context is invalid")] + Session, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct FeatureSelection { + pub api_major: u32, + pub api_minor: u32, + pub features: Vec<(String, bool, u32)>, +} + +/// Select the highest overlap. An empty range denotes a legacy 1.x client +/// whose `api_major/api_minor` fields retain their original meaning. +pub fn negotiate_range( + legacy_major: u32, + legacy_minor: u32, + min_major: u32, + min_minor: u32, + max_major: u32, + max_minor: u32, + requested: &[(String, bool)], +) -> Result { + let legacy = min_major == 0 && min_minor == 0 && max_major == 0 && max_minor == 0; + let (lo_major, lo_minor, hi_major, hi_minor) = if legacy { + ( + legacy_major, + crate::MIN_API_MINOR, + legacy_major, + legacy_minor, + ) + } else { + (min_major, min_minor, max_major, max_minor) + }; + if lo_major > crate::API_MAJOR || hi_major < crate::API_MAJOR || lo_major > hi_major { + return Err(RangeNegotiationError::Version); + } + let selected = hi_minor.min(crate::API_MINOR); + let floor = if lo_major == crate::API_MAJOR { + lo_minor + } else { + 0 + }; + if selected < floor || selected < crate::MIN_API_MINOR { + return Err(RangeNegotiationError::Version); + } + let mut seen = std::collections::BTreeSet::new(); + let mut features = Vec::with_capacity(requested.len()); + for (id, required) in requested { + if id.is_empty() || !seen.insert(id) { + return Err(RangeNegotiationError::InvalidFeature); + } + let introduced = match id.as_str() { + FEATURE_API_METADATA + | FEATURE_PERMISSION_WATCH + | FEATURE_EXTENSION_SESSION + | CONFIGURE => THIRD_PARTY_API_MINOR, + SETTINGS => SETTINGS_API_MINOR, + ACHIEVEMENTS => ACHIEVEMENTS_API_MINOR, + _ => 0, + }; + let supported = introduced != 0 && introduced <= selected; + if *required && !supported { + return Err(RangeNegotiationError::RequiredFeature); + } + features.push((id.clone(), supported, introduced)); + } + Ok(FeatureSelection { + api_major: crate::API_MAJOR, + api_minor: selected, + features, + }) +} + +pub fn validate_session_scope(kind: u32, has_target: bool) -> Result<(), RangeNegotiationError> { + match kind { + 0 | 1 if !has_target => Ok(()), + 2 if has_target => Ok(()), + _ => Err(RangeNegotiationError::Session), + } +} + +pub fn validate_target( + target: &crate::proto::TargetGameContext, +) -> Result<(), RangeNegotiationError> { + let valid = |value: &str, max: usize| { + !value.trim().is_empty() && value.len() <= max && !value.chars().any(char::is_control) + }; + if valid(&target.game_id, 256) + && (target.installation_id.is_empty() || valid(&target.installation_id, 256)) + && (target.profile_id.is_empty() || valid(&target.profile_id, 256)) + && (target.revision.is_empty() || valid(&target.revision, 256)) + { + Ok(()) + } else { + Err(RangeNegotiationError::Session) + } +} pub const ALL: &[&str] = &[ CONTEXT, @@ -39,6 +211,136 @@ pub const ALL: &[&str] = &[ ACHIEVEMENTS, ]; +/// All identifiers understood by this API. Unlike [`ALL`], this list is not a +/// default grant set and must never be used to authorize an official plugin. +pub const KNOWN: &[&str] = &[ + CONTEXT, + DISCOVERY, + CATALOG, + ACCOUNT_READ, + ACCOUNT_PUBLISH, + LOGIN, + COOKIES, + PAGE, + SECRET_READ, + SECRET_WRITE, + SECRET_DELETE, + COUNTER, + ACTIONS, + ACHIEVEMENTS, + SETTINGS, + CONFIGURE, + LIBRARY_READ, + LIBRARY_READ_ALL, + LIBRARY_METADATA_WRITE, + FAVORITES_READ, + FAVORITES_WRITE, + MATCHING_READ, + MATCHING_WRITE, + ARTWORK_READ, + ARTWORK_WRITE, + GAME_LAUNCH, + GAME_CUSTOM_LAUNCH, + GAMES_INSTALL, + STORAGE_READ, + STORAGE_WRITE, + STORAGE_DELETE, + STORAGE_PERSIST, + FILES_READ, + FILES_WRITE, + FILES_DELETE, + NETWORK_FETCH, + NOTIFICATIONS_PUBLISH, + BACKUPS_READ, + BACKUPS_CREATE, + BACKUPS_RESTORE, + LIBRARY_ROOTS_READ, + LIBRARY_ROOTS_CREATE, + LIBRARY_ROOTS_UPDATE, + LIBRARY_ROOTS_DELETE, + GAME_RUNTIME_READ, + GAME_RUNTIME_CREATE, + GAME_RUNTIME_UPDATE, + GAME_RUNTIME_DELETE, + GAME_SAVES_READ, + GAME_SAVES_CREATE, + GAME_SAVES_UPDATE, + GAME_SAVES_DELETE, + GAME_STORAGE_INSPECT, + GAME_SAVES_INSPECT, + STORAGE_DIAGNOSTICS_PUBLISH, + STORAGE_DIAGNOSTICS_READ, + COMPUTER_HARDWARE_PUBLISH, + COMPUTER_HARDWARE_READ, + GAME_PRESENCE_PUBLISH, + GAME_PRESENCE_READ, + GAME_PERFORMANCE_PUBLISH, + GAME_PERFORMANCE_READ, + GAME_SESSIONS_REPORT, + DATA_PUBLISH, + COMMON_GAME_PATHS_READ, + COMMON_GAME_PERFORMANCE_HISTORY_READ, + COMMON_RUNTIME_CATALOG_READ, + COMMON_CONTENT_AVAILABILITY_READ, + TOOLS_READ, + TOOLS_APPLY, + TOOLS_REMOVE, + PORTS_READ, + PORTS_INSTALL, +]; +pub const THIRD_PARTY_CAPABILITIES: &[&str] = &[ + CONFIGURE, + LIBRARY_READ, + LIBRARY_READ_ALL, + LIBRARY_METADATA_WRITE, + FAVORITES_READ, + FAVORITES_WRITE, + MATCHING_READ, + MATCHING_WRITE, + ARTWORK_READ, + ARTWORK_WRITE, + GAME_LAUNCH, + GAME_CUSTOM_LAUNCH, + GAMES_INSTALL, + STORAGE_READ, + STORAGE_WRITE, + STORAGE_DELETE, + STORAGE_PERSIST, + FILES_READ, + FILES_WRITE, + FILES_DELETE, + NETWORK_FETCH, + NOTIFICATIONS_PUBLISH, + BACKUPS_READ, + BACKUPS_CREATE, + BACKUPS_RESTORE, + LIBRARY_ROOTS_READ, + LIBRARY_ROOTS_DELETE, + GAME_RUNTIME_READ, + GAME_RUNTIME_DELETE, + GAME_STORAGE_INSPECT, + GAME_SAVES_INSPECT, + STORAGE_DIAGNOSTICS_PUBLISH, + STORAGE_DIAGNOSTICS_READ, + COMPUTER_HARDWARE_PUBLISH, + COMPUTER_HARDWARE_READ, + GAME_PRESENCE_PUBLISH, + GAME_PRESENCE_READ, + GAME_PERFORMANCE_PUBLISH, + GAME_PERFORMANCE_READ, + GAME_SESSIONS_REPORT, + DATA_PUBLISH, + COMMON_GAME_PATHS_READ, + COMMON_GAME_PERFORMANCE_HISTORY_READ, + COMMON_RUNTIME_CATALOG_READ, + COMMON_CONTENT_AVAILABILITY_READ, + TOOLS_READ, + TOOLS_APPLY, + TOOLS_REMOVE, + PORTS_READ, + PORTS_INSTALL, +]; + #[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)] pub enum NegotiationError { #[error("incompatible Plugin API")] @@ -60,13 +362,13 @@ pub fn negotiate( if major != crate::API_MAJOR || minor < crate::MIN_API_MINOR { return Err(NegotiationError::Version); } - if requested.is_empty() || requested.len() > ALL.len() + 1 { + if requested.is_empty() || requested.len() > KNOWN.len() { return Err(NegotiationError::Capability); } let mut seen = std::collections::BTreeSet::new(); let selected = minor.min(crate::API_MINOR); for name in requested { - if (!ALL.contains(&name.as_str()) && name != SETTINGS) + if !KNOWN.contains(&name.as_str()) || !authorized.contains(&name.as_str()) || !seen.insert(name) { @@ -81,6 +383,12 @@ pub fn negotiate( if name == SETTINGS && selected < SETTINGS_API_MINOR { return Err(NegotiationError::Unsupported); } + if name == CONFIGURE && selected < THIRD_PARTY_API_MINOR { + return Err(NegotiationError::Unsupported); + } + if THIRD_PARTY_CAPABILITIES.contains(&name.as_str()) && selected < THIRD_PARTY_API_MINOR { + return Err(NegotiationError::Unsupported); + } } Ok(selected) } diff --git a/crates/plugin-protocol/src/common_data.rs b/crates/plugin-protocol/src/common_data.rs new file mode 100644 index 000000000..a2e84a4e9 --- /dev/null +++ b/crates/plugin-protocol/src/common_data.rs @@ -0,0 +1,150 @@ +//! Typed per-query selection of published data projections. + +use std::collections::BTreeSet; + +use crate::proto::{CommonDataCategory, CommonDataSelector}; + +/// The part of a query selector that the host has independently authorized. +/// Empty selections intentionally mean that no shared records are visible. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct AuthorizedSelection { + categories: BTreeSet, + record_ids: BTreeSet, +} + +impl AuthorizedSelection { + pub fn includes_category(&self, category: CommonDataCategory) -> bool { + self.categories.contains(&category) + } + + pub fn includes_record(&self, record_id: &str) -> bool { + self.record_ids.contains(record_id) + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)] +pub enum SelectorError { + #[error("common-data selector contains an unspecified category")] + Unspecified, + #[error("common-data selector contains an unsupported category")] + Unsupported, + #[error("common-data selector contains a duplicate category")] + Duplicate, + #[error("common-data selector contains an empty selected record id")] + EmptyRecordId, + #[error("common-data selector contains a duplicate selected record id")] + DuplicateRecordId, + #[error("common-data selector exceeds the selected-record limit")] + TooManyRecordIds, +} + +/// Validate and decode category selectors. No selector and an empty selector +/// both mean private/owner-visible data only. Authorization is always checked +/// by the host against the caller's current grant for every decoded category. +pub fn categories( + selector: Option<&CommonDataSelector>, +) -> Result, SelectorError> { + let Some(selector) = selector else { + return Ok(Vec::new()); + }; + + let mut categories = Vec::with_capacity(selector.categories.len()); + for raw in &selector.categories { + let category = + CommonDataCategory::try_from(*raw).map_err(|_| SelectorError::Unsupported)?; + if category == CommonDataCategory::Unspecified { + return Err(SelectorError::Unspecified); + } + if categories.contains(&category) { + return Err(SelectorError::Duplicate); + } + categories.push(category); + } + Ok(categories) +} + +/// Validate selected published record ids. These ids are only query selectors; +/// the host must independently check a user grant for every returned record. +pub fn selected_record_ids( + selector: Option<&CommonDataSelector>, +) -> Result, SelectorError> { + let Some(selector) = selector else { + return Ok(Vec::new()); + }; + if selector.selected_record_ids.len() > 1000 { + return Err(SelectorError::TooManyRecordIds); + } + let mut ids = Vec::with_capacity(selector.selected_record_ids.len()); + for id in &selector.selected_record_ids { + if id.trim().is_empty() { + return Err(SelectorError::EmptyRecordId); + } + if ids.contains(&id.as_str()) { + return Err(SelectorError::DuplicateRecordId); + } + ids.push(id.as_str()); + } + Ok(ids) +} + +/// Resolves per-query selection against two separate current grants. Category +/// grants never authorize a selected record, and record grants never opt a +/// whole category into the query. Missing selectors therefore stay private. +pub fn authorize_selector( + selector: Option<&CommonDataSelector>, + granted_categories: &BTreeSet, + granted_record_ids: &BTreeSet, +) -> Result { + let categories = categories(selector)? + .into_iter() + .filter(|category| granted_categories.contains(category)) + .collect(); + let record_ids = selected_record_ids(selector)? + .into_iter() + .filter(|record_id| granted_record_ids.contains(*record_id)) + .map(str::to_owned) + .collect(); + Ok(AuthorizedSelection { + categories, + record_ids, + }) +} + +/// Resolves a selector from the permission identifiers in an authenticated +/// session. Selected record grants remain a separate input and are never +/// inferred from a category permission. +pub fn authorize_grant_selector( + selector: Option<&CommonDataSelector>, + permission_grants: &BTreeSet, + granted_record_ids: &BTreeSet, +) -> Result { + let granted_categories = [ + CommonDataCategory::GamePaths, + CommonDataCategory::GamePerformanceHistory, + CommonDataCategory::RuntimeCatalog, + CommonDataCategory::ContentAvailability, + CommonDataCategory::LibraryRoots, + CommonDataCategory::SaveProfiles, + ] + .into_iter() + .filter(|category| permission(*category).is_some_and(|id| permission_grants.contains(id))) + .collect(); + authorize_selector(selector, &granted_categories, granted_record_ids) +} + +/// Permission required by each stable common-data category. +pub fn permission(category: CommonDataCategory) -> Option<&'static str> { + match category { + CommonDataCategory::GamePaths => Some(crate::capability::COMMON_GAME_PATHS_READ), + CommonDataCategory::GamePerformanceHistory => { + Some(crate::capability::COMMON_GAME_PERFORMANCE_HISTORY_READ) + } + CommonDataCategory::RuntimeCatalog => Some(crate::capability::COMMON_RUNTIME_CATALOG_READ), + CommonDataCategory::ContentAvailability => { + Some(crate::capability::COMMON_CONTENT_AVAILABILITY_READ) + } + CommonDataCategory::LibraryRoots => Some("library.roots.read"), + CommonDataCategory::SaveProfiles => Some("game.saves.read"), + CommonDataCategory::Unspecified => None, + } +} diff --git a/crates/plugin-protocol/src/extensions.rs b/crates/plugin-protocol/src/extensions.rs new file mode 100644 index 000000000..0c6bd4332 --- /dev/null +++ b/crates/plugin-protocol/src/extensions.rs @@ -0,0 +1,772 @@ +//! Bounded, declarative resource metadata extensions. +//! +//! Struct values are annotations only. The host never interprets them as +//! identity, authorization, filesystem paths, or executable commands. + +use std::collections::{BTreeMap, BTreeSet, HashMap}; + +use prost::Message; +use prost_types::{Value, value::Kind}; + +use crate::{WireError, proto}; + +pub const MAX_NAMESPACES: usize = 32; +pub const MAX_EXTENSION_BYTES: usize = 64 * 1024; +pub const MAX_SCHEMA_BYTES: usize = 64 * 1024; +pub const MAX_SCHEMA_CATALOG_BYTES: usize = 256 * 1024; +pub const MAX_DEPTH: usize = 8; +pub const MAX_OBJECT_KEYS: usize = 256; +pub const MAX_SCHEMA_FIELDS: usize = 256; + +const PROTECTED_ROOT_KEYS: &[&str] = &[ + "id", + "revision", + "source", + "provenance", + "owner", + "creator", + "permissions", + "scope", + "executable", + "executable_handle", + "argv", + "cwd", + "path", + "launch_target", + "operation", + "command", +]; + +#[derive(Default)] +struct ProjectionNode { + include_value: bool, + children: BTreeMap, +} + +/// Returns a copy containing only the requested declared field paths. +/// +/// A selected path includes its entire value. Callers must derive `paths` from +/// the recipient's current field grants and the dataset's validated schema; +/// this helper only performs structural projection and grants no authority. +pub fn project_struct_paths( + value: &prost_types::Struct, + paths: &BTreeSet, +) -> Result { + if paths.len() > MAX_SCHEMA_FIELDS { + return Err(WireError); + } + if paths.is_empty() { + return Ok(prost_types::Struct::default()); + } + let mut root = ProjectionNode::default(); + for path in paths { + if !valid_field_path(path) { + return Err(WireError); + } + let mut node = &mut root; + for part in path.split('.') { + node = node.children.entry(part.to_owned()).or_default(); + } + node.include_value = true; + } + let projected = project_value( + &prost_types::Value { + kind: Some(Kind::StructValue(value.clone())), + }, + &root, + )? + .ok_or(WireError)?; + let Some(Kind::StructValue(projected)) = projected.kind else { + return Err(WireError); + }; + if projected.encoded_len() > MAX_EXTENSION_BYTES { + return Err(WireError); + } + let mut key_count = 0; + validate_struct(&projected, 0, &mut key_count)?; + Ok(projected) +} + +/// Validates a payload against its declared schema and projects only fields +/// that are both declared and present in the caller's current field grant. +pub fn project_payload_fields( + payload: &proto::ExtensionPayload, + descriptor: &proto::ExtensionSchemaDescriptor, + granted_paths: &BTreeSet, +) -> Result { + validate_payload_for_schema(payload, descriptor)?; + let declared_paths: BTreeSet<_> = descriptor + .fields + .iter() + .map(|field| field.path.as_str()) + .collect(); + if granted_paths.iter().any(|path| !valid_field_path(path)) { + return Err(WireError); + } + let selected_paths = granted_paths + .iter() + .filter(|path| declared_paths.contains(path.as_str())) + .cloned() + .collect(); + let data = project_struct_paths(payload.data.as_ref().ok_or(WireError)?, &selected_paths)?; + let mut projected = payload.clone(); + projected.data = Some(data); + Ok(projected) +} + +fn project_value( + value: &prost_types::Value, + node: &ProjectionNode, +) -> Result, WireError> { + if node.include_value { + return Ok(Some(value.clone())); + } + let Some(Kind::StructValue(object)) = value.kind.as_ref() else { + return Err(WireError); + }; + let mut projected = prost_types::Struct::default(); + for (key, child_node) in &node.children { + let Some(child) = object.fields.get(key) else { + continue; + }; + if let Some(child) = project_value(child, child_node)? { + projected.fields.insert(key.clone(), child); + } + } + Ok(Some(prost_types::Value { + kind: Some(Kind::StructValue(projected)), + })) +} + +#[derive(Clone, Debug, Default, PartialEq)] +pub struct ExtensionSet { + namespaces: BTreeMap, +} + +impl ExtensionSet { + pub fn from_wire(values: HashMap) -> Result { + let namespaces = values.into_iter().collect(); + validate_extension_set(&namespaces)?; + Ok(Self { namespaces }) + } + + pub fn as_map(&self) -> &BTreeMap { + &self.namespaces + } + + pub fn into_wire(self) -> HashMap { + self.namespaces.into_iter().collect() + } + + /// Applies only named namespace operations. Namespaces absent from the + /// patch—including namespaces the caller does not understand—are retained. + pub fn apply_patch( + &mut self, + patch: &proto::ExtensionPatch, + current_revision: u64, + ) -> Result { + validate_patch(patch)?; + if patch.expected_revision != current_revision { + return Err(WireError); + } + let next_revision = current_revision.checked_add(1).ok_or(WireError)?; + let mut candidate = self.namespaces.clone(); + let mut seen = BTreeSet::new(); + for change in &patch.namespaces { + validate_namespace(&change.namespace)?; + if !seen.insert(&change.namespace) { + return Err(WireError); + } + match change.operation.as_ref().ok_or(WireError)? { + proto::extension_namespace_patch::Operation::Set(payload) => { + validate_payload(payload)?; + if !payload + .schema_id + .starts_with(&format!("{}.", change.namespace)) + && payload.schema_id != change.namespace + { + return Err(WireError); + } + candidate.insert(change.namespace.clone(), payload.clone()); + } + proto::extension_namespace_patch::Operation::Remove(true) => { + candidate.remove(&change.namespace); + } + proto::extension_namespace_patch::Operation::Remove(false) => { + return Err(WireError); + } + } + } + validate_extension_set(&candidate)?; + self.namespaces = candidate; + Ok(next_revision) + } +} + +/// Applies a revision-checked runtime patch while preserving host-owned fields +/// and extension namespaces omitted by an older client. The caller must check +/// owner authorization before calling this function. +pub fn apply_runtime_patch( + current: &proto::RuntimeRecord, + proposed: &proto::RuntimeRecord, + patch: &proto::ExtensionPatch, +) -> Result { + validate_patch(patch)?; + if current.revision != patch.expected_revision || proposed.id != current.id { + return Err(WireError); + } + let mut updated = current.clone(); + for field in &patch.typed_field_mask { + match field.as_str() { + "name" => updated.name.clone_from(&proposed.name), + "version" => updated.version.clone_from(&proposed.version), + "supported_formats" => updated + .supported_formats + .clone_from(&proposed.supported_formats), + _ => return Err(WireError), + } + } + let mut extensions = ExtensionSet::from_wire(current.extensions.clone())?; + let revision = extensions.apply_patch(patch, current.revision)?; + updated.extensions = extensions.into_wire(); + updated.revision = revision; + Ok(updated) +} + +pub fn validate_patch(patch: &proto::ExtensionPatch) -> Result<(), WireError> { + if patch.typed_field_mask.len() > MAX_SCHEMA_FIELDS { + return Err(WireError); + } + let mut fields = BTreeSet::new(); + for path in &patch.typed_field_mask { + if !valid_field_path(path) || !fields.insert(path) { + return Err(WireError); + } + } + let mut namespaces = BTreeSet::new(); + if patch.namespaces.len() > MAX_NAMESPACES { + return Err(WireError); + } + for change in &patch.namespaces { + validate_namespace(&change.namespace)?; + if !namespaces.insert(&change.namespace) || change.operation.is_none() { + return Err(WireError); + } + if let Some(proto::extension_namespace_patch::Operation::Set(value)) = &change.operation { + validate_payload(value)?; + } + if matches!( + change.operation, + Some(proto::extension_namespace_patch::Operation::Remove(false)) + ) { + return Err(WireError); + } + } + Ok(()) +} + +pub fn validate_schema_descriptor( + descriptor: &proto::ExtensionSchemaDescriptor, +) -> Result<(), WireError> { + validate_namespace(&descriptor.namespace)?; + if !valid_schema_id(&descriptor.schema_id) + || !(descriptor.schema_id == descriptor.namespace + || descriptor + .schema_id + .strip_prefix(&descriptor.namespace) + .is_some_and(|suffix| suffix.starts_with('.'))) + || descriptor.schema_version == 0 + || descriptor.schema_digest.len() != 32 + || descriptor.schema_json.is_empty() + || descriptor.schema_json.len() > MAX_SCHEMA_BYTES + || descriptor.fields.len() > MAX_SCHEMA_FIELDS + || descriptor.encoded_len() > MAX_SCHEMA_BYTES + 16 * 1024 + { + return Err(WireError); + } + let schema: serde_json::Value = + serde_json::from_slice(&descriptor.schema_json).map_err(|_| WireError)?; + use sha2::Digest; + if sha2::Sha256::digest(&descriptor.schema_json).as_slice() != descriptor.schema_digest { + return Err(WireError); + } + let mut key_count = 0; + validate_json_value(&schema, 0, &mut key_count)?; + if !schema.is_object() + || schema.get("type").and_then(serde_json::Value::as_str) != Some("object") + || !schema_subset_valid(&schema) + || contains_remote_ref(&schema) + || has_protected_schema_properties(&schema) + { + return Err(WireError); + } + let mut paths = BTreeSet::new(); + for field in &descriptor.fields { + if !valid_field_path(&field.path) + || !paths.insert(&field.path) + || proto::ExtensionFieldClassification::try_from(field.classification).is_err() + || field.classification == proto::ExtensionFieldClassification::Unspecified as i32 + { + return Err(WireError); + } + let mut node = &schema; + for part in field.path.split('.') { + node = node + .get("properties") + .and_then(serde_json::Value::as_object) + .and_then(|properties| properties.get(part)) + .ok_or(WireError)?; + } + } + Ok(()) +} + +pub fn validate_payload(payload: &proto::ExtensionPayload) -> Result<(), WireError> { + let mut key_count = 0; + validate_payload_with_key_count(payload, &mut key_count) +} + +fn validate_payload_with_key_count( + payload: &proto::ExtensionPayload, + key_count: &mut usize, +) -> Result<(), WireError> { + if !valid_schema_id(&payload.schema_id) + || payload.schema_version == 0 + || payload.schema_digest.len() != 32 + || payload.data.is_none() + || payload.encoded_len() > MAX_EXTENSION_BYTES + { + return Err(WireError); + } + validate_struct(payload.data.as_ref().ok_or(WireError)?, 0, key_count)?; + Ok(()) +} + +fn validate_extension_set( + namespaces: &BTreeMap, +) -> Result<(), WireError> { + if namespaces.len() > MAX_NAMESPACES + || namespaces.values().map(Message::encoded_len).sum::() > MAX_EXTENSION_BYTES + { + return Err(WireError); + } + let mut key_count = 0; + for (namespace, payload) in namespaces { + validate_namespace(namespace)?; + validate_payload_with_key_count(payload, &mut key_count)?; + if !payload.schema_id.starts_with(&format!("{namespace}.")) + && payload.schema_id != *namespace + { + return Err(WireError); + } + } + Ok(()) +} + +pub fn validate_payload_for_schema( + payload: &proto::ExtensionPayload, + descriptor: &proto::ExtensionSchemaDescriptor, +) -> Result<(), WireError> { + validate_schema_descriptor(descriptor)?; + validate_payload(payload)?; + if payload.schema_id != descriptor.schema_id + || payload.schema_version != descriptor.schema_version + || payload.schema_digest != descriptor.schema_digest + { + return Err(WireError); + } + let schema: serde_json::Value = + serde_json::from_slice(&descriptor.schema_json).map_err(|_| WireError)?; + validate_struct_shape(payload.data.as_ref().ok_or(WireError)?, &schema)?; + Ok(()) +} + +fn validate_struct_shape( + value: &prost_types::Struct, + schema: &serde_json::Value, +) -> Result<(), WireError> { + use serde_json::Value as J; + + let object = schema.as_object().ok_or(WireError)?; + if let Some(expected) = object.get("type") + && !schema_type_matches(expected) + { + return Err(WireError); + } + let properties = object.get("properties").and_then(J::as_object); + if let Some(properties) = properties { + if object.get("additionalProperties") == Some(&J::Bool(false)) + && value.fields.keys().any(|key| !properties.contains_key(key)) + { + return Err(WireError); + } + for (key, child) in &value.fields { + if let Some(child_schema) = properties.get(key) { + validate_value_shape(child, child_schema)?; + } + } + } + if let Some(required) = object.get("required").and_then(J::as_array) + && required + .iter() + .filter_map(J::as_str) + .any(|key| !value.fields.contains_key(key)) + { + return Err(WireError); + } + Ok(()) +} + +fn validate_value_shape( + value: &prost_types::Value, + schema: &serde_json::Value, +) -> Result<(), WireError> { + use prost_types::value::Kind; + use serde_json::Value as J; + + let object = schema.as_object().ok_or(WireError)?; + if let Some(expected) = object.get("type") + && !value + .kind + .as_ref() + .is_some_and(|kind| kind_matches_type(kind, expected)) + { + return Err(WireError); + } + match value.kind.as_ref().ok_or(WireError)? { + Kind::StructValue(value) => validate_struct_shape(value, schema), + Kind::ListValue(list) => { + if let Some(items) = object.get("items") { + for item in &list.values { + validate_value_shape(item, items)?; + } + } + if let Some(minimum) = object.get("minItems").and_then(J::as_u64) + && list.values.len() < minimum as usize + { + return Err(WireError); + } + if let Some(maximum) = object.get("maxItems").and_then(J::as_u64) + && list.values.len() > maximum as usize + { + return Err(WireError); + } + Ok(()) + } + Kind::StringValue(text) => { + if object + .get("minLength") + .and_then(J::as_u64) + .is_some_and(|min| text.chars().count() < min as usize) + || object + .get("maxLength") + .and_then(J::as_u64) + .is_some_and(|max| text.chars().count() > max as usize) + { + Err(WireError) + } else { + Ok(()) + } + } + Kind::NumberValue(number) => { + if object + .get("minimum") + .and_then(J::as_f64) + .is_some_and(|min| *number < min) + || object + .get("maximum") + .and_then(J::as_f64) + .is_some_and(|max| *number > max) + { + Err(WireError) + } else { + Ok(()) + } + } + _ => Ok(()), + } +} + +fn schema_type_matches(expected: &serde_json::Value) -> bool { + expected.as_str() == Some("object") + || expected + .as_array() + .is_some_and(|types| types.iter().any(|name| name.as_str() == Some("object"))) +} + +fn kind_matches_type(kind: &Kind, expected: &serde_json::Value) -> bool { + let matches = |name: &str| match (kind, name) { + (Kind::StructValue(_), "object") | (Kind::ListValue(_), "array") => true, + (Kind::StringValue(_), "string") | (Kind::BoolValue(_), "boolean") => true, + (Kind::NumberValue(_), "number") => true, + (Kind::NumberValue(number), "integer") => number.fract() == 0.0, + (Kind::NullValue(_), "null") => true, + _ => false, + }; + expected.as_str().is_some_and(matches) + || expected.as_array().is_some_and(|types| { + types + .iter() + .filter_map(serde_json::Value::as_str) + .any(matches) + }) +} + +/// A package may declare no more than one schema owner for each namespace. +pub fn validate_schema_catalog( + descriptors: &[proto::ExtensionSchemaDescriptor], +) -> Result<(), WireError> { + if descriptors.len() > MAX_NAMESPACES { + return Err(WireError); + } + let mut namespaces = BTreeSet::new(); + let mut ids = BTreeSet::new(); + let mut total_bytes = 0usize; + for descriptor in descriptors { + validate_schema_descriptor(descriptor)?; + total_bytes = total_bytes.saturating_add(descriptor.encoded_len()); + if !namespaces.insert(&descriptor.namespace) + || !ids.insert((&descriptor.schema_id, descriptor.schema_version)) + || total_bytes > MAX_SCHEMA_CATALOG_BYTES + { + return Err(WireError); + } + } + Ok(()) +} + +fn validate_namespace(namespace: &str) -> Result<(), WireError> { + if !valid_schema_id(namespace) + || namespace.starts_with("org.gamenode") + || namespace.split('.').count() < 2 + { + return Err(WireError); + } + Ok(()) +} + +fn valid_schema_id(value: &str) -> bool { + !value.is_empty() + && value.len() <= 256 + && value.split('.').count() >= 2 + && value.split('.').all(|part| { + !part.is_empty() + && part.len() <= 63 + && part + .bytes() + .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-') + && part.as_bytes()[0].is_ascii_alphanumeric() + && part.as_bytes()[part.len() - 1].is_ascii_alphanumeric() + }) +} + +fn valid_field_path(value: &str) -> bool { + !value.is_empty() + && value.len() <= 256 + && value.split('.').all(|part| { + !part.is_empty() + && part.len() <= 64 + && part + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-') + }) +} + +fn validate_struct( + value: &prost_types::Struct, + depth: usize, + key_count: &mut usize, +) -> Result<(), WireError> { + if depth > MAX_DEPTH { + return Err(WireError); + } + for (key, child) in &value.fields { + *key_count += 1; + if *key_count > MAX_OBJECT_KEYS || key.is_empty() || key.len() > 256 { + return Err(WireError); + } + if depth == 0 && PROTECTED_ROOT_KEYS.contains(&key.as_str()) { + return Err(WireError); + } + validate_value(child, depth + 1, key_count)?; + } + Ok(()) +} + +fn validate_value(value: &Value, depth: usize, key_count: &mut usize) -> Result<(), WireError> { + if depth > MAX_DEPTH { + return Err(WireError); + } + match value.kind.as_ref().ok_or(WireError)? { + Kind::NumberValue(number) if !number.is_finite() => Err(WireError), + Kind::StructValue(value) => validate_struct(value, depth, key_count), + Kind::ListValue(list) => { + for value in &list.values { + validate_value(value, depth + 1, key_count)?; + } + Ok(()) + } + _ => Ok(()), + } +} + +fn validate_json_value( + value: &serde_json::Value, + depth: usize, + key_count: &mut usize, +) -> Result<(), WireError> { + if depth > MAX_DEPTH { + return Err(WireError); + } + match value { + serde_json::Value::Object(fields) => { + for (key, child) in fields { + *key_count += 1; + if *key_count > MAX_OBJECT_KEYS || key.is_empty() || key.len() > 256 { + return Err(WireError); + } + validate_json_value(child, depth + 1, key_count)?; + } + Ok(()) + } + serde_json::Value::Array(values) => { + for child in values { + validate_json_value(child, depth + 1, key_count)?; + } + Ok(()) + } + _ => Ok(()), + } +} + +fn contains_remote_ref(value: &serde_json::Value) -> bool { + match value { + serde_json::Value::Object(fields) => fields.iter().any(|(key, child)| { + key == "$ref" + || key == "$dynamicRef" + || key == "$recursiveRef" + || contains_remote_ref(child) + }), + serde_json::Value::Array(values) => values.iter().any(contains_remote_ref), + _ => false, + } +} + +fn schema_subset_valid(schema: &serde_json::Value) -> bool { + use serde_json::Value as J; + let Some(object) = schema.as_object() else { + return false; + }; + for (key, value) in object { + match key.as_str() { + "$schema" => { + if value.as_str() != Some("https://json-schema.org/draft/2020-12/schema") { + return false; + } + } + "title" | "description" => { + let maximum = if key == "title" { 128 } else { 1024 }; + if value.as_str().is_none_or(|text| text.len() > maximum) { + return false; + } + } + "x-gamenode-classification" => { + if !matches!(value.as_str(), Some("public" | "sensitive" | "private")) { + return false; + } + } + "type" => { + let valid_type = |name: &str| { + matches!( + name, + "object" | "array" | "string" | "number" | "integer" | "boolean" | "null" + ) + }; + let valid = value.as_str().is_some_and(valid_type) + || value.as_array().is_some_and(|types| { + !types.is_empty() + && types.iter().all(|v| v.as_str().is_some_and(valid_type)) + }); + if !valid { + return false; + } + } + "properties" => { + let Some(properties) = value.as_object() else { + return false; + }; + if properties.len() > MAX_OBJECT_KEYS + || properties.values().any(|child| !schema_subset_valid(child)) + { + return false; + } + } + "items" => { + if !schema_subset_valid(value) { + return false; + } + } + "required" => { + let Some(required) = value.as_array() else { + return false; + }; + if !required + .iter() + .all(|v| v.as_str().is_some_and(|s| !s.is_empty() && s.len() <= 256)) + { + return false; + } + if let Some(properties) = object.get("properties").and_then(J::as_object) + && required + .iter() + .filter_map(J::as_str) + .any(|name| !properties.contains_key(name)) + { + return false; + } + } + "enum" => { + if !value + .as_array() + .is_some_and(|values| values.iter().all(|v| !v.is_object() && !v.is_array())) + { + return false; + } + } + "additionalProperties" => { + if !value.is_boolean() { + return false; + } + } + "minimum" | "maximum" => { + if !value.as_f64().is_some_and(f64::is_finite) { + return false; + } + } + "minLength" | "maxLength" | "minItems" | "maxItems" => { + if !value + .as_u64() + .is_some_and(|v| v <= MAX_EXTENSION_BYTES as u64) + { + return false; + } + } + _ => return false, + } + } + // Keep this function intentionally closed; adding a JSON Schema keyword is + // a protocol change with corresponding bounds and tests. + !matches!(schema, J::Null) +} + +fn has_protected_schema_properties(value: &serde_json::Value) -> bool { + let Some(properties) = value + .get("properties") + .and_then(serde_json::Value::as_object) + else { + return false; + }; + properties + .keys() + .any(|key| PROTECTED_ROOT_KEYS.contains(&key.as_str())) +} diff --git a/crates/plugin-protocol/src/lib.rs b/crates/plugin-protocol/src/lib.rs index 738669690..acf7cafc7 100644 --- a/crates/plugin-protocol/src/lib.rs +++ b/crates/plugin-protocol/src/lib.rs @@ -6,16 +6,22 @@ pub mod proto { tonic::include_proto!("gamenode.plugin.v1"); } +pub use prost; +pub use prost_types; pub mod capability; pub mod catalog; +pub mod common_data; +pub mod extensions; pub mod login; pub mod models; pub mod settings; mod wire; pub const API_MAJOR: u32 = 1; -pub const API_MINOR: u32 = 5; +pub const API_MINOR: u32 = 6; +/// Last minor understood by the pre-1.6 single-minor handshake used by official providers. +pub const LEGACY_API_MINOR: u32 = 5; pub const MIN_API_MINOR: u32 = 1; pub mod achievements; @@ -47,3 +53,35 @@ redacted_debug!( proto::SettingsValue, proto::settings_value::Value, ); + +#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)] +pub enum StatusKind { + #[error("permission denied")] + Denied, + #[error("authentication failed")] + Unauthenticated, + #[error("operation is stale")] + Stale, + #[error("feature is unsupported")] + Unsupported, + #[error("request is invalid")] + Invalid, + #[error("service is unavailable")] + Unavailable, + #[error("protocol failure")] + Protocol, +} + +/// Maps gRPC status codes without exposing transport messages that could carry +/// request data. Structured denial metadata is decoded separately by clients. +pub fn classify_status(code: tonic::Code) -> StatusKind { + match code { + tonic::Code::PermissionDenied => StatusKind::Denied, + tonic::Code::Unauthenticated => StatusKind::Unauthenticated, + tonic::Code::FailedPrecondition | tonic::Code::Cancelled => StatusKind::Stale, + tonic::Code::Unimplemented => StatusKind::Unsupported, + tonic::Code::InvalidArgument => StatusKind::Invalid, + tonic::Code::Unavailable | tonic::Code::DeadlineExceeded => StatusKind::Unavailable, + _ => StatusKind::Protocol, + } +} diff --git a/crates/plugin-protocol/tests/common_data.rs b/crates/plugin-protocol/tests/common_data.rs new file mode 100644 index 000000000..77283a870 --- /dev/null +++ b/crates/plugin-protocol/tests/common_data.rs @@ -0,0 +1,169 @@ +use std::collections::BTreeSet; + +use gamenode_plugin_protocol::{common_data, proto::*}; + +#[test] +fn absent_and_empty_selectors_remain_private_only() { + assert_eq!( + common_data::categories(None).unwrap(), + Vec::::new() + ); + assert_eq!( + common_data::categories(Some(&CommonDataSelector::default())).unwrap(), + Vec::::new() + ); +} + +#[test] +fn explicit_categories_are_typed_and_map_to_independent_grants() { + let selector = CommonDataSelector { + categories: vec![ + CommonDataCategory::GamePerformanceHistory as i32, + CommonDataCategory::ContentAvailability as i32, + ], + ..Default::default() + }; + assert_eq!( + common_data::categories(Some(&selector)).unwrap(), + vec![ + CommonDataCategory::GamePerformanceHistory, + CommonDataCategory::ContentAvailability, + ] + ); + assert_eq!( + common_data::permission(CommonDataCategory::GamePerformanceHistory), + Some("common.game_performance_history.read") + ); + assert_eq!( + common_data::permission(CommonDataCategory::ContentAvailability), + Some("common.content_availability.read") + ); + assert_eq!( + common_data::permission(CommonDataCategory::LibraryRoots), + Some("library.roots.read") + ); + assert_eq!( + common_data::permission(CommonDataCategory::SaveProfiles), + Some("game.saves.read") + ); +} + +#[test] +fn shared_category_permissions_are_optional_known_third_party_grants() { + use gamenode_plugin_protocol::capability as cap; + + for permission in [ + cap::COMMON_GAME_PATHS_READ, + cap::COMMON_GAME_PERFORMANCE_HISTORY_READ, + cap::COMMON_RUNTIME_CATALOG_READ, + cap::COMMON_CONTENT_AVAILABILITY_READ, + ] { + assert!(cap::KNOWN.contains(&permission)); + assert!(cap::THIRD_PARTY_CAPABILITIES.contains(&permission)); + assert!(!cap::ALL.contains(&permission)); + } +} + +#[test] +fn invalid_or_ambiguous_category_values_are_rejected() { + for raw in [CommonDataCategory::Unspecified as i32, 99] { + assert!( + common_data::categories(Some(&CommonDataSelector { + categories: vec![raw], + ..Default::default() + })) + .is_err() + ); + } + assert_eq!( + common_data::categories(Some(&CommonDataSelector { + categories: vec![ + CommonDataCategory::GamePaths as i32, + CommonDataCategory::GamePaths as i32, + ], + ..Default::default() + })), + Err(common_data::SelectorError::Duplicate) + ); +} + +#[test] +fn selected_record_ids_are_explicit_independent_query_selectors() { + let selector = CommonDataSelector { + selected_record_ids: vec!["runtime:one".to_owned(), "save:two".to_owned()], + ..Default::default() + }; + assert_eq!( + common_data::selected_record_ids(Some(&selector)).unwrap(), + vec!["runtime:one", "save:two"] + ); + assert_eq!( + common_data::selected_record_ids(None).unwrap(), + Vec::<&str>::new() + ); + assert_eq!( + common_data::selected_record_ids(Some(&CommonDataSelector { + selected_record_ids: vec!["runtime:one".to_owned(), "runtime:one".to_owned()], + ..Default::default() + })), + Err(common_data::SelectorError::DuplicateRecordId) + ); + assert_eq!( + common_data::selected_record_ids(Some(&CommonDataSelector { + selected_record_ids: vec![" ".to_owned()], + ..Default::default() + })), + Err(common_data::SelectorError::EmptyRecordId) + ); +} + +#[test] +fn category_and_selected_record_grants_are_authorized_independently() { + let selector = CommonDataSelector { + categories: vec![ + CommonDataCategory::RuntimeCatalog as i32, + CommonDataCategory::ContentAvailability as i32, + ], + selected_record_ids: vec!["runtime:one".into(), "runtime:two".into()], + }; + let granted_categories = [CommonDataCategory::RuntimeCatalog].into(); + let granted_records = ["runtime:two".to_owned()].into(); + + let selected = + common_data::authorize_selector(Some(&selector), &granted_categories, &granted_records) + .unwrap(); + assert!(selected.includes_category(CommonDataCategory::RuntimeCatalog)); + assert!(!selected.includes_category(CommonDataCategory::ContentAvailability)); + assert!(!selected.includes_record("runtime:one")); + assert!(selected.includes_record("runtime:two")); + + let permission_grants = ["common.runtime_catalog.read".to_owned()].into(); + let selected_from_grants = common_data::authorize_grant_selector( + Some(&selector), + &permission_grants, + &granted_records, + ) + .unwrap(); + assert_eq!(selected_from_grants, selected); + + let private_only = + common_data::authorize_grant_selector(None, &permission_grants, &BTreeSet::new()).unwrap(); + assert!(!private_only.includes_category(CommonDataCategory::RuntimeCatalog)); + assert!(!private_only.includes_record("runtime:two")); + + // A category grant never implies access to every record in that category, and a record grant + // never widens the query to the whole category. + let category_only = common_data::authorize_grant_selector( + Some(&selector), + &permission_grants, + &BTreeSet::new(), + ) + .unwrap(); + assert!(category_only.includes_category(CommonDataCategory::RuntimeCatalog)); + assert!(!category_only.includes_record("runtime:two")); + let record_only = + common_data::authorize_grant_selector(Some(&selector), &BTreeSet::new(), &granted_records) + .unwrap(); + assert!(!record_only.includes_category(CommonDataCategory::RuntimeCatalog)); + assert!(record_only.includes_record("runtime:two")); +} diff --git a/crates/plugin-protocol/tests/common_data_contract.rs b/crates/plugin-protocol/tests/common_data_contract.rs new file mode 100644 index 000000000..a2780060e --- /dev/null +++ b/crates/plugin-protocol/tests/common_data_contract.rs @@ -0,0 +1,363 @@ +use gamenode_plugin_protocol::{ + common_data, + prost::Message, + prost_types::FileDescriptorSet, + proto::{ + CommonDataCategory, CommonDataSelector, DataMutationReply, DataRecord, StorageDurability, + }, +}; +use serde_json::Value; + +const DESCRIPTOR: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/plugin_descriptor.bin")); +const CONTRACT: &str = include_str!("../contracts/common_data_selector.json"); + +#[test] +fn common_data_fixture_matches_the_generated_wire_contract() { + let contract: Value = serde_json::from_str(CONTRACT).unwrap(); + assert_eq!(contract["api"], "1.6"); + assert_eq!(contract["field"]["private_default"], true); + + let descriptor = FileDescriptorSet::decode(DESCRIPTOR).unwrap(); + let request = descriptor + .file + .iter() + .flat_map(|file| &file.message_type) + .find(|message| message.name.as_deref() == Some("ResourceRequest")) + .expect("ResourceRequest descriptor"); + let field = request + .field + .iter() + .find(|field| field.name.as_deref() == Some("common_data_categories")) + .expect("common-data selector field"); + assert_eq!(field.number, Some(13)); + assert_eq!( + field.type_name.as_deref(), + Some(".gamenode.plugin.v1.CommonDataSelector") + ); + + let selector = descriptor + .file + .iter() + .flat_map(|file| &file.message_type) + .find(|message| message.name.as_deref() == Some("CommonDataSelector")) + .expect("CommonDataSelector descriptor"); + let selected_ids = selector + .field + .iter() + .find(|field| field.name.as_deref() == Some("selected_record_ids")) + .expect("selected-record selector field"); + assert_eq!(selected_ids.number, Some(2)); + assert_eq!(selected_ids.label, Some(3)); + + let data_list = descriptor + .file + .iter() + .flat_map(|file| &file.message_type) + .find(|message| message.name.as_deref() == Some("DataListRequest")) + .expect("DataListRequest descriptor"); + assert!( + data_list + .field + .iter() + .any(|field| field.name.as_deref() == Some("common_data_categories")), + "Data.List must support the same per-query category and record selector" + ); + + let data_publish = descriptor + .file + .iter() + .flat_map(|file| &file.message_type) + .find(|message| message.name.as_deref() == Some("DataPublishRequest")) + .expect("DataPublishRequest descriptor"); + for field in [ + "dataset_id", + "schema_id", + "schema_version", + "value", + "opaque_payload", + "resource_id", + "observed_at", + "sequence", + "source_observation_id", + ] { + assert!( + data_publish + .field + .iter() + .any(|candidate| candidate.name.as_deref() == Some(field)), + "DataPublishRequest must carry typed {field} metadata" + ); + } + let data_record = descriptor + .file + .iter() + .flat_map(|file| &file.message_type) + .find(|message| message.name.as_deref() == Some("DataRecord")) + .expect("DataRecord descriptor"); + for field in [ + "schema_id", + "schema_version", + "opaque_payload", + "provenance", + "resource_id", + "observed_at", + "received_at", + "expires_at", + "sequence", + "source_observation_id", + ] { + assert!( + data_record + .field + .iter() + .any(|candidate| candidate.name.as_deref() == Some(field)), + "DataRecord must carry typed {field} metadata" + ); + } + + for category in contract["categories"].as_array().unwrap() { + let name = category["name"].as_str().unwrap(); + let number = category["number"].as_i64().unwrap() as i32; + let permission = category["permission"].as_str().unwrap(); + let decoded = CommonDataCategory::try_from(number).unwrap(); + assert_eq!( + format!("{decoded:?}").to_ascii_uppercase().replace('_', ""), + name.replace('_', "") + ); + assert_eq!(common_data::permission(decoded), Some(permission)); + } + + for query in contract["queries"].as_array().unwrap() { + let id = query["id"].as_str().unwrap(); + let categories = query["categories"].as_array().unwrap(); + let selector = CommonDataSelector { + categories: categories + .iter() + .map(|name| { + let category = contract["categories"] + .as_array() + .unwrap() + .iter() + .find(|category| category["name"] == *name) + .unwrap(); + category["number"].as_i64().unwrap() as i32 + }) + .collect(), + selected_record_ids: query["selected_records"] + .as_array() + .unwrap() + .iter() + .map(|id| id.as_str().unwrap().to_owned()) + .collect(), + }; + let selected = if query["selector"] == "omitted" { + common_data::categories(None).unwrap() + } else { + common_data::categories(Some(&selector)).unwrap() + }; + let grants = query["grants"].as_array().unwrap(); + let categories_authorized = selected.iter().all(|category| { + let required = common_data::permission(*category).unwrap(); + grants.iter().any(|grant| grant.as_str() == Some(required)) + }); + let selected_records = common_data::selected_record_ids(Some(&selector)).unwrap(); + let record_grants = query["record_grants"].as_array().unwrap(); + let records_authorized = selected_records.iter().all(|record| { + record_grants + .iter() + .any(|grant| grant.as_str() == Some(*record)) + }); + let expected = query["expected"].as_str().unwrap(); + let actual = if selected.is_empty() && selected_records.is_empty() { + "PRIVATE_ONLY" + } else if categories_authorized && records_authorized { + "COMMON_INCLUDED" + } else { + "PERMISSION_DENIED" + }; + assert_eq!(actual, expected, "query fixture {id}"); + } + assert_eq!(contract["excluded_data"].as_array().unwrap().len(), 3); +} + +#[test] +fn generated_descriptor_keeps_typed_data_extensions_and_byte_envelopes_stable() { + let descriptor = FileDescriptorSet::decode(DESCRIPTOR).unwrap(); + let message = |name: &str| { + descriptor + .file + .iter() + .flat_map(|file| &file.message_type) + .find(|message| message.name.as_deref() == Some(name)) + .unwrap_or_else(|| panic!("{name} descriptor")) + }; + let field = |name: &str, field_name: &str| { + message(name) + .field + .iter() + .find(|field| field.name.as_deref() == Some(field_name)) + .unwrap_or_else(|| panic!("{name}.{field_name} descriptor")) + }; + + let resource_host = descriptor + .file + .iter() + .flat_map(|file| &file.service) + .find(|service| service.name.as_deref() == Some("ResourceHost")) + .expect("ResourceHost descriptor"); + for method in ["DataGet", "DataList", "DataWatch"] { + assert!( + resource_host + .method + .iter() + .any(|candidate| candidate.name.as_deref() == Some(method)), + "ResourceHost.{method} access" + ); + } + for request in ["DataGetRequest", "DataListRequest", "DataWatchRequest"] { + assert_eq!( + field(request, "common_data_categories") + .type_name + .as_deref(), + Some(".gamenode.plugin.v1.CommonDataSelector") + ); + } + + for (field_name, number) in [ + ("schema_id", 1), + ("schema_version", 2), + ("schema_digest", 3), + ("data", 4), + ] { + assert_eq!(field("ExtensionPayload", field_name).number, Some(number)); + } + assert_eq!( + field("ExtensionPayload", "data").type_name.as_deref(), + Some(".google.protobuf.Struct") + ); + for expected in [ + "namespace", + "schema_id", + "schema_version", + "schema_digest", + "schema_json", + "fields", + ] { + assert!( + message("ExtensionSchemaDescriptor") + .field + .iter() + .any(|candidate| candidate.name.as_deref() == Some(expected)), + "versioned namespaced schema field {expected}" + ); + } + for expected in ["schema_id", "schema_version", "value"] { + assert!( + message("DataPublishRequest") + .field + .iter() + .any(|candidate| candidate.name.as_deref() == Some(expected)), + "typed custom-data envelope field {expected}" + ); + } + assert_eq!( + field("DataPublishRequest", "value").type_name.as_deref(), + Some(".google.protobuf.Struct") + ); + assert_eq!( + field("StoragePutRequest", "value").r#type, + Some(prost_types::field_descriptor_proto::Type::Bytes as i32) + ); + assert_eq!( + field("StorageGetReply", "value").r#type, + Some(prost_types::field_descriptor_proto::Type::Bytes as i32) + ); + + for (message_name, expected_fields) in [ + ("RuntimeRecord", &["id", "revision", "extensions"][..]), + ( + "PerformanceSample", + &[ + "observed_at", + "frames_per_second", + "cpu_percent", + "memory_bytes", + "sequence", + ][..], + ), + ( + "HardwareReportRequest", + &["schema_id", "schema_version", "observations"][..], + ), + ] { + for expected in expected_fields { + assert!( + message(message_name) + .field + .iter() + .any(|field| field.name.as_deref() == Some(*expected)), + "typed base field {message_name}.{expected}" + ); + } + } + assert_eq!( + field("HardwareReportRequest", "observations") + .type_name + .as_deref(), + Some(".google.protobuf.Struct") + ); +} + +#[test] +fn data_durability_is_additive_on_the_publish_reply_and_record() { + let descriptor = FileDescriptorSet::decode(DESCRIPTOR).unwrap(); + let message = |name: &str| { + descriptor + .file + .iter() + .flat_map(|file| &file.message_type) + .find(|message| message.name.as_deref() == Some(name)) + .unwrap_or_else(|| panic!("{name} descriptor")) + }; + let field = |name: &str, field_name: &str| { + message(name) + .field + .iter() + .find(|field| field.name.as_deref() == Some(field_name)) + .unwrap_or_else(|| panic!("{name}.{field_name} descriptor")) + }; + + for (name, number) in [("DataMutationReply", 5), ("DataRecord", 16)] { + let durability = field(name, "durability"); + assert_eq!( + durability.number, + Some(number), + "{name}.durability keeps its additive number" + ); + assert_eq!( + durability.type_name.as_deref(), + Some(".gamenode.plugin.v1.StorageDurability"), + "{name}.durability carries the shared mode enum" + ); + } + + // A reader that predates the field sees no mode; a current reader sees the actual one. + let absent = DataMutationReply::decode([].as_slice()).unwrap(); + assert_eq!( + absent.durability, + StorageDurability::Unspecified as i32, + "an old or absent value decodes as unspecified" + ); + let durable = DataMutationReply { + durability: StorageDurability::Persistent as i32, + ..Default::default() + }; + let restored = DataMutationReply::decode(durable.encode_to_vec().as_slice()).unwrap(); + assert_eq!(restored.durability, StorageDurability::Persistent as i32); + let record = DataRecord { + durability: StorageDurability::SessionOnly as i32, + ..Default::default() + }; + let restored = DataRecord::decode(record.encode_to_vec().as_slice()).unwrap(); + assert_eq!(restored.durability, StorageDurability::SessionOnly as i32); +} diff --git a/crates/plugin-protocol/tests/contract.rs b/crates/plugin-protocol/tests/contract.rs index 62b9d518e..55e094a8a 100644 --- a/crates/plugin-protocol/tests/contract.rs +++ b/crates/plugin-protocol/tests/contract.rs @@ -84,6 +84,7 @@ fn discovery_location_round_trips_and_stays_absent_when_not_reported() { name: "Portal 2".into(), install_dir: r"C:\Program Files (x86)\Steam\steamapps\common\Portal 2".into(), fields: Default::default(), + target: None, }], install_root: Some(r"C:\Program Files (x86)\Steam".into()), library_folders: Some(4), @@ -206,6 +207,18 @@ fn negotiation_preserves_discovery_clients_without_granting_account_access() { negotiate(API_MAJOR, 2, &[SECRET_READ.into()], &[DISCOVERY]), Err(NegotiationError::Capability) ); + assert_eq!( + negotiate(API_MAJOR, 2, &[GAME_LAUNCH.into()], &[GAME_LAUNCH]), + Err(NegotiationError::Unsupported) + ); + assert_eq!( + negotiate(API_MAJOR, 5, &[GAME_LAUNCH.into()], &[GAME_LAUNCH]), + Err(NegotiationError::Unsupported) + ); + assert_eq!( + negotiate(API_MAJOR, 6, &[GAME_LAUNCH.into()], &[GAME_LAUNCH]), + Ok(6) + ); assert_eq!( negotiate(API_MAJOR + 1, 2, &[DISCOVERY.into()], &[DISCOVERY]), Err(NegotiationError::Version) @@ -221,6 +234,88 @@ fn negotiation_preserves_discovery_clients_without_granting_account_access() { ); } +#[test] +fn version_ranges_choose_highest_overlap_and_report_optional_features() { + use gamenode_plugin_protocol::capability::*; + let selected = negotiate_range( + 1, + 6, + 1, + 2, + 1, + 8, + &[ + (FEATURE_API_METADATA.into(), true), + ("future.feature".into(), false), + ], + ) + .unwrap(); + assert_eq!(selected.api_minor, 6); + assert_eq!( + selected.features, + vec![ + (FEATURE_API_METADATA.into(), true, 6), + ("future.feature".into(), false, 0), + ] + ); + assert_eq!( + negotiate_range(1, 5, 1, 1, 1, 5, &[(FEATURE_API_METADATA.into(), true)]), + Err(RangeNegotiationError::RequiredFeature) + ); + assert_eq!( + negotiate_range(1, 6, 2, 0, 2, 1, &[]), + Err(RangeNegotiationError::Version) + ); + assert_eq!(negotiate_range(1, 6, 0, 0, 0, 0, &[]).unwrap().api_minor, 6); + // Official 1.4/1.5 providers keep their single-minor handshake. + assert_eq!(negotiate_range(1, 5, 0, 0, 0, 0, &[]).unwrap().api_minor, 5); +} + +#[test] +fn session_scope_requires_target_only_for_extensions() { + use gamenode_plugin_protocol::capability::*; + use gamenode_plugin_protocol::proto::SessionKind; + assert_eq!( + validate_session_scope(SessionKind::Provider as u32, false), + Ok(()) + ); + assert_eq!( + validate_session_scope(SessionKind::Extension as u32, true), + Ok(()) + ); + assert_eq!( + validate_session_scope(SessionKind::Extension as u32, false), + Err(RangeNegotiationError::Session) + ); + assert_eq!( + validate_session_scope(SessionKind::Provider as u32, true), + Err(RangeNegotiationError::Session) + ); + assert!( + validate_target(&TargetGameContext { + game_id: "game:42".into(), + installation_id: "install-a".into(), + profile_id: "default".into(), + revision: "r4".into() + }) + .is_ok() + ); + assert!( + validate_target(&TargetGameContext { + game_id: "game-opaque-id".into(), + ..Default::default() + }) + .is_ok() + ); + assert!( + validate_target(&TargetGameContext { + game_id: "bad\nidentity".into(), + ..Default::default() + }) + .is_err() + ); +} + #[test] fn achievements_require_the_new_api_minor() { use gamenode_plugin_protocol::{API_MAJOR, API_MINOR, capability::*}; @@ -246,6 +341,66 @@ fn achievements_require_the_new_api_minor() { ); } +#[test] +fn api_control_contracts_roundtrip_and_denial_classification_is_safe() { + use gamenode_plugin_protocol::{StatusKind, classify_status}; + let metadata = DescribeApiReply { + api_major: 1, + api_minor: 6, + support_window: Some(SupportWindow { + minimum_api_minor: 1, + maximum_api_minor: 6, + support_ends_at: None, + policy: "current".into(), + }), + features: vec![ApiFeature { + id: "api.metadata".into(), + introduced_minor: 6, + permissions: vec![], + optional: true, + availability: "supported".into(), + }], + methods: vec![ApiMethod { + service: "PluginHost".into(), + method: "DescribeApi".into(), + introduced_minor: 6, + permissions: vec![], + ownership: "session".into(), + max_page_size: 0, + quota_bytes: 0, + idempotent: true, + }], + }; + assert_eq!( + DescribeApiReply::decode(metadata.encode_to_vec().as_slice()).unwrap(), + metadata + ); + assert_eq!( + classify_status(tonic::Code::PermissionDenied), + StatusKind::Denied + ); + assert_eq!( + classify_status(tonic::Code::Unauthenticated), + StatusKind::Unauthenticated + ); + assert_eq!( + classify_status(tonic::Code::FailedPrecondition), + StatusKind::Stale + ); + assert_eq!( + classify_status(tonic::Code::Unimplemented), + StatusKind::Unsupported + ); + assert_eq!( + classify_status(tonic::Code::InvalidArgument), + StatusKind::Invalid + ); + assert_eq!( + classify_status(tonic::Code::Unavailable), + StatusKind::Unavailable + ); +} + #[test] fn achievement_outcomes_reject_unrequested_ids_and_oversized_batches() { use gamenode_plugin_protocol::achievements::{MAX_GAMES, parse_outcomes}; @@ -583,10 +738,14 @@ fn commands_preserve_operation_and_account_profile_fences() { operation_id: "login-7".into(), account_epoch: 3, profile_epoch: 9, + session_kind: SessionKind::Provider as i32, + target_game: None, }), operation: ProviderOperation::CancelSignIn as i32, target_operation_id: "login-6".into(), settings: None, + runtime_session_result: None, + runtime_session_context_result: None, achievements: None, }; assert_eq!( diff --git a/crates/plugin-protocol/tests/extensions.rs b/crates/plugin-protocol/tests/extensions.rs new file mode 100644 index 000000000..5b6c58daa --- /dev/null +++ b/crates/plugin-protocol/tests/extensions.rs @@ -0,0 +1,360 @@ +use std::collections::{BTreeMap, HashMap}; + +use gamenode_plugin_protocol::{WireError, extensions::*, proto::*}; +use prost::Message; +use prost_types::{Struct, Value, value::Kind}; + +fn payload(schema_id: &str, label: &str) -> ExtensionPayload { + ExtensionPayload { + schema_id: schema_id.into(), + schema_version: 1, + schema_digest: vec![7; 32], + data: Some(Struct { + fields: BTreeMap::from([( + "label".into(), + Value { + kind: Some(Kind::StringValue(label.into())), + }, + )]), + }), + } +} + +fn descriptor() -> ExtensionSchemaDescriptor { + let schema_json = br#"{"type":"object","properties":{"label":{"type":"string"}}}"#.to_vec(); + use sha2::Digest; + ExtensionSchemaDescriptor { + namespace: "org.example.runtime".into(), + schema_id: "org.example.runtime.v1".into(), + schema_version: 1, + schema_digest: sha2::Sha256::digest(&schema_json).to_vec(), + schema_json, + fields: vec![ExtensionSchemaField { + path: "label".into(), + classification: ExtensionFieldClassification::Public as i32, + }], + optional: true, + } +} + +fn broker_projection_descriptor() -> ExtensionSchemaDescriptor { + let schema_json = br#"{"type":"object","properties":{"summary":{"type":"string"},"custom":{"type":"string"},"sensitive_history":{"type":"string"}}}"#.to_vec(); + use sha2::Digest; + ExtensionSchemaDescriptor { + namespace: "org.example.telemetry".into(), + schema_id: "org.example.telemetry.v1".into(), + schema_version: 1, + schema_digest: sha2::Sha256::digest(&schema_json).to_vec(), + schema_json, + fields: vec![ + ExtensionSchemaField { + path: "summary".into(), + classification: ExtensionFieldClassification::Public as i32, + }, + ExtensionSchemaField { + path: "custom".into(), + classification: ExtensionFieldClassification::Private as i32, + }, + ExtensionSchemaField { + path: "sensitive_history".into(), + classification: ExtensionFieldClassification::Sensitive as i32, + }, + ], + optional: true, + } +} + +fn string_value(value: &str) -> Value { + Value { + kind: Some(Kind::StringValue(value.into())), + } +} + +#[test] +fn extension_schema_is_bounded_packaged_and_digest_checked() { + let descriptor = descriptor(); + validate_schema_descriptor(&descriptor).unwrap(); + validate_schema_catalog(std::slice::from_ref(&descriptor)).unwrap(); + let mut wrong = descriptor.clone(); + wrong.schema_digest[0] ^= 1; + assert_eq!(validate_schema_descriptor(&wrong), Err(WireError)); + let mut external_ref = descriptor.clone(); + external_ref.schema_json = + br#"{"type":"object","$ref":"https://example.test/schema"}"#.to_vec(); + use sha2::Digest; + external_ref.schema_digest = sha2::Sha256::digest(&external_ref.schema_json).to_vec(); + assert_eq!(validate_schema_descriptor(&external_ref), Err(WireError)); + assert_eq!( + validate_schema_catalog(&[descriptor.clone(), descriptor]), + Err(WireError) + ); +} + +#[test] +fn extension_payload_limits_and_classification_are_enforced() { + let schema = descriptor(); + let mut valid_payload = payload("org.example.runtime.v1", "stable"); + valid_payload.schema_digest = schema.schema_digest.clone(); + validate_payload_for_schema(&valid_payload, &schema).unwrap(); + + for protected_key in ["revision", "owner", "permissions", "executable", "command"] { + let mut shadow = payload("org.example.runtime.v1", "stable"); + shadow.data.as_mut().unwrap().fields.insert( + protected_key.into(), + Value { + kind: Some(Kind::StringValue("forged".into())), + }, + ); + assert_eq!(validate_payload(&shadow), Err(WireError), "{protected_key}"); + } + + let mut non_finite = payload("org.example.runtime.v1", "stable"); + non_finite.data.as_mut().unwrap().fields.insert( + "measurement".into(), + Value { + kind: Some(Kind::NumberValue(f64::NAN)), + }, + ); + assert_eq!(validate_payload(&non_finite), Err(WireError)); + + let mut oversized = payload("org.example.runtime.v1", "stable"); + oversized.data.as_mut().unwrap().fields.insert( + "large".into(), + Value { + kind: Some(Kind::StringValue("x".repeat(MAX_EXTENSION_BYTES))), + }, + ); + assert_eq!(validate_payload(&oversized), Err(WireError)); + + let mut many_keys = payload("org.example.runtime.v1", "stable"); + many_keys.data.as_mut().unwrap().fields = (0..=MAX_OBJECT_KEYS) + .map(|index| { + ( + format!("k{index}"), + Value { + kind: Some(Kind::BoolValue(true)), + }, + ) + }) + .collect(); + assert_eq!(validate_payload(&many_keys), Err(WireError)); + + let mut deep = Value { + kind: Some(Kind::StringValue("leaf".into())), + }; + for depth in 0..=MAX_DEPTH { + deep = Value { + kind: Some(Kind::StructValue(Struct { + fields: BTreeMap::from([(format!("level{depth}"), deep)]), + })), + }; + } + let mut deep_payload = payload("org.example.runtime.v1", "stable"); + deep_payload.data.as_mut().unwrap().fields = BTreeMap::from([("root".into(), deep)]); + assert_eq!(validate_payload(&deep_payload), Err(WireError)); +} + +#[test] +fn broker_projection_returns_only_explicitly_granted_custom_fields() { + let descriptor = broker_projection_descriptor(); + let mut payload = ExtensionPayload { + schema_id: descriptor.schema_id.clone(), + schema_version: descriptor.schema_version, + schema_digest: descriptor.schema_digest.clone(), + data: Some(Struct { + fields: BTreeMap::from([ + ("summary".into(), string_value("frame pacing")), + ("custom".into(), string_value("producer-specific detail")), + ( + "sensitive_history".into(), + string_value("session observation"), + ), + ]), + }), + }; + validate_payload_for_schema(&payload, &descriptor).unwrap(); + + let public_only = + project_payload_fields(&payload, &descriptor, &["summary".to_owned()].into()).unwrap(); + let fields = &public_only.data.as_ref().unwrap().fields; + assert_eq!(fields.len(), 1); + assert_eq!(fields["summary"], string_value("frame pacing")); + assert!(!fields.contains_key("custom")); + assert!(!fields.contains_key("sensitive_history")); + + let reviewed = project_payload_fields( + &payload, + &descriptor, + &["summary".to_owned(), "sensitive_history".to_owned()].into(), + ) + .unwrap(); + let fields = &reviewed.data.as_ref().unwrap().fields; + assert_eq!(fields.len(), 2); + assert!(fields.contains_key("summary")); + assert!(fields.contains_key("sensitive_history")); + assert!(!fields.contains_key("custom")); + + // An unreviewed custom namespace is not made visible by a field grant from another schema. + payload.schema_id = "org.example.other.v1".into(); + assert_eq!( + project_payload_fields(&payload, &descriptor, &["summary".to_owned()].into()), + Err(WireError) + ); +} + +#[test] +fn namespace_projection_keeps_only_selected_nested_fields() { + let value = Struct { + fields: BTreeMap::from([ + ( + "display".into(), + Value { + kind: Some(Kind::StructValue(Struct { + fields: BTreeMap::from([ + ("name".into(), string_value("Runtime")), + ("internal_path".into(), string_value("/private/runtime")), + ]), + })), + }, + ), + ("owner".into(), string_value("forged-owner")), + ]), + }; + + let projected = project_struct_paths(&value, &["display.name".to_owned()].into()).unwrap(); + assert_eq!(projected.fields.len(), 1); + let Some(Kind::StructValue(display)) = projected.fields["display"].kind.as_ref() else { + panic!("selected namespace should remain an object"); + }; + assert_eq!( + display.fields, + BTreeMap::from([("name".into(), string_value("Runtime"))]) + ); + assert!(!projected.fields.contains_key("owner")); +} + +#[test] +fn namespace_patch_preserves_unknown_namespaces_and_typed_u64_values() { + let current = HashMap::from([ + ( + "org.example.runtime".into(), + payload("org.example.runtime.v1", "old"), + ), + ( + "org.unknown.consumer".into(), + payload("org.unknown.consumer.v2", "preserve-me"), + ), + ]); + let mut extensions = ExtensionSet::from_wire(current).unwrap(); + let patch = ExtensionPatch { + expected_revision: 9, + typed_field_mask: vec!["name".into()], + namespaces: vec![ExtensionNamespacePatch { + namespace: "org.example.runtime".into(), + operation: Some(extension_namespace_patch::Operation::Set(payload( + "org.example.runtime.v1", + "new", + ))), + }], + }; + validate_patch(&patch).unwrap(); + assert_eq!(extensions.apply_patch(&patch, 9), Ok(10)); + assert_eq!( + extensions.as_map()["org.unknown.consumer"], + payload("org.unknown.consumer.v2", "preserve-me") + ); + assert_eq!( + extensions.as_map()["org.example.runtime"], + payload("org.example.runtime.v1", "new") + ); + assert_eq!(extensions.apply_patch(&patch, 10), Err(WireError)); + + // A usable typed resource remains valid when this client does not recognize an optional + // extension schema. Typed identity and revision remain outside the extension Struct. + let runtime = RuntimeRecord { + id: "runtime-one".into(), + name: "Old name".into(), + revision: 9, + extensions: extensions.into_wire(), + ..Default::default() + }; + let updated = apply_runtime_patch( + &runtime, + &RuntimeRecord { + name: "New name".into(), + ..runtime.clone() + }, + &ExtensionPatch { + expected_revision: 9, + typed_field_mask: vec!["name".into()], + ..Default::default() + }, + ) + .unwrap(); + assert_eq!(updated.id, "runtime-one"); + assert_eq!(updated.name, "New name"); + assert_eq!(updated.revision, 10); + assert_eq!( + updated.extensions["org.unknown.consumer"], + payload("org.unknown.consumer.v2", "preserve-me") + ); + let decoded_with_extension = RuntimeRecord::decode(updated.encode_to_vec().as_slice()).unwrap(); + assert_eq!(decoded_with_extension.id, "runtime-one"); + assert_eq!(decoded_with_extension.name, "New name"); + assert_eq!(decoded_with_extension.revision, 10); + assert_eq!( + decoded_with_extension.extensions["org.unknown.consumer"], + payload("org.unknown.consumer.v2", "preserve-me"), + "an unsupported optional namespace must not invalidate its typed base" + ); + + let runtime = RuntimeRecord { + id: "runtime-one".into(), + revision: u64::MAX, + observed_at: i64::MAX, + ..Default::default() + }; + let decoded = RuntimeRecord::decode(runtime.encode_to_vec().as_slice()).unwrap(); + assert_eq!(decoded.revision, u64::MAX); + assert_eq!(decoded.observed_at, i64::MAX); +} + +#[test] +fn extension_set_enforces_object_key_budget_across_all_namespaces() { + fn payload_with_keys(schema_id: &str, count: usize) -> ExtensionPayload { + ExtensionPayload { + schema_id: schema_id.into(), + schema_version: 1, + schema_digest: vec![3; 32], + data: Some(Struct { + fields: (0..count) + .map(|index| (format!("field-{index}"), string_value("value"))) + .collect(), + }), + } + } + + let within_budget = HashMap::from([ + ( + "org.example.first".into(), + payload_with_keys("org.example.first.v1", MAX_OBJECT_KEYS / 2), + ), + ( + "org.example.second".into(), + payload_with_keys("org.example.second.v1", MAX_OBJECT_KEYS / 2), + ), + ]); + assert!(ExtensionSet::from_wire(within_budget).is_ok()); + + let over_budget = HashMap::from([ + ( + "org.example.first".into(), + payload_with_keys("org.example.first.v1", MAX_OBJECT_KEYS / 2 + 1), + ), + ( + "org.example.second".into(), + payload_with_keys("org.example.second.v1", MAX_OBJECT_KEYS / 2 + 1), + ), + ]); + assert_eq!(ExtensionSet::from_wire(over_budget), Err(WireError)); +} diff --git a/crates/plugin-protocol/tests/resource_contract.rs b/crates/plugin-protocol/tests/resource_contract.rs new file mode 100644 index 000000000..cedacd676 --- /dev/null +++ b/crates/plugin-protocol/tests/resource_contract.rs @@ -0,0 +1,432 @@ +use gamenode_plugin_protocol::prost::Message; +use gamenode_plugin_protocol::prost_types::FileDescriptorSet; +use serde_json::Value; + +const DESCRIPTOR: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/plugin_descriptor.bin")); +const CATALOG: &str = include_str!("../contracts/resource_host.json"); +const DOMAIN_CATALOG: &str = include_str!("../contracts/domain_host.json"); +const FIELD_POLICY: &str = include_str!("../contracts/endpoint_field_policy.json"); + +#[test] +fn checked_resource_catalog_matches_generated_protobuf_service() { + let catalog: Value = serde_json::from_str(CATALOG).unwrap(); + assert_eq!(catalog["api"], "1.6"); + assert_eq!(catalog["service"], "ResourceHost"); + assert_eq!(catalog["unknown_route"], "UNIMPLEMENTED"); + + let descriptors = FileDescriptorSet::decode(DESCRIPTOR).unwrap(); + let service = descriptors + .file + .iter() + .flat_map(|file| &file.service) + .find(|service| service.name.as_deref() == Some("ResourceHost")) + .expect("generated ResourceHost descriptor"); + let mut described: Vec<_> = service + .method + .iter() + .map(|method| { + ( + method.name.as_deref().unwrap().to_owned(), + method + .input_type + .as_deref() + .unwrap() + .replace(".gamenode.plugin.v1.", ""), + method + .output_type + .as_deref() + .unwrap() + .replace(".gamenode.plugin.v1.", ""), + method.server_streaming.unwrap_or(false), + ) + }) + .collect(); + let mut catalogued: Vec<_> = catalog["routes"] + .as_array() + .unwrap() + .iter() + .map(|route| { + ( + route["method"].as_str().unwrap().to_owned(), + route["request"].as_str().unwrap().to_owned(), + route["response"].as_str().unwrap().to_owned(), + route["streaming"].as_bool().unwrap(), + ) + }) + .collect(); + described.sort(); + catalogued.sort(); + assert_eq!( + catalogued, described, + "catalog and generated wire routes diverged" + ); + + for route in catalog["routes"].as_array().unwrap() { + assert!(!route["permission"].as_str().unwrap().is_empty()); + assert!(!route["owner"].as_str().unwrap().is_empty()); + let contract = &route["contract"]; + assert!(!contract["operation_owner"].as_str().unwrap().is_empty()); + assert!(!contract["resource_owner"].as_str().unwrap().is_empty()); + assert!(contract["revision"].is_object()); + assert!(contract["idempotency"]["required"].is_boolean()); + assert!(!contract["quota"].as_str().unwrap().is_empty()); + assert!( + !contract["commit_authorization"] + .as_str() + .unwrap() + .is_empty() + ); + assert!(!route["semantics"].as_array().unwrap().is_empty()); + } +} + +#[test] +fn runtime_request_access_is_a_host_picker_route_without_path_fields() { + let catalog: Value = serde_json::from_str(CATALOG).unwrap(); + let route = catalog["routes"] + .as_array() + .unwrap() + .iter() + .find(|route| route["method"] == "RuntimesRequestAccess") + .expect("RuntimesRequestAccess route"); + assert_eq!(route["request"], "RuntimeRequestAccessRequest"); + assert_eq!(route["response"], "RuntimeMutationReply"); + assert_eq!(route["permission"], "game.runtime.create"); + assert_eq!(route["streaming"], false); + assert!( + route["semantics"] + .as_array() + .unwrap() + .iter() + .any(|item| item.as_str().unwrap().contains("empty executable_handle")) + ); + + let descriptors = FileDescriptorSet::decode(DESCRIPTOR).unwrap(); + let message = |name: &str| { + descriptors + .file + .iter() + .flat_map(|file| &file.message_type) + .find(|message| message.name.as_deref() == Some(name)) + .unwrap_or_else(|| panic!("missing message {name}")) + }; + let request = message("RuntimeRequestAccessRequest"); + let fields: Vec<&str> = request + .field + .iter() + .map(|field| field.name.as_deref().unwrap()) + .collect(); + assert_eq!(fields, ["mutation", "runtime", "hints"]); + assert!(request.field.iter().all(|field| { + !field.name.as_deref().unwrap().contains("path") + && !field.name.as_deref().unwrap().contains("handle") + })); + + let hints = message("RuntimeAccessHints"); + let hint_fields: Vec<&str> = hints + .field + .iter() + .map(|field| field.name.as_deref().unwrap()) + .collect(); + assert_eq!(hint_fields, ["executable_names", "desktop_ids"]); +} + +#[test] +fn ordinary_and_custom_launch_are_distinct_wire_contracts() { + let catalog: Value = serde_json::from_str(CATALOG).unwrap(); + let route = |name: &str| { + catalog["routes"] + .as_array() + .unwrap() + .iter() + .find(|route| route["method"] == name) + .unwrap() + }; + let ordinary = route("GamesRequestLaunch"); + assert_eq!(ordinary["request"], "GameLaunchRequest"); + assert_eq!(ordinary["permission"], "game.launch"); + let custom = route("GamesRequestCustomLaunch"); + assert_eq!(custom["request"], "CustomLaunchRequest"); + assert_eq!(custom["permission"], "game.custom_launch"); + assert!( + custom["semantics"] + .as_array() + .unwrap() + .iter() + .any(|item| item.as_str().unwrap().contains("never aliases game.launch")) + ); +} + +#[test] +fn resource_routes_use_typed_operation_messages() { + let catalog: Value = serde_json::from_str(CATALOG).unwrap(); + for route in catalog["routes"].as_array().unwrap() { + assert_ne!(route["request"], "ResourceRequest", "{}", route["method"]); + assert_ne!(route["response"], "ResourceReply", "{}", route["method"]); + assert!(!route["permission"].as_str().unwrap().is_empty()); + assert!(!route["owner"].as_str().unwrap().is_empty()); + } + let ordinary = catalog["routes"] + .as_array() + .unwrap() + .iter() + .find(|route| route["method"] == "GamesRequestLaunch") + .unwrap(); + assert_eq!(ordinary["request"], "GameLaunchRequest"); + let custom = catalog["routes"] + .as_array() + .unwrap() + .iter() + .find(|route| route["method"] == "GamesRequestCustomLaunch") + .unwrap(); + assert_eq!(custom["request"], "CustomLaunchRequest"); + assert_eq!(custom["permission"], "game.custom_launch"); +} + +#[test] +fn endpoint_field_policy_covers_all_current_services_and_marks_future_routes() { + let fixture: Value = serde_json::from_str(FIELD_POLICY).unwrap(); + let routes = fixture["routes"].as_array().unwrap(); + assert_eq!(routes.len(), 107); + for route in routes { + assert!(!route["request_policy"].as_str().unwrap().is_empty()); + assert!(!route["response_policy"].as_str().unwrap().is_empty()); + assert!( + !route["extension_or_opaque_policy"] + .as_str() + .unwrap() + .is_empty() + ); + assert!(!route["access_model"].as_str().unwrap().is_empty()); + match route["status"].as_str().unwrap() { + "protobuf_contract" => { + assert!(!route["wire_service"].as_str().unwrap().is_empty()); + assert!(!route["wire_method"].as_str().unwrap().is_empty()); + assert!(!route["request_type"].as_str().unwrap().is_empty()); + assert!(!route["response_type"].as_str().unwrap().is_empty()); + } + "planned" => panic!("route remains planned: {}", route["route"]), + state => panic!("unexpected route state: {state}"), + } + } + + let descriptors = FileDescriptorSet::decode(DESCRIPTOR).unwrap(); + let mut actual = Vec::new(); + for file in &descriptors.file { + for service in &file.service { + let Some(service_name) = service.name.as_deref() else { + continue; + }; + if !matches!( + service_name, + "PluginHost" + | "ProviderHost" + | "ResourceHost" + | "Saves" + | "Locations" + | "StorageDiagnostics" + | "Computer" + | "GamePresence" + | "GamePerformance" + ) { + continue; + } + for method in &service.method { + actual.push((service_name.to_owned(), method.name.clone().unwrap())); + } + } + } + let mut mapped: Vec<_> = routes + .iter() + .filter(|route| route["status"] == "protobuf_contract") + .map(|route| { + ( + route["wire_service"].as_str().unwrap().to_owned(), + route["wire_method"].as_str().unwrap().to_owned(), + ) + }) + .collect(); + actual.sort(); + mapped.sort(); + assert_eq!( + mapped, actual, + "field policy must cover each current service route exactly once" + ); + + let exchange = &fixture["exchange_event_families"]; + assert!( + exchange + .as_array() + .unwrap() + .iter() + .any(|item| item["family"] == "CatalogChunk") + ); + assert!( + exchange + .as_array() + .unwrap() + .iter() + .any(|item| item["family"] == "runtime session event/result") + ); + + let runtime_sessions = exchange + .as_array() + .unwrap() + .iter() + .find(|item| item["family"] == "runtime session event/result") + .unwrap(); + assert_eq!(runtime_sessions["event_message"], "RuntimeSessionReport"); + assert_eq!(runtime_sessions["result_message"], "RuntimeSessionResult"); + assert_eq!( + runtime_sessions["permission"], + "game.sessions.report; approved game/installation/runtime scope" + ); + + let message_field = |message_name: &str, field_name: &str| { + descriptors + .file + .iter() + .flat_map(|file| &file.message_type) + .find(|message| message.name.as_deref() == Some(message_name)) + .unwrap() + .field + .iter() + .find(|field| field.name.as_deref() == Some(field_name)) + .unwrap() + .type_name + .clone() + .unwrap() + }; + assert_eq!( + message_field("ProviderEvent", "runtime_session"), + ".gamenode.plugin.v1.RuntimeSessionReport" + ); + assert_eq!( + message_field("ProviderCommand", "runtime_session_result"), + ".gamenode.plugin.v1.RuntimeSessionResult" + ); +} + +#[test] +fn host_storage_administration_is_not_a_plugin_route() { + // Physical-path accounting and reviewed cleanup are host administration. No plugin service + // advertises them and no wire message can carry a managed path, so plugin IPC cannot reach + // those values. + let proto = include_str!("../proto/plugin.proto"); + for forbidden in [ + "StorageCleanup", + "StorageLocations", + "storage_cleanup", + "storage_locations", + "physical_path", + ] { + assert!( + !proto.contains(forbidden), + "{forbidden} must not appear in the plugin wire contract" + ); + } + + let descriptors = FileDescriptorSet::decode(DESCRIPTOR).unwrap(); + for file in &descriptors.file { + for service in &file.service { + for method in &service.method { + let name = method.name.as_deref().unwrap_or_default(); + let lowered = name.to_ascii_lowercase(); + assert!( + !lowered.contains("cleanup") + && !lowered.contains("storagelocation") + && !lowered.contains("storagelocations"), + "{name} must not be a plugin route" + ); + } + } + } +} + +#[test] +fn domain_catalog_matches_generated_contracts_and_operation_grants() { + let catalog: Value = serde_json::from_str(DOMAIN_CATALOG).unwrap(); + assert_eq!(catalog["api"], "1.6"); + let routes = catalog["routes"].as_array().unwrap(); + assert_eq!(routes.len(), 26); + assert!( + routes + .iter() + .all(|route| !route["permission"].as_str().unwrap().is_empty()) + ); + + let descriptors = FileDescriptorSet::decode(DESCRIPTOR).unwrap(); + let mut actual = Vec::new(); + for file in &descriptors.file { + for service in &file.service { + let Some(service_name) = service.name.as_deref() else { + continue; + }; + if !matches!( + service_name, + "Saves" + | "Locations" + | "StorageDiagnostics" + | "Computer" + | "GamePresence" + | "GamePerformance" + ) { + continue; + } + for method in &service.method { + actual.push(( + service_name.to_owned(), + method.name.clone().unwrap(), + method + .input_type + .as_deref() + .unwrap() + .replace(".gamenode.plugin.v1.", ""), + method + .output_type + .as_deref() + .unwrap() + .replace(".gamenode.plugin.v1.", ""), + method.server_streaming.unwrap_or(false), + )); + } + } + } + let mut described: Vec<_> = routes + .iter() + .map(|route| { + ( + route["service"].as_str().unwrap().to_owned(), + route["method"].as_str().unwrap().to_owned(), + route["request"].as_str().unwrap().to_owned(), + route["response"].as_str().unwrap().to_owned(), + route["streaming"].as_bool().unwrap(), + ) + }) + .collect(); + actual.sort(); + described.sort(); + assert_eq!( + described, actual, + "domain catalog and protobuf descriptors diverged" + ); + + let permission = |method: &str| { + routes + .iter() + .find(|route| route["method"] == method) + .unwrap()["permission"] + .as_str() + .unwrap() + }; + assert_eq!(permission("CreateProfile"), "game.saves.create"); + assert_eq!(permission("UpdateProfile"), "game.saves.update"); + assert_eq!(permission("RemoveProfile"), "game.saves.delete"); + + let proto = include_str!("../proto/plugin.proto"); + assert!(proto.contains("repeated string selected_record_ids = 2")); + assert!( + proto.contains("CommonDataSelector common_data_categories = 4;"), + "Data.List must carry the same per-query selector" + ); +} diff --git a/crates/plugin-sdk/Cargo.toml b/crates/plugin-sdk/Cargo.toml index 03a19d061..3ce2db07a 100644 --- a/crates/plugin-sdk/Cargo.toml +++ b/crates/plugin-sdk/Cargo.toml @@ -1,18 +1,20 @@ [package] name = "gamenode-plugin-sdk" description = "Public client SDK for GameNode provider plugins" +documentation = "https://docs.rs/gamenode-plugin-sdk" +repository = "https://github.com/game-node-app/game-node-desktop" version.workspace = true edition.workspace = true rust-version.workspace = true -license.workspace = true +license = "MIT" authors.workspace = true -publish.workspace = true +publish = ["crates-io"] [lints] workspace = true [dependencies] -gamenode-plugin-protocol = { path = "../plugin-protocol" } +gamenode-plugin-protocol = { version = "=0.1.0", path = "../plugin-protocol" } async-trait.workspace = true thiserror.workspace = true tokio = { workspace = true, features = ["rt-multi-thread", "macros", "net", "time", "sync"] } @@ -22,5 +24,6 @@ hyper-util = { version = "0.1", features = ["tokio"] } tower = "0.5" [dev-dependencies] +serde_json.workspace = true tempfile.workspace = true tokio-stream = { version = "0.1", features = ["net"] } diff --git a/crates/plugin-sdk/LICENSE b/crates/plugin-sdk/LICENSE new file mode 100644 index 000000000..41bac266d --- /dev/null +++ b/crates/plugin-sdk/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 GameNode contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/crates/plugin-sdk/examples/action_recipes.rs b/crates/plugin-sdk/examples/action_recipes.rs new file mode 100644 index 000000000..37a1feb4c --- /dev/null +++ b/crates/plugin-sdk/examples/action_recipes.rs @@ -0,0 +1,230 @@ +//! Practical recipes for the host action services: launch/install, backups, tools and ports. +//! +//! These are plain functions over [`Actions`] (from `HostClient::actions()`); copy what you need. +//! They are compiled with the SDK and run against the desktop's fixture host in its service +//! tests, so they stay true to what the host does. Run `cargo doc` for the rules each call +//! follows; the permissions document explains every status code. +//! +//! An action answers with a job. Core may ask the user first, and the job stays `QUEUED` with +//! the message `awaiting confirmation` while the dialog is open. [`wait_for_job`] follows it to +//! a terminal state. A decline, a timeout or a revoked permission ends it `FAILED` without +//! committing anything; [`cancel`] withdraws a request that still waits. +#![allow(dead_code)] + +use gamenode_plugin_sdk::{Actions, Code, Status, idempotency_key, proto::JobState}; +use tokio_stream::StreamExt; + +/// The terminal state of a job and the host's stable code for it. Show `message` to people, but +/// branch on `state` and `result_code`. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Finished { + pub state: JobState, + pub result_code: String, + pub message: String, +} + +/// Whether a job can no longer change. +pub fn is_terminal(state: JobState) -> bool { + matches!( + state, + JobState::Succeeded | JobState::Failed | JobState::Cancelled + ) +} + +/// Follows a job to its terminal state. A watch that ends early falls back to one `JobsGet`, so a +/// lost event does not hide the outcome. `PERMISSION_DENIED` means the operation's permission was +/// revoked: the job committed nothing, and the user has to approve the access again. +pub async fn wait_for_job(actions: &Actions, job_id: &str) -> Result { + let mut events = actions.watch_job(job_id, 0).await?; + while let Some(event) = events.next().await { + let event = event?; + if is_terminal(event.state()) { + return Ok(Finished { + state: event.state(), + result_code: event.result_code, + message: event.message, + }); + } + } + let reply = actions.job(job_id).await?; + if is_terminal(reply.state()) { + Ok(Finished { + state: reply.state(), + result_code: reply.result_code, + message: reply.message, + }) + } else { + Err(Status::unavailable( + "the job watch ended before a terminal state", + )) + } +} + +/// Withdraws a request that still waits for the user. A job that already runs may answer +/// `RUNNING` and report what it finally did; do not assume the effect was undone. +pub async fn cancel(actions: &Actions, job_id: &str) -> Result { + let reply = actions.cancel_job(job_id, &idempotency_key()).await?; + Ok(Finished { + state: reply.state(), + result_code: reply.result_code, + message: reply.message, + }) +} + +fn job_started(reply: gamenode_plugin_sdk::proto::JobReply) -> Result { + if reply.job_id.is_empty() { + Err(Status::failed_precondition("the host returned no job")) + } else { + Ok(reply.job_id) + } +} + +/// Starts an installed game through its detected target and waits for the result. Core asks the +/// user unless this call redeems a host-issued intent. `expected_revision` is the entry's +/// `revision`; a changed target is refused rather than silently replaced. +pub async fn launch( + actions: &Actions, + installation_id: &str, + expected_revision: u64, +) -> Result { + let reply = actions + .launch_game( + "", + installation_id, + expected_revision, + "", + &idempotency_key(), + ) + .await?; + if reply.job_id.is_empty() { + return Err(Status::failed_precondition( + if reply.refusal_code.is_empty() { + "the launch was refused".to_owned() + } else { + reply.refusal_code + }, + )); + } + wait_for_job(actions, &reply.job_id).await +} + +/// Opens the provider's install flow for a game and waits for the result. The user confirms the +/// install in Core; a plugin cannot choose installer inputs. +pub async fn install( + actions: &Actions, + game_id: &str, + installation_id: &str, +) -> Result { + let job = actions + .install_game(game_id, installation_id, "", &idempotency_key()) + .await?; + wait_for_job(actions, &job_started(job)?).await +} + +/// Applies or updates a host-catalog tool on one installed game and waits for the result. +pub async fn apply_tool( + actions: &Actions, + tool_id: &str, + game_id: &str, + expected_revision: u64, +) -> Result { + let job = actions + .apply_tool(tool_id, game_id, expected_revision, &idempotency_key()) + .await?; + wait_for_job(actions, &job_started(job)?).await +} + +/// Removes a host-catalog tool from one installed game and waits for the result. +pub async fn remove_tool( + actions: &Actions, + tool_id: &str, + game_id: &str, + expected_revision: u64, +) -> Result { + let job = actions + .remove_tool(tool_id, game_id, expected_revision, &idempotency_key()) + .await?; + wait_for_job(actions, &job_started(job)?).await +} + +/// Installs a host-catalog port and waits for the result. The user chooses the destination, +/// sources and risk acknowledgements in Core's setup window. +pub async fn install_port( + actions: &Actions, + port_id: &str, + game_id: &str, + supplied_file_handles: Vec, +) -> Result { + let job = actions + .install_port( + port_id, + game_id, + supplied_file_handles, + 0, + &idempotency_key(), + ) + .await?; + wait_for_job(actions, &job_started(job)?).await +} + +/// Backs up an approved save profile and waits for the result. +pub async fn create_backup( + actions: &Actions, + game_id: &str, + profile_id: &str, + expected_revision: u64, +) -> Result { + let job = actions + .create_backup( + game_id, + profile_id, + "Requested by the plugin", + expected_revision, + &idempotency_key(), + ) + .await?; + wait_for_job(actions, &job_started(job)?).await +} + +/// Restores one retained backup. Core asks the user to confirm the exact targets before anything +/// is written; the plugin cannot remember or reuse that consent. +pub async fn restore_backup( + actions: &Actions, + backup_id: &str, + game_id: &str, + profile_id: &str, + expected_revision: u64, +) -> Result { + let job = actions + .restore_backup( + backup_id, + game_id, + profile_id, + expected_revision, + &idempotency_key(), + ) + .await?; + wait_for_job(actions, &job_started(job)?).await +} + +/// A small summary of a failed job for a user-facing message. `message` is untrusted text from +/// the host and must be rendered as plain text. +pub fn describe(finished: &Finished) -> Option { + if finished.state == JobState::Failed { + Some(if finished.message.is_empty() { + format!("The operation failed ({})", finished.result_code) + } else { + finished.message.clone() + }) + } else { + None + } +} + +/// Whether a status means the plugin should ask the user to approve access again instead of +/// retrying: the permission was revoked or was never granted. +pub fn needs_new_approval(status: &Status) -> bool { + status.code() == Code::PermissionDenied +} + +fn main() {} diff --git a/crates/plugin-sdk/examples/custom_launch_recipes.rs b/crates/plugin-sdk/examples/custom_launch_recipes.rs new file mode 100644 index 000000000..f8928e7b5 --- /dev/null +++ b/crates/plugin-sdk/examples/custom_launch_recipes.rs @@ -0,0 +1,80 @@ +//! Typed recipe lifecycle for `game.custom_launch`. +//! +//! This API is separate from standard `game.launch`: a missing custom-launch grant returns +//! `PERMISSION_DENIED`, and the SDK never retries through the standard launch route. Handles are +//! opaque values returned by approved host resources, not filesystem paths supplied by a plugin. +#![allow(dead_code)] + +use gamenode_plugin_sdk::{ + CustomLaunchRecipe, Resources, Status, idempotency_key, proto::CustomLaunchReply, +}; + +/// Propose a custom executable recipe with literal argv, a host-issued runtime handle and an +/// explicit environment delta. The host validates and reviews the recipe before it can run. +#[allow(clippy::too_many_arguments)] // Example mirrors the deliberate positional custom-launch API. +pub async fn propose_runtime_recipe( + resources: &Resources, + game_id: &str, + installation_id: &str, + content_id: &str, + game_revision: u64, + executable_handle: &str, + working_directory_handle: &str, + runtime_handle: &str, +) -> Result { + let recipe = CustomLaunchRecipe { + game_id: game_id.into(), + installation_id: installation_id.into(), + content_id: content_id.into(), + expected_revision: game_revision, + executable_handle: executable_handle.into(), + working_directory_handle: working_directory_handle.into(), + runtime_handle: runtime_handle.into(), + argv: vec!["--game".into(), "620".into()], + environment_set: [("GAME_MODE".into(), "compatibility".into())].into(), + environment_unset: vec!["UNSAFE_INHERITED_SETTING".into()], + ..Default::default() + }; + resources + .propose_custom_launch(&recipe, "", &idempotency_key()) + .await +} + +/// Execute only the exact host-approved recipe revision. The request has no argv, executable, +/// working-directory, runtime or environment fields to replace the plan that was reviewed. +pub async fn request_approved_recipe( + resources: &Resources, + game_id: &str, + installation_id: &str, + game_revision: u64, + recipe_id: &str, + recipe_revision: u64, + user_intent_id: &str, +) -> Result { + resources + .request_custom_launch( + game_id, + installation_id, + game_revision, + recipe_id, + recipe_revision, + user_intent_id, + &idempotency_key(), + ) + .await +} + +/// Remove an owned recipe with the revision returned by the proposal/read operation. +pub async fn remove_recipe( + resources: &Resources, + game_id: &str, + recipe_id: &str, + recipe_revision: u64, +) -> Result<(), Status> { + resources + .remove_custom_launch(game_id, recipe_id, recipe_revision, &idempotency_key()) + .await?; + Ok(()) +} + +fn main() {} diff --git a/crates/plugin-sdk/examples/data_exchange_recipes.rs b/crates/plugin-sdk/examples/data_exchange_recipes.rs new file mode 100644 index 000000000..be6f9bcd1 --- /dev/null +++ b/crates/plugin-sdk/examples/data_exchange_recipes.rs @@ -0,0 +1,410 @@ +//! Producer/consumer exchanges for performance history, approved locations, save profiles and a +//! shared runtime with several content identities. +//! +//! These are plain functions over the generated clients returned by [`HostClient`]; copy what you +//! need. They are compiled with the SDK and run against the desktop's fixture host in its service +//! tests, so they stay true to what the host does. +//! +//! What the host interprets and what it does not: +//! +//! - The host selects the game, installation and local `active-host` computer context from the +//! authenticated session. A request that names another game is refused; the caller never picks +//! its own computer identity. +//! - Units, sample sequence, FPS method/statistic/quality, CPU scope/normalization and memory kind +//! are validated and retained as given. A source or tool name is descriptive metadata: the host +//! does not start a collector or verify that one ran. +//! - Location inspection returns opaque handles and volume tokens for an approved folder. No reply +//! contains a filesystem path, so a plugin never learns where the folder is. +//! - Save profiles are owner-only. A common-category selector on the save-profile routes is an +//! `UNIMPLEMENTED` answer rather than a narrowed projection. +//! - A shared runtime projects its executable handle as empty, and content availability carries +//! safe content/runtime identities only. +//! +//! Cross-plugin reads need an explicit selector on every query plus a current host grant. Without +//! the selector the answer is private-only; with a revoked grant the call is `PERMISSION_DENIED`. +#![allow(dead_code)] + +use std::time::Duration; + +use gamenode_plugin_sdk::{ + HostClient, Status, + proto::{ + CommonDataCategory, CommonDataSelector, DomainListRequest, LibraryGetReply, + LibraryGetRequest, LocationInspectReply, LocationInspectRequest, LocationSizeReply, + LocationSizeRequest, MutationContext, PageRequest, PerformanceAggregateReply, + PerformanceAggregateRequest, PerformanceCpuNormalization, PerformanceCpuScope, + PerformanceEndSeriesRequest, PerformanceFpsMethod, PerformanceFpsStatistic, + PerformanceListReply, PerformanceListRequest, PerformanceMeasurementQuality, + PerformanceMemoryKind, PerformanceQuerySeriesReply, PerformanceQuerySeriesRequest, + PerformanceSample, PerformanceSamplesRequest, ReportMutationReply, RuntimesListReply, + SaveProfileGetRequest, SaveProfileListReply, SaveProfileListRequest, SaveProfileReply, + }, +}; + +/// The one computer context the host binds to an authenticated session. +pub const LOCAL_COMPUTER: &str = "active-host"; +/// A host-defined projection for retained performance series. +pub const PERFORMANCE_PROJECTION: &str = "performance.v1"; +/// Requested location dimensions; the host answers the ones it supports. +pub const LOCATION_DIMENSIONS: [&str; 3] = ["availability", "volume", "capacity"]; + +pub fn category_selector(category: CommonDataCategory) -> CommonDataSelector { + CommonDataSelector { + categories: vec![category as i32], + selected_record_ids: Vec::new(), + } +} + +pub fn performance_selector() -> CommonDataSelector { + category_selector(CommonDataCategory::GamePerformanceHistory) +} + +/// One actual observation as an example game overlay would collect it. Nothing here is captured +/// by GameNode: the values are the publisher's claim with explicit units and semantics. +pub fn sample(sequence: u64, observed_at: i64, fps: f64) -> PerformanceSample { + PerformanceSample { + observed_at, + frames_per_second: fps, + cpu_percent: 34.5, + memory_bytes: 512 * 1024 * 1024, + sequence, + sampling_window_ms: 0, + fps_method: PerformanceFpsMethod::Instantaneous as i32, + fps_statistic: PerformanceFpsStatistic::Instantaneous as i32, + quality: PerformanceMeasurementQuality::Measured as i32, + ..Default::default() + } +} + +/// A complete batch for one selected game. `expected_revision` is the series revision returned by +/// the previous batch (0 for the first). The host binds the game, installation, computer context +/// and producer; `game_id` here only has to match the selected target. +pub fn performance_batch( + context: &gamenode_plugin_sdk::proto::ServiceContext, + key: &str, + expected_revision: u64, + series_id: &str, + game_id: &str, + samples: Vec, +) -> PerformanceSamplesRequest { + PerformanceSamplesRequest { + mutation: Some(MutationContext { + context: Some(context.clone()), + operation_id: String::new(), + idempotency_key: key.into(), + expected_revision, + }), + series_id: series_id.into(), + game_id: game_id.into(), + samples, + runtime_id: "runtime:example".into(), + runtime_recipe_revision: "recipe-2".into(), + source: "overlay-frame-counter".into(), + tool_name: "Example overlay".into(), + tool_version: "2.0".into(), + sample_interval_ms: 100, + cpu_scope: PerformanceCpuScope::Process as i32, + cpu_normalization: PerformanceCpuNormalization::WholeMachinePercent as i32, + memory_kind: PerformanceMemoryKind::WorkingSetBytes as i32, + memory_source: "example-overlay".into(), + fps_unit: "frames/second".into(), + cpu_unit: "percent".into(), + memory_unit: "bytes".into(), + ..Default::default() + } +} + +pub async fn publish_performance( + host: &HostClient, + key: &str, + expected_revision: u64, + series_id: &str, + game_id: &str, + samples: Vec, +) -> Result { + let context = host + .resource_context() + .ok_or_else(|| Status::failed_precondition("the session has no resource context"))?; + host.resource_client() + .game_performance_publish_samples(performance_batch( + context, + key, + expected_revision, + series_id, + game_id, + samples, + )) + .await + .map(|reply| reply.into_inner()) +} + +/// Lists retained series in the caller's selected game scope. Without `selector` the common-data +/// path returns only the caller's own series; another plugin's history needs the explicit +/// performance-history category (or authorized record IDs) and a current grant. +pub async fn list_performance( + host: &HostClient, + game_id: &str, + selector: Option, + cursor: &str, + page_size: u32, +) -> Result { + let context = host + .resource_context() + .ok_or_else(|| Status::failed_precondition("the session has no resource context"))?; + host.game_performance_client() + .list(PerformanceListRequest { + page: Some(PageRequest { + context: Some(context.clone()), + cursor: cursor.into(), + page_size, + common_data_categories: selector, + }), + game_id: game_id.into(), + computer_context_id: LOCAL_COMPUTER.into(), + projection_id: PERFORMANCE_PROJECTION.into(), + }) + .await + .map(|reply| reply.into_inner()) +} + +/// Reads actual retained samples in a window. `resolution_ms = 0` keeps every sample; a larger +/// value selects actual observations only and never interpolates new points. +pub async fn query_performance( + host: &HostClient, + series_id: &str, + from_time: i64, + to_time: i64, + resolution_ms: u32, + selector: Option, +) -> Result { + let context = host + .resource_context() + .ok_or_else(|| Status::failed_precondition("the session has no resource context"))?; + host.game_performance_client() + .query_series(PerformanceQuerySeriesRequest { + context: Some(context.clone()), + series_id: series_id.into(), + from_time, + to_time, + resolution_ms, + page: Some(PageRequest { + context: Some(context.clone()), + page_size: 100, + ..Default::default() + }), + common_data_categories: selector, + }) + .await + .map(|reply| reply.into_inner()) +} + +/// Aggregates one metric over actual samples. `metric` is `fps`, `cpu_percent` or `memory_bytes`; +/// `aggregation` is `average`, `min`, `max` or a nearest-rank `p0`–`p100`. +pub async fn aggregate_performance( + host: &HostClient, + series_id: &str, + metric: &str, + aggregation: &str, + selector: Option, +) -> Result { + let context = host + .resource_context() + .ok_or_else(|| Status::failed_precondition("the session has no resource context"))?; + let now = 0; + host.game_performance_client() + .aggregate(PerformanceAggregateRequest { + context: Some(context.clone()), + series_id: series_id.into(), + from_time: now, + to_time: 0, + metric: metric.into(), + aggregation: aggregation.into(), + common_data_categories: selector, + }) + .await + .map(|reply| reply.into_inner()) +} + +/// Ends a series when the game stops. The host keeps the retained samples readable but refuses a +/// later batch with `FAILED_PRECONDITION`, so a stopped collector cannot quietly reopen history. +pub async fn end_performance( + host: &HostClient, + series_id: &str, + expected_revision: u64, + expected_last_sequence: u64, + ended_at: i64, +) -> Result { + let context = host + .resource_context() + .ok_or_else(|| Status::failed_precondition("the session has no resource context"))?; + host.resource_client() + .game_performance_end_series(PerformanceEndSeriesRequest { + mutation: Some(MutationContext { + context: Some(context.clone()), + operation_id: String::new(), + idempotency_key: gamenode_plugin_sdk::idempotency_key(), + expected_revision, + }), + series_id: series_id.into(), + ended_at, + expected_last_sequence, + }) + .await + .map(|reply| reply.into_inner()) +} + +/// Inspects an approved folder or runtime executable by its opaque handle. The answer describes +/// the approved scope with an opaque volume token; no field carries the folder's path. +pub async fn inspect_location( + host: &HostClient, + approved_resource_handle: &str, +) -> Result { + let context = host + .resource_context() + .ok_or_else(|| Status::failed_precondition("the session has no resource context"))?; + host.locations_client() + .inspect(LocationInspectRequest { + context: Some(context.clone()), + approved_resource_handle: approved_resource_handle.into(), + requested_dimensions: LOCATION_DIMENSIONS.iter().map(|d| (*d).into()).collect(), + max_entries: 100, + }) + .await + .map(|reply| reply.into_inner()) +} + +/// Measures the approved scope by metadata only. A missing or unreadable folder is reported through +/// `availability`, never as zero bytes. +pub async fn measure_location( + host: &HostClient, + approved_resource_handle: &str, +) -> Result { + let context = host + .resource_context() + .ok_or_else(|| Status::failed_precondition("the session has no resource context"))?; + host.locations_client() + .get_size(LocationSizeRequest { + context: Some(context.clone()), + approved_resource_handle: approved_resource_handle.into(), + max_entries: 0, + }) + .await + .map(|reply| reply.into_inner()) +} + +/// Lists save profiles for one of the caller's own games. `selector` is accepted on the wire, but +/// this build answers a common-category selector with `UNIMPLEMENTED`: save profiles stay +/// owner-only, and a plugin does not get another plugin's folders through a shared selector. +pub async fn list_save_profiles( + host: &HostClient, + installation_id: &str, + selector: Option, +) -> Result { + let context = host + .resource_context() + .ok_or_else(|| Status::failed_precondition("the session has no resource context"))?; + host.saves_client() + .list_profiles(SaveProfileListRequest { + context: Some(context.clone()), + game_id: String::new(), + installation_id: installation_id.into(), + cursor: String::new(), + page_size: 20, + shared_records: selector, + }) + .await + .map(|reply| reply.into_inner()) +} + +/// Reads one of the caller's own profiles. The approved folder is reported as a session-bound +/// handle; when the approval is gone the handle is empty and the profile keeps its metadata. +pub async fn read_save_profile( + host: &HostClient, + game_id: &str, + profile_id: &str, +) -> Result { + let context = host + .resource_context() + .ok_or_else(|| Status::failed_precondition("the session has no resource context"))?; + host.saves_client() + .get_profile(SaveProfileGetRequest { + context: Some(context.clone()), + game_id: game_id.into(), + profile_id: profile_id.into(), + shared_records: None, + }) + .await + .map(|reply| reply.into_inner()) +} + +/// Lists runtime records. With the explicit runtime-catalog category, the result includes other +/// plugins' runtimes as a shared projection: no executable handle, validated extension namespaces +/// and host-recorded producer provenance. Without a current grant the call is `PERMISSION_DENIED`. +pub async fn list_shared_runtimes(host: &HostClient) -> Result { + let context = host + .resource_context() + .ok_or_else(|| Status::failed_precondition("the session has no resource context"))?; + host.resource_client() + .runtimes_list(DomainListRequest { + page: Some(PageRequest { + context: Some(context.clone()), + page_size: 50, + common_data_categories: Some(category_selector(CommonDataCategory::RuntimeCatalog)), + ..Default::default() + }), + kind: "runtime".into(), + owner_filter: String::new(), + }) + .await + .map(|reply| reply.into_inner()) +} + +/// Reads one installation's safe content/runtime availability. Several content identities can +/// point at one shared runtime; each row carries content and runtime IDs, a display name and a +/// publisher, never a path, handle or payload. +pub async fn content_availability( + host: &HostClient, + installation_id: &str, +) -> Result { + let context = host + .resource_context() + .ok_or_else(|| Status::failed_precondition("the session has no resource context"))?; + host.resource_client() + .library_get(LibraryGetRequest { + context: Some(context.clone()), + game_id: String::new(), + installation_id: installation_id.into(), + common_data_categories: Some(category_selector( + CommonDataCategory::ContentAvailability, + )), + }) + .await + .map(|reply| reply.into_inner()) +} + +/// Retries a call that failed only because the transport was briefly unavailable. +pub async fn send_with_retry(mut call: F) -> Result +where + F: FnMut() -> Fut, + Fut: std::future::Future>, +{ + let mut last = Status::unavailable("nothing was sent"); + for attempt in 0..3 { + match call().await { + Err(status) + if matches!( + status.code(), + gamenode_plugin_sdk::Code::Unavailable + | gamenode_plugin_sdk::Code::DeadlineExceeded + ) => + { + last = status; + tokio::time::sleep(Duration::from_millis(200 << attempt)).await; + } + done => return done, + } + } + Err(last) +} + +fn main() {} diff --git a/crates/plugin-sdk/examples/extension_data_recipes.rs b/crates/plugin-sdk/examples/extension_data_recipes.rs new file mode 100644 index 000000000..da9362cad --- /dev/null +++ b/crates/plugin-sdk/examples/extension_data_recipes.rs @@ -0,0 +1,275 @@ +//! Hybrid typed records, versioned extension namespaces, and custom-data wire shapes. +//! +//! The typed runtime fields remain authoritative. Extension values are bounded annotations; an +//! older client should patch only the namespace it understands and carry every other namespace +//! forward unchanged. Both the Data service and the owner-only `RuntimesUpdate` namespace patch are +//! served by the desktop host; the host, not the client, assigns the next revision and validates +//! any packaged schema before committing. +#![allow(dead_code)] + +use std::collections::{BTreeMap, BTreeSet}; +use std::time::Duration; + +use gamenode_plugin_protocol::WireError; +use gamenode_plugin_sdk::{ + Durability, Resources, Status, extensions, idempotency_key, + prost_types::{Struct, Value, value::Kind}, + proto::{ + self, ExtensionNamespacePatch, ExtensionPatch, ExtensionPayload, RuntimeRecord, + StorageDurability, extension_namespace_patch::Operation, + }, +}; + +pub const KNOWN_NAMESPACE: &str = "org.example.runtime"; +pub const FUTURE_NAMESPACE: &str = "org.vendor.future-runtime"; +const RUNTIME_V1_SCHEMA: &[u8] = br#"{"type":"object","properties":{"display_family":{"type":"string"}},"additionalProperties":false}"#; +const FUTURE_RUNTIME_V9_SCHEMA: &[u8] = + br#"{"type":"object","properties":{"new_hint":{"type":"string"}},"additionalProperties":true}"#; +// SHA-256 of the exact schema JSON byte strings above. This SDK example intentionally does not +// add a separate crypto dependency just to calculate fixture constants at runtime. +const RUNTIME_V1_DIGEST: [u8; 32] = [ + 0xad, 0xff, 0x7d, 0x45, 0x8e, 0xcc, 0x45, 0x7a, 0x23, 0xb3, 0x57, 0x06, 0x07, 0x10, 0xc4, 0xa5, + 0x2a, 0xea, 0x4f, 0xf7, 0x28, 0x64, 0x8b, 0xa4, 0xab, 0xc6, 0x86, 0xdc, 0x3f, 0x21, 0x0d, 0xe3, +]; +const FUTURE_RUNTIME_V9_DIGEST: [u8; 32] = [ + 0xfe, 0x9e, 0x92, 0x61, 0xb9, 0x16, 0x4d, 0x56, 0x87, 0x30, 0xca, 0xac, 0x16, 0x91, 0x6d, 0x50, + 0xe9, 0x4b, 0xa8, 0x62, 0xad, 0xdd, 0x1b, 0xb9, 0x91, 0x5c, 0x30, 0x88, 0xf8, 0xf4, 0xef, 0x50, +]; + +fn object(fields: impl IntoIterator) -> Struct { + Struct { + fields: fields.into_iter().collect::>(), + } +} + +fn string(value: &str) -> Value { + Value { + kind: Some(Kind::StringValue(value.to_owned())), + } +} + +fn schema_fixture(schema_id: &str) -> (&'static [u8], &'static [u8; 32]) { + match schema_id { + "org.example.runtime.v1" => (RUNTIME_V1_SCHEMA, &RUNTIME_V1_DIGEST), + "org.vendor.future-runtime.v9" => (FUTURE_RUNTIME_V9_SCHEMA, &FUTURE_RUNTIME_V9_DIGEST), + _ => unreachable!("this example only declares its two fixture schemas"), + } +} + +fn payload(schema_id: &str, schema_version: u32, data: Struct) -> ExtensionPayload { + let (schema_json, schema_digest) = schema_fixture(schema_id); + debug_assert!(!schema_json.is_empty()); + ExtensionPayload { + schema_id: schema_id.to_owned(), + schema_version, + schema_digest: schema_digest.to_vec(), + data: Some(data), + } +} + +/// Typed fields such as identity, version, supported formats and revision stay outside `Struct`. +/// The future namespace is intentionally included so clients that do not understand it can +/// preserve it without interpreting it. +pub fn hybrid_runtime() -> RuntimeRecord { + RuntimeRecord { + id: "runtime:example".into(), + name: "Example Runtime".into(), + version: "2.4.1".into(), + executable_handle: "opaque-runtime-handle".into(), + supported_formats: vec!["rom.example".into()], + platform: std::env::consts::OS.into(), + extensions: [ + ( + KNOWN_NAMESPACE.into(), + payload( + "org.example.runtime.v1", + 1, + object([(String::from("display_family"), string("desktop"))]), + ), + ), + ( + FUTURE_NAMESPACE.into(), + payload( + "org.vendor.future-runtime.v9", + 9, + object([(String::from("new_hint"), string("preserve without parsing"))]), + ), + ), + ] + .into(), + revision: 7, + observed_at: 1_800_000_000, + ..Default::default() + } +} + +/// The revision-checked patch used by [`patch_known_runtime_namespace`]. Only the described +/// namespace and typed fields change; every other namespace is retained by the host. +pub fn known_namespace_patch(current_revision: u64) -> ExtensionPatch { + ExtensionPatch { + expected_revision: current_revision, + typed_field_mask: vec!["name".into()], + namespaces: vec![ExtensionNamespacePatch { + namespace: KNOWN_NAMESPACE.into(), + operation: Some(Operation::Set(payload( + "org.example.runtime.v1", + 1, + object([(String::from("display_family"), string("handheld"))]), + ))), + }], + } +} + +/// Build a revision-checked patch for only the namespace this client understands. The protocol +/// helper preserves the unknown namespace and host-owned fields, matching `RuntimesUpdate`. +pub fn patch_known_runtime_namespace(current: &RuntimeRecord) -> Result { + let patch = known_namespace_patch(current.revision); + let proposed = RuntimeRecord { + name: "Example Runtime (handheld)".into(), + ..current.clone() + }; + extensions::apply_runtime_patch(current, &proposed, &patch) +} + +/// A consumer may request only fields the host has authorized for its projection. This helper +/// illustrates the field shape; it does not create a grant or replace host-side projection. +pub fn project_display_family(record: &RuntimeRecord) -> Result { + let value = record + .extensions + .get(KNOWN_NAMESPACE) + .and_then(|extension| extension.data.as_ref()) + .ok_or(WireError)?; + extensions::project_struct_paths(value, &BTreeSet::from(["display_family".into()])) +} + +/// The signed descriptor for the namespace this client understands. The host resolves this from +/// the active package; an example builds it locally to show the shape. +pub fn known_descriptor() -> proto::ExtensionSchemaDescriptor { + proto::ExtensionSchemaDescriptor { + namespace: KNOWN_NAMESPACE.into(), + schema_id: "org.example.runtime.v1".into(), + schema_version: 1, + schema_digest: RUNTIME_V1_DIGEST.to_vec(), + schema_json: RUNTIME_V1_SCHEMA.to_vec(), + fields: vec![proto::ExtensionSchemaField { + path: "display_family".into(), + classification: proto::ExtensionFieldClassification::Public as i32, + }], + optional: true, + } +} + +/// Projects only the declared and granted fields of a known namespace. A shared catalog read +/// passes the recipient's current field grant; this helper performs structure, not authority. +pub fn project_known_namespace( + record: &RuntimeRecord, + granted: &BTreeSet, +) -> Result { + let payload = record.extensions.get(KNOWN_NAMESPACE).ok_or(WireError)?; + extensions::project_payload_fields(payload, &known_descriptor(), granted) +} + +/// A descriptor for a future schema version this client does not know. `schema_version` and +/// `schema_digest` are part of the identity: a v9 payload never validates against v1, and an +/// unsupported namespace is kept as an opaque envelope instead of being projected or rewritten. +pub fn future_descriptor() -> proto::ExtensionSchemaDescriptor { + proto::ExtensionSchemaDescriptor { + namespace: FUTURE_NAMESPACE.into(), + schema_id: "org.vendor.future-runtime.v9".into(), + schema_version: 9, + schema_digest: FUTURE_RUNTIME_V9_DIGEST.to_vec(), + schema_json: FUTURE_RUNTIME_V9_SCHEMA.to_vec(), + fields: vec![proto::ExtensionSchemaField { + path: "new_hint".into(), + classification: proto::ExtensionFieldClassification::Public as i32, + }], + optional: true, + } +} + +/// The explicit unsupported outcome: reading a future namespace with an older descriptor fails +/// schema validation. The caller must choose to carry the opacity forward, not interpret it. +pub fn reject_future_namespace(record: &RuntimeRecord) -> Result<(), WireError> { + let payload = record.extensions.get(FUTURE_NAMESPACE).ok_or(WireError)?; + extensions::validate_payload_for_schema(payload, &known_descriptor()) +} + +/// Keeps only the custom fields a consumer was granted. A `Struct` field carries data only; the +/// host's projection drops every ungranted key before the record leaves the broker. +pub fn project_custom_dataset( + value: &Struct, + granted: &BTreeSet, +) -> Result { + extensions::project_struct_paths(value, granted) +} + +/// The custom envelope uses a versioned dataset identity. A future `schema_version` is accepted +/// as an opaque label for custom records: Core does not interpret those fields, and a consumer +/// still sees only the fields its review grants. +pub fn custom_dataset_wire_shape_with_version(schema_version: u32) -> proto::DataPublishRequest { + let mut request = custom_dataset_wire_shape(); + request.schema_version = schema_version; + request +} + +/// The custom Data envelope carries a versioned Struct. This constructs a request only; send it +/// through the generated `ResourceHost` client with a session context and `data.publish` grant. +pub fn custom_dataset_wire_shape() -> proto::DataPublishRequest { + proto::DataPublishRequest { + mutation: None, + dataset_id: "org.example.game-notes".into(), + schema_id: "org.example.game-notes.v2".into(), + schema_version: 2, + value: Some(object([ + (String::from("game_key"), string("game:example")), + (String::from("note"), string("remember controller layout")), + ])), + durability: StorageDurability::SessionOnly as i32, + ttl_seconds: 86_400, + opaque_payload: Vec::new(), + resource_id: "game-notes-producer".into(), + observed_at: 1_800_000_000, + sequence: 1, + source_observation_id: "game-notes-observation-1".into(), + } +} + +/// Constructs an opaque custom-dataset publication. Consumers need an explicit +/// `opaque_payload` field grant to receive the bytes. +pub fn opaque_dataset_wire_shape() -> proto::DataPublishRequest { + proto::DataPublishRequest { + mutation: None, + dataset_id: "org.example.game-notes.binary".into(), + schema_id: "org.example.game-notes.binary.v1".into(), + schema_version: 1, + value: None, + durability: StorageDurability::SessionOnly as i32, + ttl_seconds: 86_400, + opaque_payload: vec![0, 1, 2, 255], + resource_id: "game-notes-producer".into(), + observed_at: 1_800_000_000, + sequence: 1, + source_observation_id: "game-notes-binary-observation-1".into(), + } +} + +/// Persistent opaque bytes remain private Storage data and need a separate persistence grant. +pub async fn keep_private_opaque_bytes( + resources: &Resources, + key: &str, + bytes: &[u8], +) -> Result { + let current = resources.storage_get(key).await?; + resources + .storage_put( + key, + current.revision, + &idempotency_key(), + bytes.to_vec(), + Durability::Persistent, + Some(Duration::from_secs(86_400)), + ) + .await +} + +fn main() {} diff --git a/crates/plugin-sdk/examples/library_recipes.rs b/crates/plugin-sdk/examples/library_recipes.rs new file mode 100644 index 000000000..bfb59802a --- /dev/null +++ b/crates/plugin-sdk/examples/library_recipes.rs @@ -0,0 +1,201 @@ +//! Practical recipes for the library resources: read, then write with the revision you read. +//! +//! These are plain functions over [`Resources`] (from `HostClient::resources()`); copy what you +//! need. They are compiled with the SDK and run against the desktop's fixture host in its service +//! tests, so they stay true to what the host does. Run `cargo doc` for the rules each call +//! follows; the permissions document explains every status code. +#![allow(dead_code)] + +use std::future::Future; +use std::time::Duration; + +use gamenode_plugin_sdk::{ + Code, Cover, Outcome, Resources, Status, Written, idempotency_key, proto::LibraryEvent, +}; + +/// How often a change is read again and retried after another writer got in first. +const ATTEMPTS: usize = 3; +/// How often one change is resent after a lost connection or timeout. +const SENDS: usize = 3; + +/// Sends one change, resending it **with the same key** if the connection fails or times out. The +/// host remembers a committed key, so an answer that was lost on the way back is returned again +/// instead of the change being applied twice. +pub async fn send(mut call: F) -> Result +where + F: FnMut() -> Fut, + Fut: Future>, +{ + let mut last = Status::unavailable("nothing was sent"); + for attempt in 0..SENDS { + match call().await { + Err(status) if matches!(status.code(), Code::Unavailable | Code::DeadlineExceeded) => { + last = status; + tokio::time::sleep(Duration::from_millis(200 << attempt)).await; + } + done => return done, + } + } + Err(last) +} + +/// Gives an own entry a display name (`None` restores the detected one). Reads the entry for its +/// `metadata_revision` and, if it changed in the meantime, reads it again: a conflict is an +/// answer, not an error. Every attempt is a new change, so it gets a new key. +pub async fn rename( + resources: &Resources, + installation_id: &str, + name: Option<&str>, +) -> Result { + for _ in 0..ATTEMPTS { + let entry = resources.library_get(installation_id).await?; + let key = idempotency_key(); + let written = send(|| { + resources.set_display_name(installation_id, entry.metadata_revision, &key, name) + }) + .await?; + if written.outcome != Outcome::RevisionConflict { + return Ok(written); + } + } + Err(Status::aborted("the entry kept changing; try again later")) +} + +/// Matches an own entry to the catalog game whose title is exactly `title` (ignoring case), if +/// the catalog has one. `Ok(None)` when nothing matches or the user already chose this entry's +/// game, which a plugin never overrides. +pub async fn match_by_title( + resources: &Resources, + installation_id: &str, + title: &str, +) -> Result, Status> { + let candidates = resources.search_catalog(title, 10).await?; + let Some(game) = candidates + .iter() + .find(|candidate| candidate.title.eq_ignore_ascii_case(title)) + else { + return Ok(None); + }; + for _ in 0..ATTEMPTS { + let entry = resources.library_get(installation_id).await?; + let key = idempotency_key(); + let result = + send(|| resources.assign_match(installation_id, &game.game_id, entry.revision, &key)) + .await; + match result { + Ok(written) if written.outcome == Outcome::RevisionConflict => {} + Ok(written) => return Ok(Some(written)), + // The user's own choice stands; there is nothing for a plugin to do. + Err(status) if status.code() == Code::FailedPrecondition => return Ok(None), + Err(status) => return Err(status), + } + } + Err(Status::aborted("the entry kept changing; try again later")) +} + +/// Uses `image` (static PNG, JPEG or WebP, at most 4 MiB) as the cover of an own entry, or +/// restores the game's cover with `None`. A refused image is `INVALID_ARGUMENT` with the reason. +pub async fn use_cover( + resources: &Resources, + installation_id: &str, + image: Option<(Vec, &str)>, +) -> Result { + for _ in 0..ATTEMPTS { + let entry = resources.library_get(installation_id).await?; + let key = idempotency_key(); + let written = send(|| async { + match &image { + Some((bytes, media_type)) => { + resources + .set_cover( + installation_id, + entry.artwork_revision, + &key, + bytes.clone(), + media_type, + ) + .await + } + None => { + resources + .clear_cover(installation_id, entry.artwork_revision, &key) + .await + } + } + }) + .await?; + if written.outcome != Outcome::RevisionConflict { + return Ok(written); + } + } + Err(Status::aborted("the entry kept changing; try again later")) +} + +/// The cover an own entry shows, if it has one on this device. Reading never downloads anything, +/// so `Ok(None)` just means "not yet". +pub async fn current_cover( + resources: &Resources, + installation_id: &str, +) -> Result, Status> { + match resources.read_cover(installation_id, 0).await { + Ok(cover) => Ok(Some(cover)), + Err(status) if status.code() == Code::NotFound => Ok(None), + Err(status) => Err(status), + } +} + +/// Stars every game one of the plugin's entries is matched to that is not starred yet, and +/// returns how many it starred. A favorite belongs to the game, so this never touches entries. +pub async fn star_matched_games(resources: &Resources) -> Result { + let starred = resources.favorite_games().await?; + let mut changed = 0; + for (game_id, favorite) in starred { + if favorite { + continue; + } + let key = idempotency_key(); + let written = send(|| resources.set_favorite(&game_id, true, &key)).await?; + if written.outcome == Outcome::Applied { + changed += 1; + } + } + Ok(changed) +} + +/// Keeps a view of the library current: a snapshot, then the changes after it. When the host no +/// longer retains the position (`FAILED_PRECONDITION`), list again and resume from the new +/// revision. `on_snapshot` receives the full list first and `on_event` each change after it; +/// `on_event` returns whether to keep following. +pub async fn follow_library( + resources: &Resources, + mut on_snapshot: S, + mut on_event: E, +) -> Result<(), Status> +where + S: FnMut(&[gamenode_plugin_sdk::proto::LibraryEntry]), + E: FnMut(LibraryEvent) -> bool, +{ + loop { + let snapshot = resources.library_snapshot("").await?; + on_snapshot(&snapshot.entries); + let mut events = match resources.library_watch("", snapshot.revision).await { + Ok(events) => events, + Err(status) if status.code() == Code::FailedPrecondition => continue, + Err(status) => return Err(status), + }; + loop { + match events.message().await { + Ok(Some(event)) => { + if !on_event(event) { + return Ok(()); + } + } + Ok(None) => return Ok(()), + Err(status) if status.code() == Code::FailedPrecondition => break, + Err(status) => return Err(status), + } + } + } +} + +fn main() {} diff --git a/crates/plugin-sdk/examples/utility_recipes.rs b/crates/plugin-sdk/examples/utility_recipes.rs new file mode 100644 index 000000000..c8fb6c305 --- /dev/null +++ b/crates/plugin-sdk/examples/utility_recipes.rs @@ -0,0 +1,335 @@ +//! Practical recipes for the utility services: private storage, files, network fetch and +//! notifications. +//! +//! These are plain functions over [`Resources`] (from `HostClient::resources()`); copy what you +//! need. They are compiled with the SDK and run against the desktop's fixture host in its service +//! tests, so they stay true to what the host does. Every refusal is the host's `tonic::Status`; +//! the permissions document explains each code. None of this is a sandbox: the services give a +//! plugin what the user approved through GameNode, and say nothing about what the plugin's own +//! process can do on the operating system. +#![allow(dead_code)] + +use std::future::Future; +use std::time::Duration; + +use gamenode_plugin_sdk::{ + Code, Durability, Fetch, Fetched, Notice, Outcome, Resources, Severity, Status, StoredWrite, + Written, declared_location, idempotency_key, proto::FileEntry, +}; + +/// How often a change is read again and retried after another writer got in first. +const ATTEMPTS: usize = 3; +/// How often one change is resent after a lost connection or timeout. +const SENDS: usize = 3; + +/// Sends one change, resending it **with the same key** if the connection fails or times out. +/// The host remembers a committed key, so an answer lost on the way back is returned again +/// instead of the change being applied twice. +pub async fn send(mut call: F) -> Result +where + F: FnMut() -> Fut, + Fut: Future>, +{ + let mut last = Status::unavailable("nothing was sent"); + for attempt in 0..SENDS { + match call().await { + Err(status) if matches!(status.code(), Code::Unavailable | Code::DeadlineExceeded) => { + last = status; + tokio::time::sleep(Duration::from_millis(200 << attempt)).await; + } + done => return done, + } + } + Err(last) +} + +// ---- Storage ---- + +/// Reads a small value you keep for yourself; `None` when it was never written, was deleted or +/// has expired. Storage is not encrypted: never keep a token or password here (use the provider +/// `Secret` service). +pub async fn recall(resources: &Resources, key: &str) -> Result>, Status> { + let stored = resources.storage_get(key).await?; + Ok(stored.found.then_some(stored.value)) +} + +/// Changes a stored value from what it was: reads it with its revision, applies `change`, and +/// writes the result with that revision. If someone else (another session of your plugin) +/// changed the key in between, the write is a conflict, so it reads again; `change` may +/// therefore run more than once and must not have side effects. Every attempt is a new change +/// and gets a new key; only a network retry of the same attempt reuses it. +/// +/// `RESOURCE_EXHAUSTED` means the layer is full and nothing was changed: free space (delete, or +/// store with a `ttl`) and try again. `PERMISSION_DENIED` with [`Durability::Persistent`] means +/// the user has not approved durable storage for the plugin; the host does not quietly store it +/// in memory, so ask for [`Durability::SessionOnly`] explicitly if that is acceptable. +pub async fn update( + resources: &Resources, + key: &str, + durability: Durability, + ttl: Option, + mut change: F, +) -> Result +where + F: FnMut(Option>) -> Vec, +{ + for _ in 0..ATTEMPTS { + let stored = resources.storage_get(key).await?; + let next = change(stored.found.then_some(stored.value)); + let write_key = idempotency_key(); + let written = send(|| { + resources.storage_put( + key, + stored.revision, + &write_key, + next.clone(), + durability, + ttl, + ) + }) + .await?; + if written.outcome != Outcome::RevisionConflict { + return Ok(written); + } + } + Err(Status::aborted("the value kept changing; try again later")) +} + +/// Forgets a key. Deleting what is not there succeeds (`Outcome::AlreadyApplied`). The revision +/// is read first so a delete does not remove a value another session just wrote. +pub async fn forget(resources: &Resources, key: &str) -> Result { + for _ in 0..ATTEMPTS { + let stored = resources.storage_get(key).await?; + let delete_key = idempotency_key(); + let written = send(|| resources.storage_delete(key, stored.revision, &delete_key)).await?; + if written.outcome != Outcome::RevisionConflict { + return Ok(written); + } + } + Err(Status::aborted("the value kept changing; try again later")) +} + +// ---- Files ---- + +/// What went wrong asking for a folder, in terms a plugin acts on. +#[derive(Debug)] +pub enum Access { + /// The user did not approve (or the plugin lacks the grant). Do not ask again at once: + /// explain what the plugin needs the folder for first. + Declined, + /// The handles are no longer valid; ask again. + AskAgain, + Other(Status), +} + +/// Asks for read access to the installation folder of one of your own entries and returns its +/// root handle. The user chooses and confirms the folder in GameNode; you never see its path. +/// Ask for `write` only when you need to write: a read-only approval gives no write. +pub async fn open_installation( + resources: &Resources, + installation_id: &str, + operations: &[&str], +) -> Result { + let key = idempotency_key(); + match send(|| resources.files_request_access(installation_id, operations, &[], &key)).await { + Ok(handles) => handles + .into_iter() + .next() + .map(|handle| handle.handle) + .ok_or(Access::Declined), + Err(status) => Err(match status.code() { + Code::PermissionDenied => Access::Declined, + Code::FailedPrecondition => Access::AskAgain, + _ => Access::Other(status), + }), + } +} + +/// Asks for read access to the folder where one of your own entries keeps its saves, telling +/// GameNode where that usually is on each platform. The user sees these as folders **you** +/// suggested (not verified), takes one or chooses another, and you never learn which. Put the +/// most likely folder first; a suggestion for another system is ignored without an error, so one +/// list serves every platform. Ask for `read` first, check the files with the handle, and ask +/// for `write` only when you must write. +pub async fn open_save_folder( + resources: &Resources, + installation_id: &str, +) -> Result { + let declared = [ + declared_location("save", "{documents}/My Games/Portal/Saves", "Documents"), + declared_location( + "save", + "{localappdata}/Portal/Saves", + "Local application data", + ), + declared_location("save", "{xdg_data}/portal/saves", "XDG data folder"), + declared_location("save", "{home}/.portal/saves", "Home folder"), + ]; + let key = idempotency_key(); + match send(|| { + resources.files_request_access_with(installation_id, &["read"], &["save"], &declared, &key) + }) + .await + { + Ok(handles) => handles + .into_iter() + .next() + .map(|handle| handle.handle) + .ok_or(Access::Declined), + Err(status) => Err(match status.code() { + Code::PermissionDenied => Access::Declined, + Code::FailedPrecondition => Access::AskAgain, + _ => Access::Other(status), + }), + } +} + +/// Finds the entry called `name` directly inside a directory handle. +pub async fn find( + resources: &Resources, + directory: &str, + name: &str, +) -> Result, Status> { + Ok(resources + .files_list(directory) + .await? + .into_iter() + .find(|entry| entry.name == name)) +} + +/// Reads a file of `directory` by name, at most `limit` bytes; `Ok(None)` when it is not there. +/// A longer file is `RESOURCE_EXHAUSTED` rather than read in part. +pub async fn read_named( + resources: &Resources, + directory: &str, + name: &str, + limit: u64, +) -> Result>, Status> { + let Some(entry) = find(resources, directory, name).await? else { + return Ok(None); + }; + if entry.directory { + return Ok(None); + } + resources + .files_read_all(&entry.handle, limit) + .await + .map(Some) +} + +/// Writes (creating or replacing) the file `name` in a directory the user approved for `write`. +/// The name must be one plain component that is valid on every platform, so a file made on +/// Linux can be backed up on Windows. Returns the new file's handle. +pub async fn save_named( + resources: &Resources, + directory: &str, + name: &str, + contents: &[u8], +) -> Result { + let key = idempotency_key(); + let written = send(|| resources.files_create(directory, name, contents.to_vec(), &key)).await?; + Ok(written.resource_id) +} + +// ---- Network ---- + +/// What a fetch tells a plugin to do next. +#[derive(Debug)] +pub enum FetchFailure { + /// The origin is not one the user approved, or the server sent the fetch somewhere that is + /// not approved. Nothing says where. Ask the user to approve the origin you need. + NotApproved, + /// The host is busy (too many fetches at once) or the response was over the budget you set. + /// Retry later for the former; raise `max_response_bytes` (up to 8 MiB) for the latter. + Busy(Status), + Other(Status), +} + +/// Fetches `url` (https, an origin the user approved) and returns the answer whatever its HTTP +/// status: a 404 is a normal answer. The host never sends a GameNode credential; add your own +/// `Authorization` header when your service needs one. The deadline covers redirects too. +pub async fn fetch_bytes( + resources: &Resources, + url: &str, + budget_bytes: u64, +) -> Result { + let fetch = Fetch::get(url) + .header("Accept", "application/json") + .max_response_bytes(budget_bytes) + .timeout(Duration::from_secs(10)); + resources + .network_fetch(&fetch) + .await + .map_err(|status| match status.code() { + Code::PermissionDenied => FetchFailure::NotApproved, + Code::ResourceExhausted => FetchFailure::Busy(status), + _ => FetchFailure::Other(status), + }) +} + +// ---- Notifications ---- + +/// How long the host asked to wait, from a `RESOURCE_EXHAUSTED` answer. +pub fn retry_after(status: &Status) -> Option { + status + .metadata() + .get("retry-after-ms")? + .to_str() + .ok()? + .parse() + .map(Duration::from_millis) + .ok() +} + +/// Tells the user something in their language, as plain text from your plugin. GameNode picks +/// the translation that matches, then the same language without a region, then the main text. +/// Returns `Ok(false)` when the rate limit (5 a minute) says to wait; drop the notice or merge +/// it with the next one rather than queueing a burst. A retry after a lost answer reuses the key +/// and does not show the notice twice. +pub async fn tell_user( + resources: &Resources, + english: (&str, &str), + portuguese: (&str, &str), + severity: Severity, +) -> Result { + let notice = Notice::new("en", english.0) + .body(english.1) + .severity(severity) + .translation("pt-BR", portuguese.0, portuguese.1); + let key = idempotency_key(); + match send(|| resources.notify(¬ice, &key)).await { + Ok(_) => Ok(true), + Err(status) if status.code() == Code::ResourceExhausted => Ok(false), + Err(status) => Err(status), + } +} + +// ---- Put together (the examples of the development guide) ---- + +/// Counts a launch in a value that survives restarts. It reads the value and its revision, +/// writes with that revision, and reads again after a conflict. +pub async fn count_launch(resources: &Resources) -> Result<(), Status> { + update(resources, "launches", Durability::Persistent, None, |old| { + let count = old + .and_then(|bytes| String::from_utf8(bytes).ok()) + .and_then(|text| text.parse::().ok()) + .unwrap_or(0); + (count + 1).to_string().into_bytes() + }) + .await + .map(|_| ()) +} + +/// Reads a save file of one of your own entries. The user chooses and confirms the folder in +/// GameNode and you never see a path; ask for `read` first and for `write` only when you need it. +pub async fn read_slot( + resources: &Resources, + installation_id: &str, +) -> Result>, Status> { + let Ok(root) = open_installation(resources, installation_id, &["read"]).await else { + return Ok(None); // declined or not available yet: carry on without it + }; + read_named(resources, &root, "slot1.sav", 1 << 20).await +} + +fn main() {} diff --git a/crates/plugin-sdk/src/actions.rs b/crates/plugin-sdk/src/actions.rs new file mode 100644 index 000000000..b63aaf9cb --- /dev/null +++ b/crates/plugin-sdk/src/actions.rs @@ -0,0 +1,465 @@ +//! Convenience calls for the host action services of API 1.6: launch/install, backups, +//! host-catalog tools and ports, and the jobs they return. +//! +//! Each method sends exactly the request a hand-written raw `ResourceHost` call would and returns +//! the host's answer unchanged, so the two are interchangeable. The helpers add no authority: +//! they use the session's `resource_context`, and the host still checks every grant, scope, +//! revision, confirmation and job ownership. +//! +//! Action services answer with a job. The user may have to confirm the operation in Core first: +//! the job stays `QUEUED` with the message `awaiting confirmation` until the dialog closes. +//! [`Actions::job`], [`Actions::watch_job`] and [`Actions::cancel_job`] follow or withdraw it. +//! Revoking the operation's permission while the dialog is open makes the job fail without +//! committing anything; see `docs/plugin-development.md`. + +use tonic::{Status, Streaming}; + +use crate::proto::resource_host_client::ResourceHostClient; +use crate::proto::*; +use crate::{MAX_MESSAGE_BYTES, SERVICE_TIMEOUT}; + +/// How many times a list restarts when its cursor goes stale because the host's observations +/// changed under the walk. +const LIST_RESTARTS: usize = 3; + +fn timed(message: T) -> tonic::Request { + let mut request = tonic::Request::new(message); + request.set_timeout(SERVICE_TIMEOUT); + request +} + +/// Typed access to the action services, bound to one session's `resource_context`. Get it from +/// [`HostClient::actions`](crate::HostClient::actions). Cheap to clone. +#[derive(Clone)] +pub struct Actions { + pub(crate) client: ResourceHostClient, + pub(crate) context: ServiceContext, +} + +impl Actions { + pub(crate) fn new(channel: tonic::transport::Channel, context: ServiceContext) -> Self { + Self { + client: ResourceHostClient::new(channel) + .max_decoding_message_size(MAX_MESSAGE_BYTES) + .max_encoding_message_size(MAX_MESSAGE_BYTES), + context, + } + } + + fn mutation(&self, key: &str, expected_revision: u64) -> MutationContext { + MutationContext { + context: Some(self.context.clone()), + operation_id: String::new(), + idempotency_key: key.to_owned(), + expected_revision, + } + } + + fn page(&self, page_size: u32, cursor: &str) -> PageRequest { + PageRequest { + context: Some(self.context.clone()), + cursor: cursor.to_owned(), + page_size, + common_data_categories: None, + } + } + + // ---- Launch and install (`game.launch`, `games.install`) ---- + + /// Asks the host to start an installed game through its detected target. `expected_revision` + /// is the entry's `revision`; `installation_id` may be empty when the extension's + /// host-selected target is the game. Leave `user_intent_id` empty to let Core ask the user; + /// a host-issued intent from a Core action skips the dialog. The answer is a job. + pub async fn launch_game( + &self, + game_id: &str, + installation_id: &str, + expected_revision: u64, + user_intent_id: &str, + idempotency_key: &str, + ) -> Result { + self.client + .clone() + .games_request_launch(timed(GameLaunchRequest { + context: Some(self.context.clone()), + game_id: game_id.to_owned(), + installation_id: installation_id.to_owned(), + expected_revision, + user_intent_id: user_intent_id.to_owned(), + idempotency_key: idempotency_key.to_owned(), + })) + .await + .map(tonic::Response::into_inner) + } + + /// Asks the host to open the provider's install flow for a game. The user confirms in Core + /// unless a host-issued `user_intent_id` is given. The answer is a job. + pub async fn install_game( + &self, + game_id: &str, + installation_id: &str, + user_intent_id: &str, + idempotency_key: &str, + ) -> Result { + self.client + .clone() + .games_request_install(timed(GameInstallRequest { + context: Some(self.context.clone()), + game_id: game_id.to_owned(), + installation_id: installation_id.to_owned(), + user_intent_id: user_intent_id.to_owned(), + idempotency_key: idempotency_key.to_owned(), + })) + .await + .map(tonic::Response::into_inner) + } + + // ---- Jobs (`JobsGet`, `JobsWatch`, `JobsCancel`) ---- + + /// One job of this plugin and profile. `NOT_FOUND` means it is not yours or it is gone. + pub async fn job(&self, job_id: &str) -> Result { + self.client + .clone() + .jobs_get(timed(JobGetRequest { + context: Some(self.context.clone()), + job_id: job_id.to_owned(), + })) + .await + .map(tonic::Response::into_inner) + } + + /// The job's events in order, starting after `after_sequence` (0: from the beginning). The + /// stream ends after the terminal state. No request timeout is applied, because a job may + /// wait for the user's confirmation. + pub async fn watch_job( + &self, + job_id: &str, + after_sequence: u64, + ) -> Result, Status> { + self.client + .clone() + .jobs_watch(JobWatchRequest { + context: Some(self.context.clone()), + job_id: job_id.to_owned(), + after_sequence, + }) + .await + .map(tonic::Response::into_inner) + } + + /// Asks to stop a job. `CANCELLED` in the reply means it stopped; `RUNNING` means the work + /// cannot stop halfway and will report what it finally did. + pub async fn cancel_job( + &self, + job_id: &str, + idempotency_key: &str, + ) -> Result { + self.client + .clone() + .jobs_cancel(timed(JobCancelRequest { + mutation: Some(self.mutation(idempotency_key, 0)), + job_id: job_id.to_owned(), + })) + .await + .map(tonic::Response::into_inner) + } + + // ---- Backups (`backups.read`, `backups.create`, `backups.restore`) ---- + + /// One page of backup history for an approved game and save profile. + pub async fn backup_page( + &self, + game_id: &str, + profile_id: &str, + page_size: u32, + cursor: &str, + ) -> Result { + self.client + .clone() + .backups_list(timed(BackupsListRequest { + page: Some(self.page(page_size, cursor)), + game_id: game_id.to_owned(), + profile_id: profile_id.to_owned(), + })) + .await + .map(tonic::Response::into_inner) + } + + /// Every retained backup of an approved game and save profile, following the cursors. A + /// stale cursor restarts the walk, up to three times. + pub async fn backups( + &self, + game_id: &str, + profile_id: &str, + ) -> Result, Status> { + let mut restarts = 0; + 'again: loop { + let mut backups = Vec::new(); + let mut cursor = String::new(); + loop { + match self + .backup_page( + game_id, + profile_id, + crate::resources::MAX_PAGE_SIZE, + &cursor, + ) + .await + { + Ok(page) => { + backups.extend(page.backups); + if page.next_cursor.is_empty() { + return Ok(backups); + } + cursor = page.next_cursor; + } + Err(status) + if status.code() == tonic::Code::FailedPrecondition + && !cursor.is_empty() + && restarts < LIST_RESTARTS => + { + restarts += 1; + continue 'again; + } + Err(status) => return Err(status), + } + } + } + } + + /// Requests a backup of an approved save profile. `expected_revision` is the profile's + /// revision. The answer is a job; a restore confirmation is only for restore. + pub async fn create_backup( + &self, + game_id: &str, + profile_id: &str, + reason: &str, + expected_revision: u64, + idempotency_key: &str, + ) -> Result { + self.client + .clone() + .backups_request_create(timed(BackupCreateRequest { + mutation: Some(self.mutation(idempotency_key, expected_revision)), + game_id: game_id.to_owned(), + profile_id: profile_id.to_owned(), + reason: reason.to_owned(), + })) + .await + .map(tonic::Response::into_inner) + } + + /// Requests a restore of one retained backup. Core shows its own restore confirmation, so + /// `user_intent_id` stays empty. The answer is a job. + pub async fn restore_backup( + &self, + backup_id: &str, + game_id: &str, + profile_id: &str, + expected_revision: u64, + idempotency_key: &str, + ) -> Result { + self.client + .clone() + .backups_request_restore(timed(BackupRestoreRequest { + mutation: Some(self.mutation(idempotency_key, expected_revision)), + backup_id: backup_id.to_owned(), + game_id: game_id.to_owned(), + profile_id: profile_id.to_owned(), + user_intent_id: String::new(), + })) + .await + .map(tonic::Response::into_inner) + } + + // ---- Host-catalog tools (`tools.read`, `tools.apply`, `tools.remove`) ---- + + /// One page of the host tool catalog. `game_id` scopes the catalog and its availability to + /// one installed game; empty lists the built-in catalog. + pub async fn tool_page( + &self, + game_id: &str, + platform: &str, + page_size: u32, + cursor: &str, + ) -> Result { + self.client + .clone() + .tools_list(timed(ToolsListRequest { + page: Some(self.page(page_size, cursor)), + game_id: game_id.to_owned(), + platform: platform.to_owned(), + })) + .await + .map(tonic::Response::into_inner) + } + + /// Every tool in the catalog for `game_id` and `platform`, following the cursors. A stale + /// cursor restarts the walk, up to three times. + pub async fn tools(&self, game_id: &str, platform: &str) -> Result, Status> { + let mut restarts = 0; + 'again: loop { + let mut tools = Vec::new(); + let mut cursor = String::new(); + loop { + match self + .tool_page(game_id, platform, crate::resources::MAX_PAGE_SIZE, &cursor) + .await + { + Ok(page) => { + tools.extend(page.tools); + if page.next_cursor.is_empty() { + return Ok(tools); + } + cursor = page.next_cursor; + } + Err(status) + if status.code() == tonic::Code::FailedPrecondition + && !cursor.is_empty() + && restarts < LIST_RESTARTS => + { + restarts += 1; + continue 'again; + } + Err(status) => return Err(status), + } + } + } + } + + /// Requests the host-catalog tool's apply/update on one installed game. `expected_revision` + /// is the entry's `revision`; the host opens its own review. The answer is a job. + pub async fn apply_tool( + &self, + tool_id: &str, + game_id: &str, + expected_revision: u64, + idempotency_key: &str, + ) -> Result { + self.client + .clone() + .tools_request_apply(timed(ToolApplyRequest { + mutation: Some(self.mutation(idempotency_key, expected_revision)), + tool_id: tool_id.to_owned(), + game_id: game_id.to_owned(), + user_intent_id: String::new(), + })) + .await + .map(tonic::Response::into_inner) + } + + /// Requests removal of an installed host-catalog tool from one game. The answer is a job. + pub async fn remove_tool( + &self, + tool_id: &str, + game_id: &str, + expected_revision: u64, + idempotency_key: &str, + ) -> Result { + self.client + .clone() + .tools_request_remove(timed(ToolRemoveRequest { + mutation: Some(self.mutation(idempotency_key, expected_revision)), + tool_id: tool_id.to_owned(), + game_id: game_id.to_owned(), + user_intent_id: String::new(), + })) + .await + .map(tonic::Response::into_inner) + } + + // ---- Host-catalog PC ports (`ports.read`, `ports.install`) ---- + + /// One page of the host port catalog, optionally filtered by platform and a case-insensitive + /// name query. + pub async fn port_page( + &self, + platform: &str, + query: &str, + page_size: u32, + cursor: &str, + ) -> Result { + self.client + .clone() + .ports_list(timed(PortsListRequest { + page: Some(self.page(page_size, cursor)), + platform: platform.to_owned(), + query: query.to_owned(), + })) + .await + .map(tonic::Response::into_inner) + } + + /// Every host port matching the filter, following the cursors. A stale cursor restarts the + /// walk, up to three times. + pub async fn ports(&self, platform: &str, query: &str) -> Result, Status> { + let mut restarts = 0; + 'again: loop { + let mut ports = Vec::new(); + let mut cursor = String::new(); + loop { + match self + .port_page(platform, query, crate::resources::MAX_PAGE_SIZE, &cursor) + .await + { + Ok(page) => { + ports.extend(page.ports); + if page.next_cursor.is_empty() { + return Ok(ports); + } + cursor = page.next_cursor; + } + Err(status) + if status.code() == tonic::Code::FailedPrecondition + && !cursor.is_empty() + && restarts < LIST_RESTARTS => + { + restarts += 1; + continue 'again; + } + Err(status) => return Err(status), + } + } + } + } + + /// One host port by its catalog id. + pub async fn port(&self, port_id: &str) -> Result { + let reply = self + .client + .clone() + .ports_detail(timed(PortDetailRequest { + context: Some(self.context.clone()), + port_id: port_id.to_owned(), + })) + .await? + .into_inner(); + reply + .port + .ok_or_else(|| Status::not_found("port not found")) + } + + /// Requests installation of a host-catalog port. `expected_revision` is the source game's + /// entry revision, or 0 for a new catalog install; `supplied_file_handles` are optional + /// approved Files candidates that need `files.read`. The host opens its own setup and review. + pub async fn install_port( + &self, + port_id: &str, + game_id: &str, + supplied_file_handles: Vec, + expected_revision: u64, + idempotency_key: &str, + ) -> Result { + self.client + .clone() + .ports_request_install(timed(PortInstallRequest { + mutation: Some(self.mutation(idempotency_key, expected_revision)), + port_id: port_id.to_owned(), + game_id: game_id.to_owned(), + supplied_file_handles, + user_intent_id: String::new(), + })) + .await + .map(tonic::Response::into_inner) + } +} diff --git a/crates/plugin-sdk/src/lib.rs b/crates/plugin-sdk/src/lib.rs index 2d4c3cecd..9a68ca26d 100644 --- a/crates/plugin-sdk/src/lib.rs +++ b/crates/plugin-sdk/src/lib.rs @@ -3,16 +3,109 @@ use std::path::{Path, PathBuf}; use std::time::Duration; -pub use gamenode_plugin_protocol::{achievements, capability, models, proto, settings}; +pub use gamenode_plugin_protocol::{ + achievements, capability, extensions, models, prost_types, proto, settings, +}; use proto::{plugin_host_client::PluginHostClient, provider_host_client::ProviderHostClient, *}; use tokio::sync::mpsc; use tokio_stream::wrappers::ReceiverStream; use tonic::transport::{Channel, Endpoint}; +pub mod actions; +pub mod resources; +pub mod utilities; + +pub use actions::Actions; +pub use resources::{ + Cover, CustomLaunchRecipe, LibrarySnapshot, Outcome, Resources, RuntimeArgumentTemplate, + RuntimeContentBinding, RuntimeSpec, Written, idempotency_key, +}; +pub use tonic::{Code, Status}; +pub use utilities::{ + Durability, Fetch, Fetched, Notice, Severity, StoredValue, StoredWrite, declared_location, +}; + pub const MAX_MESSAGE_BYTES: usize = 8 * 1024 * 1024; pub const EVENT_QUEUE: usize = 32; const SERVICE_TIMEOUT: Duration = Duration::from_secs(15); +/// Build an explicit, typed per-query category selector. An empty iterator is +/// valid and means private/owner-visible records only. The host still checks +/// the matching activation grant and its scope for every query. +pub fn common_data_selector( + categories: impl IntoIterator, +) -> Result { + let selector = CommonDataSelector { + categories: categories + .into_iter() + .map(|category| category as i32) + .collect(), + ..Default::default() + }; + gamenode_plugin_protocol::common_data::categories(Some(&selector))?; + Ok(selector) +} + +/// Build a selector for explicitly granted published records without asking +/// for category-wide access. The host must authorize every id independently. +pub fn selected_record_selector( + record_ids: impl IntoIterator>, +) -> Result { + let selector = CommonDataSelector { + selected_record_ids: record_ids.into_iter().map(Into::into).collect(), + ..Default::default() + }; + gamenode_plugin_protocol::common_data::selected_record_ids(Some(&selector))?; + Ok(selector) +} + +/// Build a selector combining category-wide and selected-record grants. +pub fn common_data_selector_with_records( + categories: impl IntoIterator, + record_ids: impl IntoIterator>, +) -> Result { + let mut selector = common_data_selector(categories)?; + selector.selected_record_ids = record_ids.into_iter().map(Into::into).collect(); + gamenode_plugin_protocol::common_data::selected_record_ids(Some(&selector))?; + Ok(selector) +} + +#[cfg(test)] +mod common_data_selector_tests { + use super::*; + + #[test] + fn selector_is_explicit_and_empty_means_private_only() { + let private = common_data_selector([]).unwrap(); + assert!(private.categories.is_empty()); + assert!(private.selected_record_ids.is_empty()); + + let selected = common_data_selector([ + CommonDataCategory::GamePaths, + CommonDataCategory::GamePerformanceHistory, + ]) + .unwrap(); + assert_eq!( + selected.categories, + vec![ + CommonDataCategory::GamePaths as i32, + CommonDataCategory::GamePerformanceHistory as i32, + ] + ); + + let selected_records = selected_record_selector(["runtime:one", "save:two"]).unwrap(); + assert!(selected_records.categories.is_empty()); + assert_eq!( + selected_records.selected_record_ids, + ["runtime:one", "save:two"] + ); + assert!( + common_data_selector([CommonDataCategory::GamePaths, CommonDataCategory::GamePaths,]) + .is_err() + ); + } +} + #[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)] pub enum Error { #[error("plugin launch configuration is invalid")] @@ -42,6 +135,45 @@ impl From for Error { } } +/// Opt-in detailed status classification. The legacy [`Error`] conversion is +/// unchanged so existing official plugins retain their matching behavior. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum DetailedError { + Denied(Option), + Unauthenticated, + Stale, + Unsupported, + Invalid, + Unavailable, + Protocol, +} + +impl From<&tonic::Status> for DetailedError { + fn from(status: &tonic::Status) -> Self { + use gamenode_plugin_protocol::StatusKind as K; + match gamenode_plugin_protocol::classify_status(status.code()) { + K::Denied => Self::Denied(status.details().get(..).and_then(|bytes| { + // The status detail payload uses a length-delimited protobuf + // DenialDetail. Malformed/absent details remain a plain denial. + use gamenode_plugin_protocol::prost::Message; + DenialDetail::decode(bytes).ok() + })), + K::Unauthenticated => Self::Unauthenticated, + K::Stale => Self::Stale, + K::Unsupported => Self::Unsupported, + K::Invalid => Self::Invalid, + K::Unavailable => Self::Unavailable, + K::Protocol => Self::Protocol, + } + } +} + +impl DetailedError { + pub fn from_status(status: &tonic::Status) -> Self { + status.into() + } +} + impl From for Error { fn from(_: gamenode_plugin_protocol::WireError) -> Self { Self::Protocol @@ -55,7 +187,59 @@ pub struct Launch { pub operation_id: String, } +#[derive(Clone, Debug)] +pub struct SessionOptions { + pub min_api_major: u32, + pub min_api_minor: u32, + pub max_api_major: u32, + pub max_api_minor: u32, + pub features: Vec<(String, bool)>, + pub session_kind: SessionKind, + pub target_game: Option, +} + +impl Default for SessionOptions { + fn default() -> Self { + Self { + min_api_major: 0, + min_api_minor: 0, + max_api_major: 0, + max_api_minor: 0, + features: Vec::new(), + session_kind: SessionKind::Unspecified, + target_game: None, + } + } +} + impl Launch { + /// The opaque, host-issued user intent for a Core-started extension action, if present. + /// Provider sessions and extensions started outside that Core action have no intent. + pub fn user_intent_id(&self) -> Option { + std::env::var("GAMENODE_PLUGIN_USER_INTENT_ID") + .ok() + .filter(|id| !id.is_empty()) + } + + /// The target Core selected for a one-shot extension session, if present. The host still + /// verifies this exact value during `OpenSession`; editing environment values cannot widen it. + pub fn selected_target(&self) -> Option { + Some(TargetGameContext { + game_id: std::env::var("GAMENODE_PLUGIN_TARGET_GAME_ID") + .ok() + .filter(|value| !value.is_empty())?, + installation_id: std::env::var("GAMENODE_PLUGIN_TARGET_INSTALLATION_ID") + .ok() + .filter(|value| !value.is_empty())?, + profile_id: std::env::var("GAMENODE_PLUGIN_TARGET_PROFILE_ID") + .ok() + .filter(|value| !value.is_empty())?, + revision: std::env::var("GAMENODE_PLUGIN_TARGET_REVISION") + .ok() + .filter(|value| !value.is_empty())?, + }) + } + pub fn from_env() -> Result { let endpoint = std::env::var_os("GAMENODE_PLUGIN_ENDPOINT") .or_else(|| std::env::var_os("GAMENODE_PLUGIN_SOCKET")) @@ -115,10 +299,13 @@ pub async fn connect(endpoint: &Path) -> Result { #[derive(Clone)] pub struct HostClient { client: ProviderHostClient, + channel: Channel, context: ServiceContext, events: mpsc::Sender, plugin_id: std::sync::Arc, settings_supported: bool, + configure_supported: bool, + resource_context: Option, } fn request(message: T) -> tonic::Request { @@ -128,25 +315,158 @@ fn request(message: T) -> tonic::Request { } impl HostClient { + /// Raw generated client for the API 1.6 resource surface. It remains bound + /// to the same local authenticated channel; callers provide scoped request + /// contexts explicitly so the SDK adds no authority implicitly. + pub fn resource_client(&self) -> proto::resource_host_client::ResourceHostClient { + proto::resource_host_client::ResourceHostClient::new(self.channel.clone()) + .max_decoding_message_size(MAX_MESSAGE_BYTES) + .max_encoding_message_size(MAX_MESSAGE_BYTES) + } + + /// The raw client of the `Saves` service (save profiles contributed by plugins). Like + /// [`resource_client`](Self::resource_client), callers put the session's resource context in + /// each request; the SDK adds no authority. + pub fn saves_client(&self) -> proto::saves_client::SavesClient { + proto::saves_client::SavesClient::new(self.channel.clone()) + .max_decoding_message_size(MAX_MESSAGE_BYTES) + .max_encoding_message_size(MAX_MESSAGE_BYTES) + } + + /// The raw client of the `Locations` service (inspection of approved places). Like + /// [`resource_client`](Self::resource_client), callers put the session's resource context in + /// each request; the SDK adds no authority. + pub fn locations_client(&self) -> proto::locations_client::LocationsClient { + proto::locations_client::LocationsClient::new(self.channel.clone()) + .max_decoding_message_size(MAX_MESSAGE_BYTES) + .max_encoding_message_size(MAX_MESSAGE_BYTES) + } + + /// The raw client of the `StorageDiagnostics` service. Calls still require the session's + /// resource context and the corresponding host-reviewed permission. + pub fn storage_diagnostics_client( + &self, + ) -> proto::storage_diagnostics_client::StorageDiagnosticsClient { + proto::storage_diagnostics_client::StorageDiagnosticsClient::new(self.channel.clone()) + .max_decoding_message_size(MAX_MESSAGE_BYTES) + .max_encoding_message_size(MAX_MESSAGE_BYTES) + } + + /// The raw client of the `Computer` service (sensitive hardware observations). Calls still + /// require the session's resource context and the corresponding host-reviewed permission. + pub fn computer_client(&self) -> proto::computer_client::ComputerClient { + proto::computer_client::ComputerClient::new(self.channel.clone()) + .max_decoding_message_size(MAX_MESSAGE_BYTES) + .max_encoding_message_size(MAX_MESSAGE_BYTES) + } + + /// The raw client of the `GamePresence` service (expiring game/session status). Calls still + /// require the session's resource context and the corresponding host-reviewed permission. + pub fn game_presence_client(&self) -> proto::game_presence_client::GamePresenceClient { + proto::game_presence_client::GamePresenceClient::new(self.channel.clone()) + .max_decoding_message_size(MAX_MESSAGE_BYTES) + .max_encoding_message_size(MAX_MESSAGE_BYTES) + } + + /// The raw client of the `GamePerformance` service (retained FPS/CPU/RAM observations). + /// Calls require the session's resource context and the corresponding read permission. + pub fn game_performance_client( + &self, + ) -> proto::game_performance_client::GamePerformanceClient { + proto::game_performance_client::GamePerformanceClient::new(self.channel.clone()) + .max_decoding_message_size(MAX_MESSAGE_BYTES) + .max_encoding_message_size(MAX_MESSAGE_BYTES) + } + + /// Typed convenience calls for the library resources (library reads, display names, + /// favorites, catalog matching and covers), bound to this session's resource context. `None` + /// when the session negotiated a minor before API 1.6, like [`resource_context`](Self::resource_context). + /// They send exactly what the raw [`resource_client`](Self::resource_client) would. + pub fn resources(&self) -> Option { + self.resource_context + .clone() + .map(|context| Resources::new(self.channel.clone(), context)) + } + + /// Typed convenience calls for the host action services (launch/install, backups, tools, + /// ports and their jobs), bound to this session's resource context. `None` when the session + /// negotiated a minor before API 1.6, like [`resource_context`](Self::resource_context). + /// They send exactly what the raw [`resource_client`](Self::resource_client) would. + pub fn actions(&self) -> Option { + self.resource_context + .clone() + .map(|context| Actions::new(self.channel.clone(), context)) + } + pub fn context(&self) -> &ServiceContext { &self.context } + /// The host-issued context for plugin-initiated `ResourceHost` calls, from `OpenSession`. + /// `None` when the session negotiated a minor before API 1.6. It is bound to this session + /// and the active profile and adds no authority beyond the session's grants; after a profile + /// change the host ends the session and a new one issues a new context. + pub fn resource_context(&self) -> Option<&ServiceContext> { + self.resource_context.as_ref() + } + + pub async fn describe_api(&self) -> Result { + PluginHostClient::new(self.channel.clone()) + .describe_api(request(DescribeApiRequest { + session_id: self.context.session_id.clone(), + session_credential: self.context.session_credential.clone(), + })) + .await + .map(|reply| reply.into_inner()) + .map_err(|status| DetailedError::from_status(&status)) + } + + pub async fn get_permissions(&self) -> Result { + PluginHostClient::new(self.channel.clone()) + .get_permissions(request(GetPermissionsRequest { + session_id: self.context.session_id.clone(), + session_credential: self.context.session_credential.clone(), + })) + .await + .map(|reply| reply.into_inner()) + .map_err(|status| DetailedError::from_status(&status)) + } + + pub async fn watch_permission_changes( + &self, + after_revision: u64, + ) -> Result, DetailedError> { + PluginHostClient::new(self.channel.clone()) + .watch_permission_changes(request(WatchPermissionChangesRequest { + session_id: self.context.session_id.clone(), + session_credential: self.context.session_credential.clone(), + after_revision, + })) + .await + .map(|reply| reply.into_inner()) + .map_err(|status| DetailedError::from_status(&status)) + } + pub fn for_command(&self, command: &ProviderCommand) -> Result { let context = command.context.as_ref().ok_or(Error::Protocol)?; if context.session_id != self.context.session_id || context.provider_id != self.context.provider_id || context.session_credential != self.context.session_credential + || context.session_kind != self.context.session_kind + || context.target_game != self.context.target_game || context.operation_id.is_empty() { return Err(Error::Protocol); } Ok(Self { client: self.client.clone(), + channel: self.channel.clone(), context: context.clone(), events: self.events.clone(), plugin_id: self.plugin_id.clone(), settings_supported: self.settings_supported, + configure_supported: self.configure_supported, + resource_context: self.resource_context.clone(), }) } @@ -343,10 +663,69 @@ impl HostClient { self.send(provider_event::Event::Result(result)).await } + /// Reports one plugin-observed runtime lifecycle transition using the host-issued API 1.6 + /// resource context. This does not grant launch, process inspection or file access. + pub async fn report_runtime_session(&self, report: RuntimeSessionReport) -> Result<(), Error> { + let context = self.resource_context.clone().ok_or(Error::Configuration)?; + let target = context.target_game.as_ref().ok_or(Error::Denied)?; + if report.correlation_id.is_empty() + || ((report.runtime_context_id.is_empty()) + && (report.game_id != target.game_id + || report.installation_id != target.installation_id)) + || report.content_id.is_empty() + || report.runtime_id.is_empty() + || report.runtime_instance_id.is_empty() + || report.reporter_session_id != context.session_id + || report.sequence == 0 + || report.observed_at <= 0 + || report.source_observation_id.is_empty() + || !matches!( + RuntimeSessionTransition::try_from(report.transition), + Ok(transition) if transition != RuntimeSessionTransition::Unspecified + ) + { + return Err(Error::Protocol); + } + self.send_with_context(context, provider_event::Event::RuntimeSession(report)) + .await + } + + /// Requests one explicitly approved reporting context for a game/install observed by this + /// already-running runtime instance. The identifiers are proposals; the host resolves and + /// validates the current library binding before asking the user. + pub async fn request_runtime_session_context( + &self, + request: RuntimeSessionContextRequest, + ) -> Result<(), Error> { + if request.correlation_id.is_empty() + || request.game_id.is_empty() + || request.installation_id.is_empty() + || request.runtime_id.is_empty() + || request.runtime_instance_id.is_empty() + || request.content_id.is_empty() + { + return Err(Error::Protocol); + } + let context = self.resource_context.clone().ok_or(Error::Configuration)?; + self.send_with_context( + context, + provider_event::Event::RuntimeSessionContext(request), + ) + .await + } + async fn send(&self, event: provider_event::Event) -> Result<(), Error> { + self.send_with_context(self.context.clone(), event).await + } + + async fn send_with_context( + &self, + context: ServiceContext, + event: provider_event::Event, + ) -> Result<(), Error> { self.events .send(ProviderEvent { - context: Some(self.context.clone()), + context: Some(context), event: Some(event), }) .await @@ -379,6 +758,78 @@ impl Session { .await } + pub async fn open_with_options( + launch: Launch, + plugin_id: &str, + provider_id: &str, + plugin_version: &str, + capabilities: &[&str], + options: SessionOptions, + ) -> Result { + let channel = connect(&launch.endpoint).await?; + Self::from_channel_with_options( + channel, + launch, + plugin_id, + provider_id, + plugin_version, + capabilities, + options, + ) + .await + } + + /// Opens an extension session scoped to exactly one target game. The + /// extension has no provider identity of its own and must use the resource + /// client instead of provider-owned account/catalog operations. + pub async fn open_extension( + launch: Launch, + plugin_id: &str, + plugin_version: &str, + target: TargetGameContext, + capabilities: &[&str], + ) -> Result { + let channel = connect(&launch.endpoint).await?; + let mut session_capabilities = Vec::with_capacity(capabilities.len() + 1); + session_capabilities.push(capability::CONTEXT); + session_capabilities.extend( + capabilities + .iter() + .copied() + .filter(|permission| *permission != capability::CONTEXT), + ); + Self::from_channel_with_options( + channel, + launch, + plugin_id, + "", + plugin_version, + &session_capabilities, + SessionOptions { + min_api_major: 1, + min_api_minor: gamenode_plugin_protocol::API_MINOR, + max_api_major: 1, + max_api_minor: gamenode_plugin_protocol::API_MINOR, + features: vec![(capability::FEATURE_EXTENSION_SESSION.into(), true)], + session_kind: SessionKind::Extension, + target_game: Some(target), + }, + ) + .await + } + + /// Opens the one-shot extension session using only the target selected by Core at process + /// startup. Prefer this for packages launched from the desktop's game actions. + pub async fn open_extension_from_launch( + launch: Launch, + plugin_id: &str, + plugin_version: &str, + capabilities: &[&str], + ) -> Result { + let target = launch.selected_target().ok_or(Error::Configuration)?; + Self::open_extension(launch, plugin_id, plugin_version, target, capabilities).await + } + /// Also allows independent reference hosts to exercise the public protocol. pub async fn from_channel( channel: Channel, @@ -387,18 +838,72 @@ impl Session { provider_id: &str, plugin_version: &str, capabilities: &[&str], + ) -> Result { + Self::from_channel_with_options( + channel, + launch, + plugin_id, + provider_id, + plugin_version, + capabilities, + SessionOptions::default(), + ) + .await + } + + /// API 1.6+ handshake with an explicit compatibility range and optional + /// feature requests. The legacy `from_channel` method keeps its API 1.1–1.5 + /// request shape for existing official plugins. + pub async fn from_channel_with_options( + channel: Channel, + launch: Launch, + plugin_id: &str, + provider_id: &str, + plugin_version: &str, + capabilities: &[&str], + options: SessionOptions, ) -> Result { if launch.credential.len() != 32 { return Err(Error::Configuration); } + capability::validate_session_scope( + options.session_kind as u32, + options.target_game.is_some(), + ) + .map_err(|_| Error::Configuration)?; + if let Some(target) = options.target_game.as_ref() { + capability::validate_target(target).map_err(|_| Error::Configuration)?; + } let reply = PluginHostClient::new(channel.clone()) .open_session(request(OpenSessionRequest { plugin_id: plugin_id.into(), plugin_version: plugin_version.into(), api_major: gamenode_plugin_protocol::API_MAJOR, - api_minor: gamenode_plugin_protocol::API_MINOR, + api_minor: if options.min_api_major == 0 + && options.min_api_minor == 0 + && options.max_api_major == 0 + && options.max_api_minor == 0 + { + gamenode_plugin_protocol::LEGACY_API_MINOR + } else { + gamenode_plugin_protocol::API_MINOR + }, session_credential: launch.credential.clone(), requested_capabilities: capabilities.iter().map(|s| (*s).into()).collect(), + min_api_major: options.min_api_major, + min_api_minor: options.min_api_minor, + max_api_major: options.max_api_major, + max_api_minor: options.max_api_minor, + features: options + .features + .iter() + .map(|(id, required)| FeatureRequest { + id: id.clone(), + required: *required, + }) + .collect(), + session_kind: options.session_kind as i32, + target_game: options.target_game.clone(), })) .await? .into_inner(); @@ -419,6 +924,17 @@ impl Session { { return Err(Error::Protocol); } + for (id, required) in &options.features { + let Some(status) = reply.features.iter().find(|status| &status.id == id) else { + if *required { + return Err(Error::Protocol); + } + continue; + }; + if *required && status.availability != FeatureAvailability::Supported as i32 { + return Err(Error::Protocol); + } + } let settings_supported = capabilities.contains(&capability::SETTINGS); if settings_supported && reply.api_minor < capability::SETTINGS_API_MINOR { return Err(Error::Protocol); @@ -428,6 +944,11 @@ impl Session { { return Err(Error::Protocol); } + let resource_context = reply.resource_context.filter(|context| { + reply.api_minor >= capability::THIRD_PARTY_API_MINOR + && context.session_id == reply.session_id + && context.session_credential == launch.credential + }); let context = ServiceContext { session_id: reply.session_id, session_credential: launch.credential, @@ -435,9 +956,11 @@ impl Session { operation_id: launch.operation_id, account_epoch: 0, profile_epoch: 0, + session_kind: options.session_kind as i32, + target_game: options.target_game.clone(), }; let (events, receive) = mpsc::channel(EVENT_QUEUE); - let mut client = ProviderHostClient::new(channel) + let mut client = ProviderHostClient::new(channel.clone()) .max_decoding_message_size(MAX_MESSAGE_BYTES) .max_encoding_message_size(MAX_MESSAGE_BYTES); events @@ -456,10 +979,13 @@ impl Session { Ok(Self { host: HostClient { client, + channel: channel.clone(), context, events, plugin_id: plugin_id.into(), settings_supported, + configure_supported: capabilities.contains(&capability::CONFIGURE), + resource_context, }, commands, }) @@ -473,6 +999,21 @@ pub trait ProviderPlugin: Send + Sync + 'static { command: ProviderCommand, host: HostClient, ) -> Result; + /// Receives correlated runtime-session acknowledgements without treating them as operations. + async fn runtime_session_result( + &self, + _result: RuntimeSessionResult, + _host: HostClient, + ) -> Result<(), Error> { + Ok(()) + } + async fn runtime_session_context_result( + &self, + _result: RuntimeSessionContextResult, + _host: HostClient, + ) -> Result<(), Error> { + Ok(()) + } /// Plugin-owned semantic validation and persistence. Check the immutable /// request's profile/session scope again immediately before applying work. /// The default keeps settings unavailable for existing provider plugins. @@ -488,9 +1029,126 @@ pub trait ProviderPlugin: Send + Sync + 'static { }, }) } + /// Optional external configuration lifecycle. The default explicitly + /// declines; it does not turn an SDK plugin into an external UI provider. + async fn configure( + &self, + command: ProviderCommand, + _host: HostClient, + ) -> Result { + let context = command.context.ok_or(Error::Protocol)?; + Ok(OperationResult { + disposition: OperationDisposition::Failed as i32, + configuration: Some(ConfigurationResult { + session_id: context.session_id, + profile_id: String::new(), + window_id: command.target_operation_id, + accepted: false, + failure: "unsupported".into(), + }), + ..Default::default() + }) + } async fn shutdown(&self) {} } +#[async_trait::async_trait] +pub trait ExtensionPlugin: Send + Sync + 'static { + async fn handle( + &self, + command: ProviderCommand, + host: HostClient, + ) -> Result; + + async fn runtime_session_result( + &self, + _result: RuntimeSessionResult, + _host: HostClient, + ) -> Result<(), Error> { + Ok(()) + } + + async fn runtime_session_context_result( + &self, + _result: RuntimeSessionContextResult, + _host: HostClient, + ) -> Result<(), Error> { + Ok(()) + } + + async fn configure( + &self, + command: ProviderCommand, + _host: HostClient, + ) -> Result { + let context = command.context.ok_or(Error::Protocol)?; + Ok(OperationResult { + disposition: OperationDisposition::Failed as i32, + configuration: Some(ConfigurationResult { + session_id: context.session_id, + profile_id: String::new(), + window_id: command.target_operation_id, + accepted: false, + failure: "unsupported".into(), + }), + ..Default::default() + }) + } + + async fn shutdown(&self) {} +} + +struct ExtensionAdapter

(std::sync::Arc

); + +#[async_trait::async_trait] +impl ProviderPlugin for ExtensionAdapter

{ + async fn handle( + &self, + command: ProviderCommand, + host: HostClient, + ) -> Result { + self.0.handle(command, host).await + } + async fn configure( + &self, + command: ProviderCommand, + host: HostClient, + ) -> Result { + self.0.configure(command, host).await + } + async fn runtime_session_result( + &self, + result: RuntimeSessionResult, + host: HostClient, + ) -> Result<(), Error> { + self.0.runtime_session_result(result, host).await + } + async fn runtime_session_context_result( + &self, + result: RuntimeSessionContextResult, + host: HostClient, + ) -> Result<(), Error> { + self.0.runtime_session_context_result(result, host).await + } + async fn shutdown(&self) { + self.0.shutdown().await; + } +} + +/// Dispatches the shared authenticated command stream to an extension after +/// checking the negotiated session is target-scoped. +pub async fn run_extension( + session: Session, + plugin: std::sync::Arc

, +) -> Result<(), Error> { + if session.host.context.session_kind != SessionKind::Extension as i32 + || session.host.context.target_game.is_none() + { + return Err(Error::Configuration); + } + run(session, std::sync::Arc::new(ExtensionAdapter(plugin))).await +} + /// Dispatch bounded operations concurrently so control requests can reach a /// provider whose login or network request is still pending. pub async fn run( @@ -507,8 +1165,30 @@ pub async fn run( let host = session.host.for_command(&command)?; let operation = ProviderOperation::try_from(command.operation).map_err(|_| Error::Protocol)?; if operation == ProviderOperation::Acknowledge { continue; } + if operation == ProviderOperation::RuntimeSessionResult { + let result = command.runtime_session_result.clone().ok_or(Error::Protocol)?; + if result.correlation_id != command.target_operation_id { + return Err(Error::Protocol); + } + let plugin = plugin.clone(); + tasks.spawn(async move { + plugin.runtime_session_result(result, host).await + }); + continue; + } + if operation == ProviderOperation::RuntimeSessionContextResult { + let result = command.runtime_session_context_result.clone().ok_or(Error::Protocol)?; + if result.correlation_id != command.target_operation_id { + return Err(Error::Protocol); + } + let plugin = plugin.clone(); + tasks.spawn(async move { + plugin.runtime_session_context_result(result, host).await + }); + continue; + } if operation == ProviderOperation::Shutdown { break; } - let control = matches!(operation, ProviderOperation::FocusSignIn | ProviderOperation::CancelSignIn | ProviderOperation::Cancel | ProviderOperation::SignOut | ProviderOperation::SettingsCancel); + let control = matches!(operation, ProviderOperation::FocusSignIn | ProviderOperation::CancelSignIn | ProviderOperation::Cancel | ProviderOperation::SignOut | ProviderOperation::SettingsCancel | ProviderOperation::ConfigurationFocus | ProviderOperation::ConfigurationClose); let permit = if control { controls.clone() } else { work.clone() }.try_acquire_owned(); let Ok(permit) = permit else { let busy = if is_settings(operation) { @@ -530,6 +1210,17 @@ pub async fn run( let _permit = permit; let result = if is_settings(operation) { dispatch_settings(plugin.as_ref(), command, host.clone()).await + } else if matches!(operation, ProviderOperation::ConfigurationOpen | ProviderOperation::ConfigurationFocus | ProviderOperation::ConfigurationClose) { + if !host.configure_supported { + Ok(failure(Error::Denied)) + } else { + let expected_session = host.context.session_id.clone(); + let expected_window = command.target_operation_id.clone(); + let result = plugin.configure(command, host.clone()).await?; + if result.configuration.as_ref().is_none_or(|reply| reply.session_id != expected_session || reply.window_id != expected_window) { + Ok(failure(Error::Protocol)) + } else { Ok(result) } + } } else { plugin.handle(command, host.clone()).await }.unwrap_or_else(failure); diff --git a/crates/plugin-sdk/src/resources.rs b/crates/plugin-sdk/src/resources.rs new file mode 100644 index 000000000..3189adcc2 --- /dev/null +++ b/crates/plugin-sdk/src/resources.rs @@ -0,0 +1,1607 @@ +//! Convenience calls for the library resources of API 1.6: library reads, display names, +//! favorites, catalog matching, covers and shared data. +//! +//! Each method builds exactly the request a hand-written raw `ResourceHost` call would and +//! returns the host's answer unchanged, so the two are interchangeable; a service test in the +//! desktop repeats every call both ways and compares them. The helpers add no authority: they use +//! the session's `resource_context`, and the host still checks every grant, scope and revision. +//! Errors are the host's own [`tonic::Status`], whose codes the permissions document explains +//! (`NOT_FOUND` for a foreign or unknown entry, `FAILED_PRECONDITION` for a choice the user made, +//! `RESOURCE_EXHAUSTED` for a rate or byte budget, `UNAVAILABLE` when GameNode cannot answer). +//! +//! # Writing safely +//! +//! Every write needs an idempotency key and, for entries, the revision you last read: +//! +//! * Make one key per intended change with [`idempotency_key`] and **reuse it for retries** of that +//! change after a timeout or lost connection; the host then returns the original outcome +//! instead of applying it twice. A new change gets a new key. +//! * [`Outcome::RevisionConflict`] is a normal answer, not an error: the entry changed since you +//! read it. Read it again ([`Resources::library_get`]) and decide whether the change still +//! applies, using the new revision. The host does not remember conflicts, so the key may be +//! reused with the new revision. +//! * [`Outcome::AlreadyApplied`] means the entry already had that value; nothing was written. +//! +//! # Shared data +//! +//! [`Resources::data_publish`] fills only `mutation`; the caller supplies the dataset, payload and +//! observation fields, including `durability`. `SESSION_ONLY` keeps the record for the producing +//! session, while `PERSISTENT` writes it to the host's public pool so consumers can read it after +//! this session ends. The helper never chooses the mode and never retries: the host still enforces +//! `data.publish` (plus `storage.persist` for `PERSISTENT`), and a missing grant is +//! `PERMISSION_DENIED`, not a session-only downgrade. [`Resources::data_get`], +//! [`Resources::data_list`] and [`Resources::data_watch`] read with the same session context; an +//! optional `CommonDataSelector` requests another plugin's reviewed projection, which the host +//! checks independently of the request. + +use std::sync::atomic::{AtomicU64, Ordering}; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use tonic::{Request, Status, Streaming}; + +use crate::proto::resource_host_client::ResourceHostClient; +use crate::proto::*; +use crate::{MAX_MESSAGE_BYTES, SERVICE_TIMEOUT}; + +/// The most entries the host returns in one page. +pub const MAX_PAGE_SIZE: u32 = 200; +/// How many times [`Resources::library_entries`] and [`Resources::favorite_games`] restart a +/// list the library changed under them before giving up. +const LIST_RESTARTS: usize = 3; +/// The only display field a plugin may write. +const DISPLAY_NAME: &str = "display_name"; + +/// A consistent walk of the library: the entries and the library revision they were read at, +/// which is where [`Resources::library_watch`] should resume from. +#[derive(Clone, Debug, PartialEq)] +pub struct LibrarySnapshot { + pub entries: Vec, + pub revision: u64, +} + +/// What a write did. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Outcome { + /// The value changed. `Written::revision` is the new revision. + Applied, + /// The entry already had this value; nothing was written. + AlreadyApplied, + /// The entry changed since the revision you gave; nothing was written and + /// `Written::revision` is the current one. + RevisionConflict, +} + +/// The host's answer to a write. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Written { + /// The installation id (or the game id, for favorites) the write was about. + pub resource_id: String, + /// The resource's revision after the call, or the current one after a conflict. + pub revision: u64, + pub outcome: Outcome, +} + +/// A proposed, typed custom launch recipe. Choose one direct target: `executable_handle` or `uri`; +/// both may be empty when a host-issued `runtime_handle` wraps the detected target. URI recipes +/// may include argv, cwd and environment changes, but the host/OS URI adapter can explicitly +/// reject customizations it cannot apply. A runtime wrapper cannot be combined with a URI target. +/// Environment set/unset is a delta applied to the child process by the host. Handles are opaque +/// host-issued resource identifiers; they are never interpreted by the SDK as filesystem paths. +/// The host validates the recipe and its handles before saving it. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct CustomLaunchRecipe { + pub game_id: String, + pub installation_id: String, + /// Existing content identity selected by the host; execution cannot replace it. + pub content_id: String, + pub expected_revision: u64, + pub executable_handle: String, + pub uri: String, + pub argv: Vec, + pub working_directory_handle: String, + pub environment_set: std::collections::BTreeMap, + pub environment_unset: Vec, + pub runtime_handle: String, + /// Declared launch-time layers; each contributes ordered argv/environment changes and is + /// disclosed in the host review. Execution references only the stored recipe revision. + pub mod_layers: Vec, +} + +/// A declared launch-time mod layer, kept as typed fields rather than a free-form description. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct CustomLaunchModLayer { + pub id: String, + pub name: String, + pub version: String, + pub revision: u64, + pub argv: Vec, + pub environment_set: std::collections::BTreeMap, + pub environment_unset: Vec, +} + +/// A runtime executable approved on the host and shared by games that use the same interpreter. +/// The handle remains opaque: plugins provide it to registration and custom-launch requests but +/// must never interpret it as a path. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct RuntimeSpec { + pub name: String, + pub version: String, + pub executable_handle: String, + pub supported_formats: Vec, + pub extensions: std::collections::HashMap, + pub platform: String, + pub argument_template: Vec, +} + +/// One ordered runtime argument. `ContentPath` expands to the selected content path as one +/// argv element; literal values are never parsed as shell text. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum RuntimeArgumentTemplate { + Literal(String), + ContentPath, +} + +/// Text hints for the host's runtime picker. Executable base names and desktop ids only: never a +/// path, an argument or a handle. The host matches them against its own installed-program +/// inventory (PackageKit on Linux) and always offers manual Browse. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct RuntimeExecutableHints { + pub executable_names: Vec, + pub desktop_ids: Vec, +} + +/// One content-to-runtime binding. The game and installation IDs preserve GameNode identity; +/// content and runtime handles are opaque host-issued references. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct RuntimeContentBinding { + /// Empty when registering a new content item; set to the existing ID when updating its + /// locator after a move or rename. + pub content_id: String, + pub game_id: String, + pub installation_id: String, + pub content_handle: String, + pub content_kind: String, + pub runtime_id: String, + pub supported_platforms: Vec, +} + +fn runtime_record(spec: RuntimeSpec, id: &str, revision: u64) -> RuntimeRecord { + RuntimeRecord { + id: id.to_owned(), + name: spec.name, + version: spec.version, + executable_handle: spec.executable_handle, + supported_formats: spec.supported_formats, + extensions: spec.extensions, + revision, + observed_at: 0, + platform: spec.platform, + argument_template: spec + .argument_template + .into_iter() + .map(|argument| crate::proto::RuntimeArgumentTemplate { + value: Some(match argument { + RuntimeArgumentTemplate::Literal(value) => { + crate::proto::runtime_argument_template::Value::Literal(value) + } + RuntimeArgumentTemplate::ContentPath => { + crate::proto::runtime_argument_template::Value::ContentPath( + ContentPathArgument {}, + ) + } + }), + }) + .collect(), + provenance: None, + } +} + +fn runtime_register_request( + context: &ServiceContext, + spec: RuntimeSpec, + key: &str, + expected_revision: u64, +) -> RuntimeRegisterRequest { + RuntimeRegisterRequest { + mutation: Some(MutationContext { + context: Some(context.clone()), + operation_id: String::new(), + idempotency_key: key.to_owned(), + expected_revision, + }), + runtime: Some(runtime_record(spec, "", 0)), + } +} + +fn runtime_request_access_request( + context: &ServiceContext, + spec: RuntimeSpec, + hints: RuntimeExecutableHints, + key: &str, + expected_revision: u64, +) -> RuntimeRequestAccessRequest { + let mut runtime = runtime_record(spec, "", 0); + // The request never carries an executable handle: the host owns the choice and approval. + runtime.executable_handle.clear(); + RuntimeRequestAccessRequest { + mutation: Some(MutationContext { + context: Some(context.clone()), + operation_id: String::new(), + idempotency_key: key.to_owned(), + expected_revision, + }), + runtime: Some(runtime), + hints: Some(RuntimeAccessHints { + executable_names: hints.executable_names, + desktop_ids: hints.desktop_ids, + }), + } +} + +fn runtime_update_request( + context: &ServiceContext, + runtime_id: &str, + spec: RuntimeSpec, + field_mask: Vec, + key: &str, + expected_revision: u64, +) -> RuntimeUpdateRequest { + RuntimeUpdateRequest { + mutation: Some(MutationContext { + context: Some(context.clone()), + operation_id: String::new(), + idempotency_key: key.to_owned(), + expected_revision, + }), + runtime: Some(runtime_record(spec, runtime_id, expected_revision)), + field_mask, + extension_patch: None, + } +} + +fn runtime_content_request( + context: &ServiceContext, + binding: RuntimeContentBinding, + key: &str, + expected_revision: u64, +) -> ContentRegistrationRequest { + ContentRegistrationRequest { + mutation: Some(MutationContext { + context: Some(context.clone()), + operation_id: String::new(), + idempotency_key: key.to_owned(), + expected_revision, + }), + content_id: binding.content_id, + game_id: binding.game_id, + installation_id: binding.installation_id, + content_handle: binding.content_handle, + content_kind: binding.content_kind, + runtime_id: binding.runtime_id, + supported_platforms: binding.supported_platforms, + } +} + +#[cfg(test)] +mod runtime_sdk_tests { + use super::*; + + fn runtime() -> RuntimeSpec { + RuntimeSpec { + name: "Example Emulator".into(), + version: "1.2".into(), + executable_handle: "approved-runtime-handle".into(), + supported_formats: vec!["sfc".into(), "smc".into()], + extensions: Default::default(), + platform: "linux".into(), + argument_template: vec![ + RuntimeArgumentTemplate::Literal("--game".into()), + RuntimeArgumentTemplate::ContentPath, + ], + } + } + + #[test] + fn registration_sends_host_issued_handle_and_expected_revision() { + let context = ServiceContext { + provider_id: "runtime-plugin".into(), + ..Default::default() + }; + let request = runtime_register_request(&context, runtime(), "register-key", 0); + let mutation = request.mutation.unwrap(); + let runtime = request.runtime.unwrap(); + + assert_eq!(mutation.context.as_ref(), Some(&context)); + assert_eq!(mutation.idempotency_key, "register-key"); + assert_eq!(mutation.expected_revision, 0); + assert!(runtime.id.is_empty()); + assert_eq!(runtime.name, "Example Emulator"); + assert_eq!(runtime.executable_handle, "approved-runtime-handle"); + assert_eq!(runtime.supported_formats, ["sfc", "smc"]); + assert_eq!(runtime.platform, "linux"); + assert_eq!(runtime.argument_template.len(), 2); + assert!(matches!( + runtime.argument_template[0].value.as_ref(), + Some(crate::proto::runtime_argument_template::Value::Literal(value)) + if value == "--game" + )); + assert!(matches!( + runtime.argument_template[1].value.as_ref(), + Some(crate::proto::runtime_argument_template::Value::ContentPath( + _ + )) + )); + assert_eq!(runtime.revision, 0); + assert_eq!(runtime.observed_at, 0); + } + + #[test] + fn request_access_strips_the_handle_and_sends_text_hints_only() { + let context = ServiceContext::default(); + let request = runtime_request_access_request( + &context, + runtime(), + RuntimeExecutableHints { + executable_names: vec!["dolphin-emu".into()], + desktop_ids: vec!["dolphin-emu.desktop".into()], + }, + "request-key", + 0, + ); + let mutation = request.mutation.unwrap(); + let runtime = request.runtime.unwrap(); + let hints = request.hints.unwrap(); + + assert_eq!(mutation.idempotency_key, "request-key"); + assert_eq!(mutation.expected_revision, 0); + assert!(runtime.id.is_empty()); + assert!(runtime.executable_handle.is_empty()); + assert_eq!(runtime.name, "Example Emulator"); + assert_eq!(runtime.platform, "linux"); + assert_eq!(hints.executable_names, ["dolphin-emu"]); + assert_eq!(hints.desktop_ids, ["dolphin-emu.desktop"]); + } + + #[test] + fn update_and_content_binding_keep_game_and_installation_identity() { + let context = ServiceContext::default(); + let update = runtime_update_request( + &context, + "runtime-1", + runtime(), + vec!["version".into()], + "update-key", + 7, + ); + let updated = update.runtime.unwrap(); + assert_eq!(updated.id, "runtime-1"); + assert_eq!(updated.revision, 7); + assert_eq!(update.field_mask, ["version"]); + assert_eq!(update.mutation.unwrap().expected_revision, 7); + + let binding = runtime_content_request( + &context, + RuntimeContentBinding { + content_id: String::new(), + game_id: "620".into(), + installation_id: "steam:620".into(), + content_handle: "approved-content-handle".into(), + content_kind: "rom".into(), + runtime_id: "runtime-1".into(), + supported_platforms: vec!["linux".into()], + }, + "bind-key", + 3, + ); + assert_eq!(binding.game_id, "620"); + assert!(binding.content_id.is_empty()); + assert_eq!(binding.installation_id, "steam:620"); + assert_eq!(binding.content_handle, "approved-content-handle"); + assert_eq!(binding.runtime_id, "runtime-1"); + assert_eq!(binding.supported_platforms, ["linux"]); + assert_eq!(binding.mutation.unwrap().expected_revision, 3); + + let moved_binding = runtime_content_request( + &context, + RuntimeContentBinding { + content_id: "content-existing".into(), + game_id: "620".into(), + installation_id: "steam:620".into(), + content_handle: "approved-content-handle-after-move".into(), + content_kind: "rom".into(), + runtime_id: "runtime-1".into(), + supported_platforms: vec!["linux".into()], + }, + "move-key", + 4, + ); + assert_eq!(moved_binding.content_id, "content-existing"); + assert_eq!(moved_binding.installation_id, "steam:620"); + assert_eq!( + moved_binding.content_handle, + "approved-content-handle-after-move" + ); + } +} + +impl Written { + /// Whether the entry now has the requested value, whether this call set it or not. + pub fn is_done(&self) -> bool { + matches!(self.outcome, Outcome::Applied | Outcome::AlreadyApplied) + } +} + +impl TryFrom for Written { + type Error = Status; + + fn try_from(reply: MutationReply) -> Result { + let outcome = match MutationOutcome::try_from(reply.outcome) { + Ok(MutationOutcome::Applied) => Outcome::Applied, + Ok(MutationOutcome::AlreadyApplied) => Outcome::AlreadyApplied, + Ok(MutationOutcome::RevisionConflict) => Outcome::RevisionConflict, + _ => return Err(Status::internal("the host sent an unknown outcome")), + }; + Ok(Self { + resource_id: reply.resource_id, + revision: reply.revision, + outcome, + }) + } +} + +/// A cover read back from the host. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Cover { + pub bytes: Vec, + /// `image/jpeg` or `image/png`. + pub media_type: String, + /// The entry's artwork revision: 0 while the cover is the game's own, not a plugin's. + pub revision: u64, +} + +/// A key for one intended change. Reuse it when retrying that change; use a new one for the +/// next. At most 128 bytes and free of control characters, as the host requires. +pub fn idempotency_key() -> String { + static COUNTER: AtomicU64 = AtomicU64::new(0); + let nanos = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or(Duration::ZERO) + .as_nanos(); + format!( + "sdk-{:x}-{nanos:x}-{:x}", + std::process::id(), + COUNTER.fetch_add(1, Ordering::Relaxed) + ) +} + +pub(crate) fn timed(message: T) -> Request { + let mut request = Request::new(message); + request.set_timeout(SERVICE_TIMEOUT); + request +} + +/// The library entry and exact recipe revision a custom launch was approved for. +struct ApprovedRecipe<'a> { + game_id: &'a str, + installation_id: &'a str, + expected_revision: u64, + recipe_id: &'a str, + recipe_revision: u64, +} + +/// Typed access to the library resources, bound to one session's `resource_context`. Get it from +/// [`HostClient::resources`](crate::HostClient::resources). Cheap to clone. +#[derive(Clone)] +pub struct Resources { + pub(crate) client: ResourceHostClient, + pub(crate) context: ServiceContext, +} + +impl Resources { + pub(crate) fn new(channel: tonic::transport::Channel, context: ServiceContext) -> Self { + Self { + client: ResourceHostClient::new(channel) + .max_decoding_message_size(MAX_MESSAGE_BYTES) + .max_encoding_message_size(MAX_MESSAGE_BYTES), + context, + } + } + + pub(crate) fn mutation(&self, key: &str, expected_revision: u64) -> MutationContext { + MutationContext { + context: Some(self.context.clone()), + operation_id: String::new(), + idempotency_key: key.to_owned(), + expected_revision, + } + } + + fn custom_launch_proposal( + context: &ServiceContext, + recipe: &CustomLaunchRecipe, + user_intent_id: &str, + key: &str, + ) -> CustomLaunchRequest { + CustomLaunchRequest { + context: Some(context.clone()), + game_id: recipe.game_id.clone(), + installation_id: recipe.installation_id.clone(), + content_id: recipe.content_id.clone(), + expected_revision: recipe.expected_revision, + user_intent_id: user_intent_id.to_owned(), + idempotency_key: key.to_owned(), + executable_handle: recipe.executable_handle.clone(), + argv: recipe.argv.clone(), + working_directory_handle: recipe.working_directory_handle.clone(), + environment_set: recipe.environment_set.clone().into_iter().collect(), + environment_unset: recipe.environment_unset.clone(), + runtime_handle: recipe.runtime_handle.clone(), + recipe_id: String::new(), + recipe_revision: 0, + uri: recipe.uri.clone(), + mod_layers: recipe + .mod_layers + .iter() + .map(|layer| crate::proto::CustomLaunchModLayer { + id: layer.id.clone(), + name: layer.name.clone(), + version: layer.version.clone(), + revision: layer.revision, + argv: layer.argv.clone(), + environment_set: layer.environment_set.clone().into_iter().collect(), + environment_unset: layer.environment_unset.clone(), + }) + .collect(), + } + } + + fn custom_launch_execution( + context: &ServiceContext, + approved: ApprovedRecipe<'_>, + user_intent_id: &str, + key: &str, + ) -> CustomLaunchRequest { + CustomLaunchRequest { + context: Some(context.clone()), + game_id: approved.game_id.to_owned(), + installation_id: approved.installation_id.to_owned(), + content_id: String::new(), + expected_revision: approved.expected_revision, + user_intent_id: user_intent_id.to_owned(), + idempotency_key: key.to_owned(), + executable_handle: String::new(), + argv: Vec::new(), + working_directory_handle: String::new(), + environment_set: Default::default(), + environment_unset: Vec::new(), + runtime_handle: String::new(), + recipe_id: approved.recipe_id.to_owned(), + recipe_revision: approved.recipe_revision, + uri: String::new(), + mod_layers: Vec::new(), + } + } + + fn custom_launch_removal( + context: &ServiceContext, + game_id: &str, + recipe_id: &str, + recipe_revision: u64, + key: &str, + ) -> CustomLaunchRemoveRequest { + CustomLaunchRemoveRequest { + mutation: Some(MutationContext { + context: Some(context.clone()), + operation_id: String::new(), + idempotency_key: key.to_owned(), + expected_revision: recipe_revision, + }), + game_id: game_id.to_owned(), + recipe_id: recipe_id.to_owned(), + } + } + + fn page(&self, page_size: u32, cursor: &str) -> PageRequest { + PageRequest { + context: Some(self.context.clone()), + cursor: cursor.to_owned(), + page_size, + common_data_categories: None, + } + } + + // ---- Runtimes and content bindings (`game.runtime.*`) ---- + + /// One page of the caller's private runtime catalog by default. Supplying a selector is an + /// explicit request for common runtime records; the host still requires the matching read + /// grant and enforces its scope. + pub async fn runtimes_page( + &self, + page_size: u32, + cursor: &str, + shared_records: Option, + ) -> Result { + let mut page = self.page(page_size, cursor); + page.common_data_categories = shared_records; + self.client + .clone() + .runtimes_list(timed(DomainListRequest { + page: Some(page), + kind: String::new(), + owner_filter: String::new(), + })) + .await + .map(tonic::Response::into_inner) + } + + /// One runtime record. With no selector, the host returns only records visible to this plugin. + pub async fn runtime_get( + &self, + runtime_id: &str, + shared_records: Option, + ) -> Result { + let reply = self + .client + .clone() + .runtimes_get(timed(DomainGetRequest { + context: Some(self.context.clone()), + resource_id: runtime_id.to_owned(), + expected_revision: 0, + shared_records, + })) + .await? + .into_inner(); + reply + .runtime + .ok_or_else(|| Status::internal("the host sent no runtime record")) + } + + /// Runtime catalog events after `after_revision` (0: from now on). A stale position is + /// `FAILED_PRECONDITION`; list again and resume from that reply's revision. + pub async fn runtimes_watch( + &self, + after_revision: u64, + shared_records: Option, + ) -> Result, Status> { + self.client + .clone() + .runtimes_watch(DomainWatchRequest { + context: Some(self.context.clone()), + after_revision, + resource_id: String::new(), + shared_records, + }) + .await + .map(tonic::Response::into_inner) + } + + /// Register an already installed runtime. This call does not install or download software; + /// `executable_handle` must be a host-issued approved resource handle. + pub async fn runtime_register( + &self, + runtime: RuntimeSpec, + expected_revision: u64, + key: &str, + ) -> Result { + self.client + .clone() + .runtimes_register(timed(runtime_register_request( + &self.context, + runtime, + key, + expected_revision, + ))) + .await + .map(tonic::Response::into_inner) + } + + /// Ask the host to let the user approve one exact executable as a runtime. The spec must not + /// carry a handle; the reply's runtime record also carries none. The host reuses a valid + /// owned runtime with the same name/platform/formats without prompting, and a declined + /// picker creates nothing. Reuse the key for retries of this request. + pub async fn runtime_request_access( + &self, + runtime: RuntimeSpec, + hints: RuntimeExecutableHints, + expected_revision: u64, + key: &str, + ) -> Result { + if !runtime.executable_handle.is_empty() { + return Err(Status::invalid_argument( + "runtime_request_access takes no executable handle", + )); + } + self.client + .clone() + .runtimes_request_access(timed(runtime_request_access_request( + &self.context, + runtime, + hints, + key, + expected_revision, + ))) + .await + .map(tonic::Response::into_inner) + } + + /// Update selected fields of a runtime owned by this plugin using its last known revision. + pub async fn runtime_update( + &self, + runtime_id: &str, + runtime: RuntimeSpec, + field_mask: impl IntoIterator>, + expected_revision: u64, + key: &str, + ) -> Result { + self.client + .clone() + .runtimes_update(timed(runtime_update_request( + &self.context, + runtime_id, + runtime, + field_mask.into_iter().map(Into::into).collect(), + key, + expected_revision, + ))) + .await + .map(tonic::Response::into_inner) + } + + /// Applies the protocol's revision checked typed and namespace patch to an owned runtime. + /// Namespace operations are further restricted by the host to this plugin's namespace. + pub async fn runtime_update_patch( + &self, + runtime_id: &str, + runtime: RuntimeSpec, + patch: ExtensionPatch, + field_mask: impl IntoIterator>, + expected_revision: u64, + key: &str, + ) -> Result { + let mut request = runtime_update_request( + &self.context, + runtime_id, + runtime, + field_mask.into_iter().map(Into::into).collect(), + key, + expected_revision, + ); + request.extension_patch = Some(patch); + self.client + .clone() + .runtimes_update(timed(request)) + .await + .map(tonic::Response::into_inner) + } + + /// Remove an owned runtime. Runtime removal does not imply content, game, save or history + /// deletion; callers must handle the resulting unbound installations explicitly. + pub async fn runtime_remove( + &self, + runtime_id: &str, + expected_revision: u64, + key: &str, + ) -> Result { + self.client + .clone() + .runtimes_remove(timed(DomainRemoveRequest { + mutation: Some(self.mutation(key, expected_revision)), + resource_id: runtime_id.to_owned(), + })) + .await? + .into_inner() + .try_into() + } + + /// Bind one content item to an existing GameNode game and installation. The content handle + /// and runtime ID are opaque; this operation does not create a duplicate game identity. + pub async fn register_runtime_content( + &self, + binding: RuntimeContentBinding, + expected_revision: u64, + key: &str, + ) -> Result { + self.client + .clone() + .games_register_content(timed(runtime_content_request( + &self.context, + binding, + key, + expected_revision, + ))) + .await? + .into_inner() + .try_into() + } + + // ---- Library reads (`library.read`, or `library.read.all` for other providers) ---- + + /// One page of the library. An empty `provider_id` means the caller's own provider; naming + /// another needs `library.read.all`. Pass the previous reply's `next_cursor` to continue; a + /// cursor goes stale when the library changes (`FAILED_PRECONDITION`), and the list then + /// restarts. Most plugins want [`library_entries`](Self::library_entries). + pub async fn library_page( + &self, + provider_id: &str, + search: &str, + page_size: u32, + cursor: &str, + ) -> Result { + self.client + .clone() + .library_list(timed(LibraryListRequest { + page: Some(self.page(page_size, cursor)), + provider_id: provider_id.to_owned(), + search: search.to_owned(), + })) + .await + .map(tonic::Response::into_inner) + } + + /// Every entry of `provider_id` (empty: the caller's own), following the cursors. See + /// [`library_snapshot`](Self::library_snapshot). + pub async fn library_entries(&self, provider_id: &str) -> Result, Status> { + self.library_snapshot(provider_id) + .await + .map(|snapshot| snapshot.entries) + } + + /// Every entry of `provider_id` (empty: the caller's own) and the library revision they were + /// read at, following the cursors. If the library changes during the walk the list restarts, + /// up to three times, so the result is one consistent snapshot; after that the last + /// `FAILED_PRECONDITION` is returned. Resume a watch from `revision`. + pub async fn library_snapshot(&self, provider_id: &str) -> Result { + let mut restarts = 0; + 'again: loop { + let mut entries = Vec::new(); + let mut cursor = String::new(); + loop { + match self + .library_page(provider_id, "", MAX_PAGE_SIZE, &cursor) + .await + { + Ok(page) => { + entries.extend(page.entries); + if page.next_cursor.is_empty() { + return Ok(LibrarySnapshot { + entries, + revision: page.revision, + }); + } + cursor = page.next_cursor; + } + // Only a cursor can go stale; a refusal of the first page is a real error. + Err(status) + if status.code() == tonic::Code::FailedPrecondition + && !cursor.is_empty() + && restarts < LIST_RESTARTS => + { + restarts += 1; + continue 'again; + } + Err(status) => return Err(status), + } + } + } + } + + /// One of the caller's own entries by its `installation_id`. + pub async fn library_get(&self, installation_id: &str) -> Result { + let reply = self + .client + .clone() + .library_get(timed(LibraryGetRequest { + context: Some(self.context.clone()), + game_id: String::new(), + installation_id: installation_id.to_owned(), + common_data_categories: None, + })) + .await? + .into_inner(); + reply + .entry + .ok_or_else(|| Status::internal("the host sent no entry")) + } + + /// Library changes after `after_revision` (0: from now on), as the host's own event stream. + /// A position the host no longer retains is `FAILED_PRECONDITION`: list again, then watch + /// from the list's revision. + pub async fn library_watch( + &self, + provider_id: &str, + after_revision: u64, + ) -> Result, Status> { + self.client + .clone() + .library_watch(LibraryWatchRequest { + context: Some(self.context.clone()), + after_revision, + provider_id: provider_id.to_owned(), + common_data_categories: None, + }) + .await + .map(tonic::Response::into_inner) + } + + // ---- Display name (`library.metadata.write`) ---- + + /// Sets the display name of an own entry, or restores the detected name with `None`. + /// `expected_revision` is the entry's `metadata_revision`. + pub async fn set_display_name( + &self, + installation_id: &str, + expected_revision: u64, + key: &str, + display_name: Option<&str>, + ) -> Result { + self.client + .clone() + .metadata_update(timed(MetadataUpdateRequest { + mutation: Some(self.mutation(key, expected_revision)), + game_id: String::new(), + installation_id: installation_id.to_owned(), + display_fields: [( + DISPLAY_NAME.to_owned(), + display_name.unwrap_or_default().to_owned(), + )] + .into(), + })) + .await? + .into_inner() + .try_into() + } + + // ---- Favorites (`favorites.read`, `favorites.write`) ---- + + /// The favorite state of every GameNode game matched by the caller's own entries, as + /// `(game_id, favorite)`, following the cursors like [`library_entries`](Self::library_entries). + pub async fn favorite_games(&self) -> Result, Status> { + let mut restarts = 0; + 'again: loop { + let mut games = Vec::new(); + let mut cursor = String::new(); + loop { + let reply = self + .client + .clone() + .favorites_list(timed(FavoritesListRequest { + page: Some(self.page(MAX_PAGE_SIZE, &cursor)), + profile_id: String::new(), + })) + .await; + match reply { + Ok(page) => { + let page = page.into_inner(); + games.extend(page.entries.into_iter().map(|e| (e.game_id, e.favorite))); + if page.next_cursor.is_empty() { + return Ok(games); + } + cursor = page.next_cursor; + } + Err(status) + if status.code() == tonic::Code::FailedPrecondition + && !cursor.is_empty() + && restarts < LIST_RESTARTS => + { + restarts += 1; + continue 'again; + } + Err(status) => return Err(status), + } + } + } + } + + /// Marks or unmarks a GameNode game that one of the caller's own entries is matched to. A + /// favorite has no revision: this is a desired-state write. + pub async fn set_favorite( + &self, + game_id: &str, + favorite: bool, + key: &str, + ) -> Result { + self.client + .clone() + .favorites_set(timed(FavoritesSetRequest { + mutation: Some(self.mutation(key, 0)), + profile_id: String::new(), + game_id: game_id.to_owned(), + favorite, + })) + .await? + .into_inner() + .try_into() + } + + /// Proposes a recipe for later custom execution. This never calls standard `game.launch` and + /// does not start a process; the host validates the typed handles and permission separately. + pub async fn propose_custom_launch( + &self, + recipe: &CustomLaunchRecipe, + user_intent_id: &str, + key: &str, + ) -> Result { + self.client + .clone() + .games_propose_custom_launch(timed(Self::custom_launch_proposal( + &self.context, + recipe, + user_intent_id, + key, + ))) + .await + .map(tonic::Response::into_inner) + } + + /// Requests execution of a previously proposed recipe revision. The request carries no + /// replacement executable, argv, cwd, runtime or environment payload, so the host can only + /// execute the immutable recipe it approved. A denied `game.custom_launch` grant stays a + /// `PERMISSION_DENIED` error; there is no fallback to standard launch. + #[allow(clippy::too_many_arguments)] // Published SDK API: a parameter struct would break plugin callers. + pub async fn request_custom_launch( + &self, + game_id: &str, + installation_id: &str, + expected_revision: u64, + recipe_id: &str, + recipe_revision: u64, + user_intent_id: &str, + key: &str, + ) -> Result { + self.client + .clone() + .games_request_custom_launch(timed(Self::custom_launch_execution( + &self.context, + ApprovedRecipe { + game_id, + installation_id, + expected_revision, + recipe_id, + recipe_revision, + }, + user_intent_id, + key, + ))) + .await + .map(tonic::Response::into_inner) + } + + /// Removes one of this caller's recipes at the revision it last read. + pub async fn remove_custom_launch( + &self, + game_id: &str, + recipe_id: &str, + recipe_revision: u64, + key: &str, + ) -> Result { + self.client + .clone() + .games_remove_custom_launch(timed(Self::custom_launch_removal( + &self.context, + game_id, + recipe_id, + recipe_revision, + key, + ))) + .await + .map(tonic::Response::into_inner) + } + + // ---- Matching (`matching.read`, `matching.write`) ---- + + /// Searches the GameNode catalog by title: one page of at most `page_size` candidates (0: the + /// host's default of 20; the host caps it at 50), in the server's order. `UNAVAILABLE` when + /// GameNode cannot answer, never an empty list; `RESOURCE_EXHAUSTED` past the host's rate. + pub async fn search_catalog( + &self, + query: &str, + page_size: u32, + ) -> Result, Status> { + self.client + .clone() + .matching_search(timed(MatchingSearchRequest { + context: Some(self.context.clone()), + query: query.to_owned(), + platform: String::new(), + page_size, + cursor: String::new(), + })) + .await + .map(|reply| reply.into_inner().candidates) + } + + /// Matches an own entry to a GameNode game that the library knows or a recent + /// [`search_catalog`](Self::search_catalog) returned. `expected_revision` is the entry's + /// `revision`. A match the user chose is `FAILED_PRECONDITION` and is never replaced. + pub async fn assign_match( + &self, + installation_id: &str, + gamenode_game_id: &str, + expected_revision: u64, + key: &str, + ) -> Result { + self.client + .clone() + .matching_assign(timed(MatchingAssignRequest { + mutation: Some(self.mutation(key, expected_revision)), + provider_id: String::new(), + provider_game_id: String::new(), + gamenode_game_id: gamenode_game_id.to_owned(), + installation_id: installation_id.to_owned(), + })) + .await? + .into_inner() + .try_into() + } + + // ---- Covers (`artwork.read`, `artwork.write`) ---- + + /// The cover an own entry shows, at most `max_bytes` (0: the host's 5 MiB maximum). Nothing is + /// downloaded: an entry whose cover is not on this device is `NOT_FOUND`, and a larger image + /// is `RESOURCE_EXHAUSTED` rather than truncated. + pub async fn read_cover(&self, installation_id: &str, max_bytes: u64) -> Result { + let reply = self + .client + .clone() + .artwork_read(timed(ArtworkReadRequest { + context: Some(self.context.clone()), + game_id: String::new(), + installation_id: installation_id.to_owned(), + artwork_kind: String::new(), + max_bytes, + })) + .await? + .into_inner(); + Ok(Cover { + bytes: reply.encoded_image, + media_type: reply.media_type, + revision: reply.revision, + }) + } + + /// Sets the cover of an own entry from an encoded static PNG, JPEG or WebP (at most 4 MiB and + /// 4096 x 4096 pixels; `media_type` must match the bytes). The host decodes, shrinks and + /// re-encodes it; the matched game's cover is not touched. `expected_revision` is the entry's + /// `artwork_revision`. A refused image is `INVALID_ARGUMENT` with the reason. + pub async fn set_cover( + &self, + installation_id: &str, + expected_revision: u64, + key: &str, + image: Vec, + media_type: &str, + ) -> Result { + self.send_cover( + installation_id, + expected_revision, + key, + image, + media_type, + "", + ) + .await + } + + /// Like [`set_cover`](Self::set_cover), but the image is a file the plugin may read: + /// `file_handle` is a regular-file handle from the Files service (`files_list`, + /// `files_create`), from an approval of this same installation. It needs `files.read` besides + /// `artwork.write`; the host reads the file itself under the same 4 MiB bound, so the plugin + /// does not have to hold the bytes. A path or URL is never accepted. `media_type` must match + /// the file's bytes. + pub async fn set_cover_from_file( + &self, + installation_id: &str, + expected_revision: u64, + key: &str, + file_handle: &str, + media_type: &str, + ) -> Result { + self.send_cover( + installation_id, + expected_revision, + key, + Vec::new(), + media_type, + file_handle, + ) + .await + } + + /// Restores the game's own cover for an own entry. + pub async fn clear_cover( + &self, + installation_id: &str, + expected_revision: u64, + key: &str, + ) -> Result { + self.send_cover(installation_id, expected_revision, key, Vec::new(), "", "") + .await + } + + async fn send_cover( + &self, + installation_id: &str, + expected_revision: u64, + key: &str, + image: Vec, + media_type: &str, + file_handle: &str, + ) -> Result { + self.client + .clone() + .artwork_set(timed(ArtworkSetRequest { + mutation: Some(self.mutation(key, expected_revision)), + game_id: String::new(), + installation_id: installation_id.to_owned(), + artwork_kind: String::new(), + encoded_image: image, + media_type: media_type.to_owned(), + file_handle: file_handle.to_owned(), + })) + .await? + .into_inner() + .try_into() + } + + // ---- Shared data (`data.publish`; `storage.persist` for `PERSISTENT`) ---- + + /// Publishes one shared-data record. The caller fills the request's dataset, payload and + /// observation fields and leaves `mutation` empty; this helper overwrites it with `key`, + /// `expected_revision` and this session's context. Publication is append-only, so + /// `expected_revision` must be `0`. `request.durability` selects the mode: `SESSION_ONLY` + /// needs `data.publish`, and `PERSISTENT` needs `storage.persist` as well, which the host + /// enforces with an explicit `PERMISSION_DENIED` rather than a session-only downgrade. The + /// reply reports the mode and expiry actually stored. + pub async fn data_publish( + &self, + key: &str, + expected_revision: u64, + request: DataPublishRequest, + ) -> Result { + let request = DataPublishRequest { + mutation: Some(self.mutation(key, expected_revision)), + ..request + }; + self.client + .clone() + .data_publish(timed(request)) + .await + .map(tonic::Response::into_inner) + } + + /// One shared-data record by its host-assigned id. A durable record stays readable while its + /// producer is offline. `selector` explicitly requests another plugin's common record; without + /// it the host returns only records visible to this plugin. A hidden or missing record is + /// `NOT_FOUND`. + pub async fn data_get( + &self, + dataset_id: &str, + record_id: &str, + selector: Option, + ) -> Result { + let reply = self + .client + .clone() + .data_get(timed(DataGetRequest { + context: Some(self.context.clone()), + dataset_id: dataset_id.to_owned(), + record_id: record_id.to_owned(), + common_data_categories: selector, + })) + .await? + .into_inner(); + reply + .record + .ok_or_else(|| Status::internal("the host sent no data record")) + } + + /// One page of a dataset at the host's snapshot revision. `filter` must stay empty in this + /// build. `page_size` 0 means the host's default. Pass the reply's `next_cursor` back + /// unchanged to continue; the cursor is bound to this session and query and expires. + pub async fn data_list( + &self, + dataset_id: &str, + filter: &str, + selector: Option, + page_size: u32, + ) -> Result { + self.client + .clone() + .data_list(timed(DataListRequest { + page: Some(self.page(page_size, "")), + dataset_id: dataset_id.to_owned(), + filter: filter.to_owned(), + common_data_categories: selector, + })) + .await + .map(tonic::Response::into_inner) + } + + /// Shared-data changes after `after_revision` (0: from now on), as the host's own event + /// stream. Resume from a list reply's `revision`; a position the host no longer accepts is + /// `FAILED_PRECONDITION`, so list again and watch from that revision. A revoked projection or + /// an overflowing queue ends the stream the same way. + pub async fn data_watch( + &self, + dataset_id: &str, + after_revision: u64, + selector: Option, + ) -> Result, Status> { + self.client + .clone() + .data_watch(DataWatchRequest { + context: Some(self.context.clone()), + dataset_id: dataset_id.to_owned(), + after_revision, + common_data_categories: selector, + }) + .await + .map(tonic::Response::into_inner) + } +} + +#[cfg(test)] +mod custom_launch_tests { + use super::*; + #[test] + fn proposal_preserves_typed_custom_launch_fields() { + let context = ServiceContext { + provider_id: "fixture".into(), + ..Default::default() + }; + let recipe = CustomLaunchRecipe { + game_id: "620".into(), + installation_id: "steam:620".into(), + content_id: String::new(), + expected_revision: 12, + executable_handle: "exec-handle".into(), + uri: String::new(), + argv: vec!["--literal value".into(), "$(not-a-shell)".into()], + working_directory_handle: "cwd-handle".into(), + environment_set: [("A".into(), "value with spaces".into())].into(), + environment_unset: vec!["B".into()], + runtime_handle: String::new(), + mod_layers: Vec::new(), + }; + + let request = Resources::custom_launch_proposal(&context, &recipe, "intent", "key"); + + assert_eq!(request.context.as_ref(), Some(&context)); + assert_eq!(request.game_id, "620"); + assert_eq!(request.installation_id, "steam:620"); + assert_eq!(request.expected_revision, 12); + assert_eq!(request.executable_handle, "exec-handle"); + assert!(request.uri.is_empty()); + assert_eq!(request.argv, recipe.argv); + assert_eq!(request.working_directory_handle, "cwd-handle"); + assert_eq!( + request.environment_set.get("A").map(String::as_str), + Some("value with spaces") + ); + assert_eq!(request.environment_unset, ["B"]); + assert!(request.runtime_handle.is_empty()); + assert!(request.recipe_id.is_empty()); + assert_eq!(request.recipe_revision, 0); + assert_eq!(request.user_intent_id, "intent"); + assert_eq!(request.idempotency_key, "key"); + } + + #[test] + fn runtime_proposal_keeps_content_and_omits_direct_executable() { + let context = ServiceContext { + provider_id: "fixture".into(), + ..Default::default() + }; + let recipe = CustomLaunchRecipe { + game_id: "620".into(), + installation_id: "steam:620".into(), + content_id: "content-variant-1".into(), + expected_revision: 12, + executable_handle: String::new(), + uri: String::new(), + argv: vec!["--literal value".into()], + working_directory_handle: "cwd-handle".into(), + environment_set: [("A".into(), "value with spaces".into())].into(), + environment_unset: vec!["B".into()], + runtime_handle: "runtime-handle".into(), + mod_layers: Vec::new(), + }; + + let request = Resources::custom_launch_proposal(&context, &recipe, "intent", "key"); + + assert!(request.executable_handle.is_empty()); + assert!(request.uri.is_empty()); + assert_eq!(request.content_id, "content-variant-1"); + assert_eq!(request.runtime_handle, "runtime-handle"); + assert_eq!(request.argv, recipe.argv); + assert_eq!(request.working_directory_handle, "cwd-handle"); + assert_eq!( + request.environment_set.get("A").map(String::as_str), + Some("value with spaces") + ); + assert_eq!(request.environment_unset, ["B"]); + } + + #[test] + fn known_mod_layer_proposal_keeps_host_reviewed_fields_typed() { + let context = ServiceContext::default(); + let recipe = CustomLaunchRecipe { + game_id: "fixture-game".into(), + installation_id: "fixture-install".into(), + expected_revision: 7, + executable_handle: "opaque-executable".into(), + runtime_handle: "opaque-known-mod-layer".into(), + argv: vec!["--profile".into(), "fixture".into()], + ..Default::default() + }; + + let request = Resources::custom_launch_proposal(&context, &recipe, "intent", "key"); + + assert_eq!(request.runtime_handle, "opaque-known-mod-layer"); + assert_eq!(request.executable_handle, "opaque-executable"); + assert_eq!(request.argv, ["--profile", "fixture"]); + assert_eq!(request.expected_revision, 7); + } + + #[test] + fn declared_mod_layers_keep_identity_revision_and_ordered_contributions_typed() { + let context = ServiceContext::default(); + let recipe = CustomLaunchRecipe { + game_id: "fixture-game".into(), + installation_id: "fixture-install".into(), + expected_revision: 7, + argv: vec!["--windowed".into()], + mod_layers: vec![ + CustomLaunchModLayer { + id: "texture-hd".into(), + name: "HD texture layer".into(), + version: "1.2".into(), + revision: 3, + argv: vec!["--mod=texture-hd".into()], + environment_set: [("MOD_LAYER".into(), "texture-hd".into())].into(), + environment_unset: vec!["VANILLA".into()], + }, + CustomLaunchModLayer { + id: "second".into(), + revision: 1, + ..Default::default() + }, + ], + ..Default::default() + }; + + let request = Resources::custom_launch_proposal(&context, &recipe, "intent", "key"); + + assert_eq!(request.argv, ["--windowed"]); + assert_eq!(request.mod_layers.len(), 2); + assert_eq!(request.mod_layers[0].id, "texture-hd"); + assert_eq!(request.mod_layers[0].name, "HD texture layer"); + assert_eq!(request.mod_layers[0].revision, 3); + assert_eq!(request.mod_layers[0].argv, ["--mod=texture-hd"]); + assert_eq!( + request.mod_layers[0] + .environment_set + .get("MOD_LAYER") + .map(String::as_str), + Some("texture-hd") + ); + assert_eq!(request.mod_layers[0].environment_unset, ["VANILLA"]); + assert_eq!(request.mod_layers[1].id, "second"); + } + + #[test] + fn environment_only_consent_stays_a_recipe_and_does_not_become_install_intent() { + let context = ServiceContext::default(); + let recipe = CustomLaunchRecipe { + game_id: "fixture-game".into(), + installation_id: "fixture-install".into(), + expected_revision: 7, + environment_set: [("FIXTURE_MODE".into(), "enabled".into())].into(), + environment_unset: vec!["FIXTURE_LEGACY_MODE".into()], + ..Default::default() + }; + + let request = Resources::custom_launch_proposal(&context, &recipe, "launch-intent", "key"); + + assert!(request.executable_handle.is_empty()); + assert!(request.uri.is_empty()); + assert!(request.runtime_handle.is_empty()); + assert!(request.argv.is_empty()); + assert_eq!( + request + .environment_set + .get("FIXTURE_MODE") + .map(String::as_str), + Some("enabled") + ); + assert_eq!(request.environment_unset, ["FIXTURE_LEGACY_MODE"]); + assert_eq!(request.user_intent_id, "launch-intent"); + // Installation has a separate request type and intent field; launch consent cannot fill it. + let install = GameInstallRequest { + game_id: request.game_id.clone(), + installation_id: request.installation_id.clone(), + user_intent_id: "separate-install-intent".into(), + ..Default::default() + }; + assert_ne!(install.user_intent_id, request.user_intent_id); + } + + #[test] + fn uri_proposal_uses_the_uri_target_without_executable_fields() { + let context = ServiceContext::default(); + let recipe = CustomLaunchRecipe { + game_id: "620".into(), + installation_id: "steam:620".into(), + expected_revision: 12, + uri: "game://open?id=620".into(), + argv: vec!["--profile".into(), "alternate profile".into()], + working_directory_handle: "cwd-handle".into(), + environment_set: [("MODE".into(), "custom".into())].into(), + environment_unset: vec!["LEGACY_MODE".into()], + ..Default::default() + }; + + let request = Resources::custom_launch_proposal(&context, &recipe, "intent", "key"); + + assert_eq!(request.uri, "game://open?id=620"); + assert!(request.executable_handle.is_empty()); + assert_eq!(request.argv, recipe.argv); + assert_eq!(request.working_directory_handle, "cwd-handle"); + assert!(request.runtime_handle.is_empty()); + assert_eq!( + request.environment_set.get("MODE").map(String::as_str), + Some("custom") + ); + assert_eq!(request.environment_unset, ["LEGACY_MODE"]); + } + + #[test] + fn execution_uses_only_the_approved_recipe_reference() { + let context = ServiceContext::default(); + let request = Resources::custom_launch_execution( + &context, + ApprovedRecipe { + game_id: "620", + installation_id: "steam:620", + expected_revision: 12, + recipe_id: "recipe-1", + recipe_revision: 4, + }, + "intent", + "key", + ); + + assert_eq!(request.context.as_ref(), Some(&context)); + assert_eq!(request.game_id, "620"); + assert_eq!(request.installation_id, "steam:620"); + assert!(request.content_id.is_empty()); + assert_eq!(request.expected_revision, 12); + assert_eq!(request.recipe_id, "recipe-1"); + assert_eq!(request.recipe_revision, 4); + assert_eq!(request.user_intent_id, "intent"); + assert_eq!(request.idempotency_key, "key"); + assert!(request.executable_handle.is_empty()); + assert!(request.uri.is_empty()); + assert!(request.argv.is_empty()); + assert!(request.working_directory_handle.is_empty()); + assert!(request.environment_set.is_empty()); + assert!(request.environment_unset.is_empty()); + assert!(request.runtime_handle.is_empty()); + } + + #[test] + fn removal_binds_recipe_revision_and_idempotency_key() { + let context = ServiceContext { + provider_id: "fixture".into(), + ..Default::default() + }; + let request = Resources::custom_launch_removal(&context, "620", "recipe-1", 4, "key"); + let mutation = request.mutation.expect("removal must be revision guarded"); + + assert_eq!(request.game_id, "620"); + assert_eq!(request.recipe_id, "recipe-1"); + assert_eq!(mutation.context.as_ref(), Some(&context)); + assert_eq!(mutation.expected_revision, 4); + assert_eq!(mutation.idempotency_key, "key"); + } +} diff --git a/crates/plugin-sdk/src/utilities.rs b/crates/plugin-sdk/src/utilities.rs new file mode 100644 index 000000000..bb8c731e7 --- /dev/null +++ b/crates/plugin-sdk/src/utilities.rs @@ -0,0 +1,571 @@ +//! Convenience calls for the utility services of API 1.6: private storage, files, network fetch +//! and notifications. They are more methods of [`Resources`], with the same guarantees as the +//! library helpers: each builds exactly the request a hand-written raw `ResourceHost` call would +//! and returns the host's answer unchanged, a desktop service test repeats every call both ways, +//! and the helpers add no authority. The host checks every grant, scope, quota and revision. +//! +//! What the services refuse is explained, with every limit and status code, in +//! `docs/plugin-api-permissions.md`. In short, errors are the host's own [`tonic::Status`]: +//! +//! * `PERMISSION_DENIED`: the user did not grant it (or revoked it, or approved other origins); +//! * `FAILED_PRECONDITION`: ask again (file access), or the same key was used for another request; +//! * `NOT_FOUND`: a handle or entry that is not yours or is gone; +//! * `RESOURCE_EXHAUSTED`: a quota, rate or byte budget (nothing was changed or truncated); +//! * `INVALID_ARGUMENT`: the request itself is malformed; do not retry it unchanged; +//! * `UNAVAILABLE`/`DEADLINE_EXCEEDED`: retry with the **same** idempotency key. +//! +//! These services give a plugin what the user approved *through GameNode*. They are not a +//! sandbox: nothing here stops the plugin's own process from using the operating system +//! directly, and a plugin must not claim otherwise. + +use std::collections::BTreeMap; +use std::time::Duration; + +use tonic::Status; + +use crate::proto::*; +use crate::resources::{Resources, Written, timed}; + +/// How long a stored or shared value is kept and where. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Durability { + /// Kept in GameNode's memory until the plugin's last session ends. Needs only + /// `storage.write`. + SessionOnly, + /// Survives restarts. Needs `storage.persist`, which the user approves separately; without + /// it the write is `PERMISSION_DENIED` and is **not** downgraded to a volatile success. + Persistent, +} + +impl Durability { + /// The wire value to send or compare, shared by storage and shared-data replies. + pub fn to_proto(self) -> i32 { + match self { + Self::SessionOnly => StorageDurability::SessionOnly as i32, + Self::Persistent => StorageDurability::Persistent as i32, + } + } + + /// Reads a wire value. `None` means the field was absent (an older host or client) or the + /// value is unknown, so the caller never assumes a mode the host did not report. + pub fn from_proto(value: i32) -> Option { + match StorageDurability::try_from(value) { + Ok(StorageDurability::SessionOnly) => Some(Self::SessionOnly), + Ok(StorageDurability::Persistent) => Some(Self::Persistent), + _ => None, + } + } +} + +/// A key read from storage. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct StoredValue { + /// Whether the key exists. An expired value is a key that does not exist. + pub found: bool, + pub value: Vec, + /// 0 while the key does not exist; the `expected_revision` of the next write or delete. + pub revision: u64, + /// Where the value lives now; `None` when it was not found. + pub durability: Option, + /// Unix seconds; 0 when it never expires. + pub expires_at: i64, +} + +/// What a storage write did, with the layer's usage so a plugin can free space before it runs out. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct StoredWrite { + /// The key's new revision, or the current one after a conflict. + pub revision: u64, + pub outcome: crate::Outcome, + /// Logical bytes in use in the layer that was written, and that layer's quota. + pub usage_bytes: u64, + pub quota_bytes: u64, + pub durability: Option, + pub expires_at: i64, +} + +/// One https request for [`Resources::network_fetch`]. Only the URL is required; the host's +/// defaults are a GET with a 1 MiB response budget and a 30 second deadline (both capped). +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Fetch { + url: String, + method: String, + headers: BTreeMap, + body: Vec, + max_response_bytes: u64, + timeout_ms: u32, +} + +impl Fetch { + /// A GET of `url`, which must be https with an origin the user approved. + pub fn get(url: impl Into) -> Self { + Self { + url: url.into(), + ..Self::default() + } + } + + /// Another method (`HEAD`, `POST`, `PUT`, `PATCH` or `DELETE`) with an optional body. + #[must_use] + pub fn method(mut self, method: &str, body: impl Into>) -> Self { + self.method = method.to_owned(); + self.body = body.into(); + self + } + + /// Adds a header. The host refuses the ones that are its own to set (`Host`, + /// `Content-Length`, `Proxy-*`, ...) and adds none of GameNode's. + #[must_use] + pub fn header(mut self, name: &str, value: &str) -> Self { + self.headers.insert(name.to_owned(), value.to_owned()); + self + } + + /// The most response bytes to accept; a larger response is `RESOURCE_EXHAUSTED`, not cut. + #[must_use] + pub fn max_response_bytes(mut self, bytes: u64) -> Self { + self.max_response_bytes = bytes; + self + } + + /// The deadline for the whole fetch, redirects included. + #[must_use] + pub fn timeout(mut self, timeout: Duration) -> Self { + self.timeout_ms = u32::try_from(timeout.as_millis()).unwrap_or(u32::MAX); + self + } +} + +/// The answer to a fetch. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Fetched { + pub status_code: u16, + /// Header names are lower case. Bodies are not decompressed. + pub headers: BTreeMap, + pub body: Vec, + /// The origin that finally answered, after redirects. + pub final_origin: String, +} + +/// How a notice is presented. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Severity { + #[default] + Unspecified, + Info, + Success, + Warning, + Error, +} + +impl Severity { + fn as_str(self) -> &'static str { + match self { + Self::Unspecified => "", + Self::Info => "info", + Self::Success => "success", + Self::Warning => "warning", + Self::Error => "error", + } + } +} + +/// A short plain-text notice. GameNode shows it as coming from the plugin, picks the translation +/// that matches the user's language, and never interprets anything in it as markup, a link or an +/// action. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Notice { + title: String, + body: String, + locale: String, + severity: Severity, + translations: Vec<(String, String, String)>, +} + +impl Notice { + /// A notice with a title in `locale` (a language tag such as `en`; empty when unspecified). + pub fn new(locale: &str, title: &str) -> Self { + Self { + title: title.to_owned(), + locale: locale.to_owned(), + ..Self::default() + } + } + + #[must_use] + pub fn body(mut self, body: &str) -> Self { + self.body = body.to_owned(); + self + } + + #[must_use] + pub fn severity(mut self, severity: Severity) -> Self { + self.severity = severity; + self + } + + /// The same notice in another language. Each `locale` is distinct and non-empty; at most 8. + #[must_use] + pub fn translation(mut self, locale: &str, title: &str, body: &str) -> Self { + self.translations + .push((locale.to_owned(), title.to_owned(), body.to_owned())); + self + } +} + +/// A suggestion of where the folder for `kind` (`"save"` or `"prefix"`) usually is. `location` is +/// an absolute path, or starts with a placeholder the host expands: `{home}`, `{documents}`, +/// `{appdata}`, `{localappdata}` (Windows) or `{xdg_data}`, `{xdg_config}` (Linux), followed by +/// plain names separated by `/` (no `..`). `description` is one line of plain text, at most 120 +/// bytes. Within one kind, declare the most likely folder first, at most 8 per kind. +pub fn declared_location(kind: &str, location: &str, description: &str) -> DeclaredLocation { + DeclaredLocation { + kind: kind.to_owned(), + location: location.to_owned(), + description: description.to_owned(), + } +} + +/// The most bytes one `FilesRead` returns. +pub const MAX_READ_CHUNK: u64 = 4 * 1024 * 1024; + +impl Resources { + // ---- Private storage (`storage.read`, `storage.write`, `storage.persist`, `storage.delete`) ---- + + /// Reads one key of the plugin's own namespace. A key that does not exist is not an error: + /// [`StoredValue::found`] is false and `revision` is 0. + pub async fn storage_get(&self, key: &str) -> Result { + let reply = self + .client + .clone() + .storage_get(timed(StorageGetRequest { + context: Some(self.context.clone()), + key: key.to_owned(), + })) + .await? + .into_inner(); + Ok(StoredValue { + found: reply.found, + value: reply.value, + revision: reply.revision, + durability: Durability::from_proto(reply.durability), + expires_at: reply.expires_at, + }) + } + + /// Writes one key (at most 1 MiB; the layer holds 16 MiB). `expected_revision` is the key's + /// revision from [`storage_get`](Self::storage_get), 0 for a new key. `ttl` of `None` keeps + /// the value until it is deleted; otherwise it expires after `ttl`, which the host limits to + /// 30 days. A revision conflict is an answer ([`crate::Outcome::RevisionConflict`]), not an + /// error; a quota failure is `RESOURCE_EXHAUSTED` and changes nothing. + pub async fn storage_put( + &self, + key: &str, + expected_revision: u64, + idempotency_key: &str, + value: impl Into>, + durability: Durability, + ttl: Option, + ) -> Result { + let reply = self + .client + .clone() + .storage_put(timed(StoragePutRequest { + mutation: Some(self.mutation(idempotency_key, expected_revision)), + key: key.to_owned(), + value: value.into(), + durability: durability.to_proto(), + ttl_seconds: ttl.map_or(0, |ttl| ttl.as_secs().max(1)), + })) + .await? + .into_inner(); + let outcome = Written::try_from(MutationReply { + resource_id: key.to_owned(), + revision: reply.revision, + outcome: reply.outcome, + })? + .outcome; + Ok(StoredWrite { + revision: reply.revision, + outcome, + usage_bytes: reply.usage_bytes, + quota_bytes: reply.quota_bytes, + durability: Durability::from_proto(reply.durability), + expires_at: reply.expires_at, + }) + } + + /// Deletes one key. Deleting a key that is not there is [`crate::Outcome::AlreadyApplied`]. + pub async fn storage_delete( + &self, + key: &str, + expected_revision: u64, + idempotency_key: &str, + ) -> Result { + self.client + .clone() + .storage_delete(timed(StorageDeleteRequest { + mutation: Some(self.mutation(idempotency_key, expected_revision)), + key: key.to_owned(), + })) + .await? + .into_inner() + .try_into() + } + + // ---- Files (`files.read`, `files.write`, `files.delete`) ---- + + /// Asks for access to a folder of one of the plugin's own library entries. `operations` are + /// `"read"`, `"write"` and `"delete"` and `kinds` are `"installation"`, `"save"` or `"prefix"` + /// (empty: the installation folder). The user chooses and confirms the folder; the plugin never + /// names a path. The handles are opaque and last for the session: after a restart ask again. + /// `FAILED_PRECONDITION` and `NOT_FOUND` on a handle mean "ask again". + pub async fn files_request_access( + &self, + installation_id: &str, + operations: &[&str], + kinds: &[&str], + idempotency_key: &str, + ) -> Result, Status> { + self.files_request_access_with(installation_id, operations, kinds, &[], idempotency_key) + .await + } + + /// Like [`files_request_access`](Self::files_request_access), also telling GameNode where the + /// folder usually is (see [`declared_location`]). The suggestions are shown to the user as + /// declared by the plugin and not verified; the user takes one or chooses another folder, and + /// a suggestion alone grants nothing. The reply says nothing about which suggestions exist or + /// were taken. A malformed suggestion is `INVALID_ARGUMENT`; one that cannot apply on this + /// system is dropped without an error, so one list can serve every platform. + pub async fn files_request_access_with( + &self, + installation_id: &str, + operations: &[&str], + kinds: &[&str], + declared: &[DeclaredLocation], + idempotency_key: &str, + ) -> Result, Status> { + Ok(self + .client + .clone() + .files_request_access(timed(FilesRequestAccessRequest { + mutation: Some(self.mutation(idempotency_key, 0)), + game_id: String::new(), + installation_id: installation_id.to_owned(), + requested_operations: operations.iter().map(|op| (*op).to_owned()).collect(), + resource_kinds: kinds.iter().map(|kind| (*kind).to_owned()).collect(), + declared_locations: declared.to_vec(), + })) + .await? + .into_inner() + .handles) + } + + /// One page of a directory, by handle. `page_size` 0 is the host's default. + pub async fn files_page( + &self, + directory: &str, + page_size: u32, + cursor: &str, + ) -> Result { + self.client + .clone() + .files_list(timed(FilesListRequest { + context: Some(self.context.clone()), + directory_handle: directory.to_owned(), + cursor: cursor.to_owned(), + page_size, + })) + .await + .map(tonic::Response::into_inner) + } + + /// Every entry of a directory, following the cursors. Each entry has its own handle. + pub async fn files_list(&self, directory: &str) -> Result, Status> { + let mut entries = Vec::new(); + let mut cursor = String::new(); + loop { + let page = self.files_page(directory, 0, &cursor).await?; + entries.extend(page.entries); + if page.next_cursor.is_empty() { + return Ok(entries); + } + cursor = page.next_cursor; + } + } + + /// Up to `max_bytes` (at most [`MAX_READ_CHUNK`]; 0 is the host's default) of a file from + /// `offset`. Continue at the reply's `next_offset` until `eof`. + pub async fn files_read( + &self, + file: &str, + offset: u64, + max_bytes: u64, + ) -> Result { + self.client + .clone() + .files_read(timed(FilesReadRequest { + context: Some(self.context.clone()), + file_handle: file.to_owned(), + offset, + max_bytes, + })) + .await + .map(tonic::Response::into_inner) + } + + /// The whole file, read in chunks. A file longer than `limit` bytes is `RESOURCE_EXHAUSTED` + /// rather than read in part, so the plugin never holds more than it chose to. + pub async fn files_read_all(&self, file: &str, limit: u64) -> Result, Status> { + let mut contents = Vec::new(); + let mut offset = 0; + loop { + let want = limit + .saturating_sub(contents.len() as u64) + .saturating_add(1) + .min(MAX_READ_CHUNK); + let chunk = self.files_read(file, offset, want).await?; + contents.extend_from_slice(&chunk.contents); + if contents.len() as u64 > limit { + return Err(Status::resource_exhausted( + "the file is larger than the limit", + )); + } + if chunk.eof { + return Ok(contents); + } + if chunk.next_offset <= offset { + return Err(Status::internal("the host did not advance the read")); + } + offset = chunk.next_offset; + } + } + + /// Writes `contents` into an existing file at `offset` (not past its end); with `truncate` + /// the file ends where the write does. The reply's `resource_id` is the file's handle. + pub async fn files_write( + &self, + file: &str, + offset: u64, + contents: impl Into>, + truncate: bool, + idempotency_key: &str, + ) -> Result { + self.write(file, "", offset, contents.into(), truncate, idempotency_key) + .await + } + + /// Creates, or replaces, the file `name` (one plain name, valid on every platform) inside the + /// directory `directory`. The reply's `resource_id` is the new file's handle. + pub async fn files_create( + &self, + directory: &str, + name: &str, + contents: impl Into>, + idempotency_key: &str, + ) -> Result { + self.write(directory, name, 0, contents.into(), true, idempotency_key) + .await + } + + async fn write( + &self, + handle: &str, + name: &str, + offset: u64, + contents: Vec, + truncate: bool, + idempotency_key: &str, + ) -> Result { + self.client + .clone() + .files_write(timed(FilesWriteRequest { + mutation: Some(self.mutation(idempotency_key, 0)), + file_handle: handle.to_owned(), + offset, + contents, + truncate, + name: name.to_owned(), + })) + .await? + .into_inner() + .try_into() + } + + /// Deletes one regular file. Directories are never deleted. + pub async fn files_delete(&self, file: &str, idempotency_key: &str) -> Result { + self.client + .clone() + .files_delete(timed(FilesDeleteRequest { + mutation: Some(self.mutation(idempotency_key, 0)), + file_handle: file.to_owned(), + })) + .await? + .into_inner() + .try_into() + } + + // ---- Network (`network.fetch`) ---- + + /// Fetches an https URL for the plugin, from an origin the user approved. The host connects + /// only to public addresses, follows at most 5 redirects and only to approved origins, adds no + /// GameNode credential and never reveals where a refused request would have gone. A + /// non-2xx answer is a normal [`Fetched`]; only a refusal or failure is an error. + pub async fn network_fetch(&self, fetch: &Fetch) -> Result { + let reply = self + .client + .clone() + .network_fetch(timed(NetworkFetchRequest { + context: Some(self.context.clone()), + url: fetch.url.clone(), + method: fetch.method.clone(), + headers: fetch + .headers + .iter() + .map(|(name, value)| (name.clone(), value.clone())) + .collect(), + body: fetch.body.clone(), + max_response_bytes: fetch.max_response_bytes, + timeout_ms: fetch.timeout_ms, + })) + .await? + .into_inner(); + Ok(Fetched { + status_code: u16::try_from(reply.status_code) + .map_err(|_| Status::internal("the host sent an unknown status code"))?, + headers: reply.headers.into_iter().collect(), + body: reply.body, + final_origin: reply.final_origin, + }) + } + + // ---- Notifications (`notifications.publish`) ---- + + /// Shows a short plain-text notice from the plugin. The host limits a plugin to 5 a minute: + /// `RESOURCE_EXHAUSTED` carries the wait in `retry-after-ms`, and that attempt is not + /// remembered, so the same key may be sent again later. Resending a notice the host already + /// showed (same key, same notice) does not show it twice. + pub async fn notify(&self, notice: &Notice, idempotency_key: &str) -> Result { + self.client + .clone() + .notifications_publish(timed(NotificationPublishRequest { + mutation: Some(self.mutation(idempotency_key, 0)), + title: notice.title.clone(), + body: notice.body.clone(), + locale: notice.locale.clone(), + severity: notice.severity.as_str().to_owned(), + translations: notice + .translations + .iter() + .map(|(locale, title, body)| NotificationTranslation { + locale: locale.clone(), + title: title.clone(), + body: body.clone(), + }) + .collect(), + })) + .await? + .into_inner() + .try_into() + } +} diff --git a/crates/plugin-sdk/tests/common_data_selector.rs b/crates/plugin-sdk/tests/common_data_selector.rs new file mode 100644 index 000000000..c8c284a45 --- /dev/null +++ b/crates/plugin-sdk/tests/common_data_selector.rs @@ -0,0 +1,45 @@ +use gamenode_plugin_protocol::proto::CommonDataCategory; +use serde_json::Value; + +const CONTRACT: &str = include_str!("../../plugin-protocol/contracts/common_data_selector.json"); + +fn category(name: &str) -> CommonDataCategory { + match name { + "GAME_PATHS" => CommonDataCategory::GamePaths, + "GAME_PERFORMANCE_HISTORY" => CommonDataCategory::GamePerformanceHistory, + "RUNTIME_CATALOG" => CommonDataCategory::RuntimeCatalog, + "CONTENT_AVAILABILITY" => CommonDataCategory::ContentAvailability, + _ => panic!("unrecognized common data category in shared contract: {name}"), + } +} + +#[test] +fn sdk_selector_matches_shared_contract_for_private_and_common_queries() { + let contract: Value = serde_json::from_str(CONTRACT).unwrap(); + let categories = contract["categories"].as_array().unwrap(); + for query in contract["queries"].as_array().unwrap() { + let names = query["categories"].as_array().unwrap(); + let selector = gamenode_plugin_sdk::common_data_selector( + names.iter().map(|name| category(name.as_str().unwrap())), + ) + .unwrap(); + let expected = names + .iter() + .map(|name| { + let name = name.as_str().unwrap(); + let entry = categories + .iter() + .find(|entry| entry["name"] == name) + .unwrap(); + entry["number"].as_i64().unwrap() as i32 + }) + .collect::>(); + assert_eq!(selector.categories, expected, "query {}", query["id"]); + if names.is_empty() { + assert!( + selector.categories.is_empty(), + "empty selector is private-only" + ); + } + } +} diff --git a/crates/plugin-sdk/tests/reference_host.rs b/crates/plugin-sdk/tests/reference_host.rs index b6ce6e579..7f5b46ba1 100644 --- a/crates/plugin-sdk/tests/reference_host.rs +++ b/crates/plugin-sdk/tests/reference_host.rs @@ -5,7 +5,7 @@ use std::sync::Arc; use gamenode_plugin_sdk::{ - Error, HostClient, Launch, ProviderPlugin, Session, capability, models, proto::*, + Error, HostClient, Launch, ProviderPlugin, Session, capability, models, prost_types, proto::*, }; use tokio::sync::{Semaphore, mpsc, oneshot}; use tokio_stream::wrappers::{ReceiverStream, UnixListenerStream}; @@ -20,7 +20,9 @@ fn authorize(context: Option<&ServiceContext>) -> Result<&ServiceContext, Status let context = context.ok_or_else(|| Status::unauthenticated("missing context"))?; if context.session_id != "session" || context.session_credential != [9; 32] - || context.provider_id != "fixture" + || !(context.provider_id == "fixture" + || (context.provider_id.is_empty() + && context.session_kind == SessionKind::Extension as i32)) { return Err(Status::permission_denied("wrong session")); } @@ -39,6 +41,8 @@ fn reference_host_rejects_stale_epochs_and_unknown_operations() { operation_id: "current".into(), account_epoch: 7, profile_epoch: 11, + session_kind: SessionKind::Provider as i32, + target_game: None, }; assert!(authorize(Some(¤t)).is_ok()); let stale = ServiceContext { @@ -54,22 +58,45 @@ fn reference_host_rejects_stale_epochs_and_unknown_operations() { #[tonic::async_trait] impl plugin_host_server::PluginHost for ReferenceHost { + type WatchPermissionChangesStream = + tokio_stream::Iter>>; async fn open_session( &self, request: Request, ) -> Result, Status> { let hello = request.into_inner(); + let valid_provider = hello.session_kind == SessionKind::Provider as i32 + && hello.requested_capabilities == [capability::CONTEXT, capability::CONFIGURE]; + let valid_extension = hello.session_kind == SessionKind::Extension as i32 + && hello.target_game.is_some() + && hello.requested_capabilities + == [ + capability::CONTEXT, + capability::GAME_LAUNCH, + capability::CONFIGURE, + ]; if hello.plugin_id != "fixture.plugin" || hello.session_credential != [9; 32] - || hello.requested_capabilities != [capability::CONTEXT] + || !(valid_provider || valid_extension) { return Err(Status::permission_denied("invalid launch")); } Ok(Response::new(OpenSessionReply { + resource_context: None, session_id: "session".into(), granted_capabilities: hello.requested_capabilities, api_major: 1, - api_minor: 2, + api_minor: 6, + features: hello + .features + .iter() + .map(|feature| FeatureStatus { + id: feature.id.clone(), + availability: FeatureAvailability::Supported as i32, + introduced_minor: 6, + }) + .collect(), + support_window: None, })) } @@ -79,6 +106,60 @@ impl plugin_host_server::PluginHost for ReferenceHost { ) -> Result, Status> { Err(Status::permission_denied("not granted")) } + async fn describe_api( + &self, + request: Request, + ) -> Result, Status> { + if request.get_ref().session_id != "session" + || request.get_ref().session_credential != [9; 32] + { + return Err(Status::unauthenticated("invalid fixture")); + } + Ok(Response::new(DescribeApiReply { + api_major: 1, + api_minor: 6, + support_window: None, + features: vec![], + methods: vec![], + })) + } + async fn get_permissions( + &self, + request: Request, + ) -> Result, Status> { + if request.get_ref().session_id != "session" + || request.get_ref().session_credential != [9; 32] + { + return Err(Status::unauthenticated("invalid fixture")); + } + Ok(Response::new(GetPermissionsReply { + revision: 3, + grants: vec![PermissionGrant { + permission_id: capability::CONTEXT.into(), + state: "granted".into(), + scope: "provider".into(), + reason: String::new(), + revision: 3, + }], + })) + } + async fn watch_permission_changes( + &self, + request: Request, + ) -> Result, Status> { + if request.get_ref().session_id != "session" + || request.get_ref().session_credential != [9; 32] + { + return Err(Status::unauthenticated("invalid fixture")); + } + Ok(Response::new(tokio_stream::iter(vec![Ok( + PermissionChange { + revision: 4, + grants: vec![], + revoked: true, + }, + )]))) + } } #[tonic::async_trait] @@ -114,8 +195,19 @@ impl provider_host_server::ProviderHost for ReferenceHost { ..context.clone() }), operation: operation as i32, - target_operation_id: String::new(), + target_operation_id: if matches!( + operation, + ProviderOperation::ConfigurationOpen + | ProviderOperation::ConfigurationFocus + | ProviderOperation::ConfigurationClose + ) { + id.into() + } else { + String::new() + }, settings: None, + runtime_session_result: None, + runtime_session_context_result: None, achievements: None, }; for (operation, id) in [ @@ -128,6 +220,9 @@ impl provider_host_server::ProviderHost for ReferenceHost { (ProviderOperation::SyncCatalog, "catalog"), (ProviderOperation::ReadCounter, "counter"), (ProviderOperation::SignOut, "sign-out"), + (ProviderOperation::ConfigurationOpen, "config-open"), + (ProviderOperation::ConfigurationFocus, "config-focus"), + (ProviderOperation::ConfigurationClose, "config-close"), ] { tx.send(Ok(command(operation, id))).await.unwrap(); } @@ -140,7 +235,7 @@ impl provider_host_server::ProviderHost for ReferenceHost { .await .unwrap(); count += 1; - if count == 9 { + if count == 12 { tx.send(Ok(command(ProviderOperation::Shutdown, "shutdown"))) .await .unwrap(); @@ -298,6 +393,36 @@ impl ProviderPlugin for FixturePlugin { } } +struct ExtensionFixture; + +#[tonic::async_trait] +impl gamenode_plugin_sdk::ExtensionPlugin for ExtensionFixture { + async fn handle(&self, _: ProviderCommand, _: HostClient) -> Result { + Ok(OperationResult { + disposition: OperationDisposition::Completed as i32, + ..Default::default() + }) + } + async fn configure( + &self, + command: ProviderCommand, + host: HostClient, + ) -> Result { + let context = host.context(); + Ok(OperationResult { + disposition: OperationDisposition::Completed as i32, + configuration: Some(ConfigurationResult { + session_id: context.session_id.clone(), + profile_id: String::new(), + window_id: command.target_operation_id, + accepted: true, + failure: String::new(), + }), + ..Default::default() + }) + } +} + #[tokio::test] async fn independent_plugin_uses_brokers_and_cancels_a_pending_login() { let temp = tempfile::tempdir().unwrap(); @@ -314,7 +439,7 @@ async fn independent_plugin_uses_brokers_and_cancels_a_pending_login() { let _ = stopped.await; }), ); - let session = Session::open( + let session = Session::open_with_options( Launch { endpoint, credential: vec![9; 32], @@ -323,10 +448,26 @@ async fn independent_plugin_uses_brokers_and_cancels_a_pending_login() { "fixture.plugin", "fixture", "1.0", - &[capability::CONTEXT], + &[capability::CONTEXT, capability::CONFIGURE], + gamenode_plugin_sdk::SessionOptions { + min_api_major: 1, + min_api_minor: 1, + max_api_major: 1, + max_api_minor: 6, + features: vec![(capability::FEATURE_API_METADATA.into(), true)], + session_kind: SessionKind::Provider, + target_game: None, + }, ) .await .unwrap(); + assert_eq!(session.host.describe_api().await.unwrap().api_minor, 6); + assert_eq!( + session.host.get_permissions().await.unwrap().grants[0].permission_id, + capability::CONTEXT + ); + let mut changes = session.host.watch_permission_changes(3).await.unwrap(); + assert_eq!(changes.message().await.unwrap().unwrap().revision, 4); let plugin = Arc::new(FixturePlugin { started: Semaphore::new(0), cancelled: Semaphore::new(0), @@ -339,7 +480,7 @@ async fn independent_plugin_uses_brokers_and_cancels_a_pending_login() { .unwrap() .unwrap(); let mut results = std::collections::BTreeMap::new(); - for _ in 0..9 { + for _ in 0..12 { let (id, result) = completed.recv().await.unwrap(); results.insert(id, result); } @@ -385,6 +526,78 @@ async fn independent_plugin_uses_brokers_and_cancels_a_pending_login() { Some(1_700_000_000) ); assert!(results["sign-out"].signed_out); + assert_eq!( + results["config-open"] + .configuration + .as_ref() + .unwrap() + .window_id, + "config-open" + ); + assert!( + !results["config-open"] + .configuration + .as_ref() + .unwrap() + .accepted + ); + let _ = shutdown.send(()); + server.await.unwrap().unwrap(); +} + +#[tokio::test] +async fn extension_session_keeps_target_scope_through_lifecycle_dispatch() { + let temp = tempfile::tempdir().unwrap(); + let endpoint = temp.path().join("extension.sock"); + let listener = tokio::net::UnixListener::bind(&endpoint).unwrap(); + let (tx, mut completed) = mpsc::channel(16); + let reference = ReferenceHost { completed: tx }; + let (shutdown, stopped) = oneshot::channel(); + let server = tokio::spawn( + tonic::transport::Server::builder() + .add_service(plugin_host_server::PluginHostServer::new(reference.clone())) + .add_service(provider_host_server::ProviderHostServer::new(reference)) + .serve_with_incoming_shutdown(UnixListenerStream::new(listener), async { + let _ = stopped.await; + }), + ); + let target = TargetGameContext { + game_id: "steam:620".into(), + installation_id: "install-1".into(), + profile_id: "default".into(), + revision: "r7".into(), + }; + let session = Session::open_extension( + Launch { + endpoint, + credential: vec![9; 32], + operation_id: "extension-launch".into(), + }, + "fixture.plugin", + "1.0", + target.clone(), + &[capability::GAME_LAUNCH, capability::CONFIGURE], + ) + .await + .unwrap(); + assert_eq!(session.host.context().provider_id, ""); + assert_eq!(session.host.context().target_game.as_ref(), Some(&target)); + gamenode_plugin_sdk::run_extension(session, Arc::new(ExtensionFixture)) + .await + .unwrap(); + let mut results = std::collections::BTreeMap::new(); + for _ in 0..12 { + let (operation, result) = completed.recv().await.unwrap(); + results.insert(operation, result); + } + assert_eq!( + results["config-open"] + .configuration + .as_ref() + .unwrap() + .window_id, + "config-open" + ); let _ = shutdown.send(()); server.await.unwrap().unwrap(); } @@ -394,3 +607,96 @@ fn public_models_do_not_expose_session_secrets_in_diagnostics() { let secret = models::SessionCredential::new("fixture-secret").unwrap(); assert!(!format!("{secret:?}").contains("fixture-secret")); } + +#[test] +fn detailed_errors_keep_safe_categories_and_structured_denials() { + use gamenode_plugin_protocol::prost::Message; + use gamenode_plugin_sdk::DetailedError; + let detail = DenialDetail { + reason: DenialReason::Revoked as i32, + permission_id: "files.read".into(), + grant_revision: 8, + }; + let status = Status::with_details( + tonic::Code::PermissionDenied, + "private request value", + detail.encode_to_vec().into(), + ); + assert_eq!( + DetailedError::from_status(&status), + DetailedError::Denied(Some(detail)) + ); + assert_eq!( + DetailedError::from_status(&Status::unauthenticated("token")), + DetailedError::Unauthenticated + ); + assert_eq!( + DetailedError::from_status(&Status::failed_precondition("stale")), + DetailedError::Stale + ); + assert_eq!( + DetailedError::from_status(&Status::unimplemented("future")), + DetailedError::Unsupported + ); + assert_eq!( + DetailedError::from_status(&Status::invalid_argument("invalid")), + DetailedError::Invalid + ); + assert_eq!( + DetailedError::from_status(&Status::unavailable("offline")), + DetailedError::Unavailable + ); + assert!( + !format!( + "{:?}", + DetailedError::from_status(&Status::permission_denied("private request value")) + ) + .contains("private request value") + ); +} + +#[test] +fn sdk_extension_helpers_preserve_unselected_application_namespaces() { + use gamenode_plugin_sdk::extensions::ExtensionSet; + use std::collections::HashMap; + let payload = |schema_id: &str, note: &str| ExtensionPayload { + schema_id: schema_id.into(), + schema_version: 1, + schema_digest: vec![3; 32], + data: Some(prost_types::Struct { + fields: std::collections::BTreeMap::from([( + "note".into(), + prost_types::Value { + kind: Some(prost_types::value::Kind::StringValue(note.into())), + }, + )]), + }), + }; + let wire = HashMap::from([ + ( + "org.example.selected".into(), + payload("org.example.selected.v1", "old"), + ), + ( + "org.other.unknown".into(), + payload("org.other.unknown.v8", "keep"), + ), + ]); + let mut extensions = ExtensionSet::from_wire(wire).unwrap(); + let patch = ExtensionPatch { + expected_revision: 4, + typed_field_mask: vec![], + namespaces: vec![ExtensionNamespacePatch { + namespace: "org.example.selected".into(), + operation: Some(extension_namespace_patch::Operation::Set(payload( + "org.example.selected.v1", + "new", + ))), + }], + }; + assert_eq!(extensions.apply_patch(&patch, 4), Ok(5)); + assert_eq!( + extensions.as_map()["org.other.unknown"], + payload("org.other.unknown.v8", "keep") + ); +} diff --git a/crates/plugin-sdk/tests/settings_reference_host.rs b/crates/plugin-sdk/tests/settings_reference_host.rs index 95b7f3723..7de216939 100644 --- a/crates/plugin-sdk/tests/settings_reference_host.rs +++ b/crates/plugin-sdk/tests/settings_reference_host.rs @@ -28,6 +28,7 @@ struct ReferenceHost { #[tonic::async_trait] impl plugin_host_server::PluginHost for ReferenceHost { + type WatchPermissionChangesStream = tokio_stream::Empty>; async fn open_session( &self, request: RpcRequest, @@ -40,10 +41,13 @@ impl plugin_host_server::PluginHost for ReferenceHost { return Err(Status::permission_denied("not granted")); } Ok(Response::new(OpenSessionReply { + resource_context: None, session_id: "session".into(), granted_capabilities: self.grants.clone(), api_major: 1, api_minor: self.minor, + features: vec![], + support_window: None, })) } async fn submit_discovery( @@ -52,6 +56,24 @@ impl plugin_host_server::PluginHost for ReferenceHost { ) -> Result, Status> { Err(Status::permission_denied("not granted")) } + async fn describe_api( + &self, + _: RpcRequest, + ) -> Result, Status> { + Err(Status::unimplemented("fixture")) + } + async fn get_permissions( + &self, + _: RpcRequest, + ) -> Result, Status> { + Err(Status::unimplemented("fixture")) + } + async fn watch_permission_changes( + &self, + _: RpcRequest, + ) -> Result, Status> { + Err(Status::unimplemented("fixture")) + } } #[tonic::async_trait] @@ -181,10 +203,14 @@ impl Harness { operation_id: id.into(), account_epoch: 8, profile_epoch: 5, + session_kind: SessionKind::Unspecified as i32, + target_game: None, }), operation: settings.operation() as i32, target_operation_id: String::new(), settings: Some(settings.clone().into()), + runtime_session_result: None, + runtime_session_context_result: None, achievements: None, })) .await diff --git a/crates/plugin-steam/src/runtime.rs b/crates/plugin-steam/src/runtime.rs index f73b84dbb..87952086c 100644 --- a/crates/plugin-steam/src/runtime.rs +++ b/crates/plugin-steam/src/runtime.rs @@ -166,6 +166,7 @@ impl ProviderPlugin for SteamPlugin { name: r.name.unwrap_or_default(), install_dir: r.install_dir, fields: r.fields.into_iter().collect(), + target: None, }) .collect(), install_root: scan.install_root, diff --git a/crates/plugin-steam/src/runtime/tests.rs b/crates/plugin-steam/src/runtime/tests.rs index 222bd049f..e9c1fdd54 100644 --- a/crates/plugin-steam/src/runtime/tests.rs +++ b/crates/plugin-steam/src/runtime/tests.rs @@ -96,6 +96,7 @@ fn authorize(context: Option<&ServiceContext>) -> Result<(), Status> { #[tonic::async_trait] impl plugin_host_server::PluginHost for Host { + type WatchPermissionChangesStream = tokio_stream::Empty>; async fn open_session( &self, request: Request, @@ -109,9 +110,12 @@ impl plugin_host_server::PluginHost for Host { return Err(Status::permission_denied("invalid launch")); } Ok(Response::new(OpenSessionReply { + resource_context: None, session_id: "reference".into(), api_major: API_MAJOR, api_minor: API_MINOR, + features: vec![], + support_window: None, granted_capabilities: hello.requested_capabilities, })) } @@ -121,6 +125,24 @@ impl plugin_host_server::PluginHost for Host { ) -> Result, Status> { Err(Status::unimplemented("stream only")) } + async fn describe_api( + &self, + _: Request, + ) -> Result, Status> { + Err(Status::unimplemented("reference fixture")) + } + async fn get_permissions( + &self, + _: Request, + ) -> Result, Status> { + Err(Status::unimplemented("reference fixture")) + } + async fn watch_permission_changes( + &self, + _: Request, + ) -> Result, Status> { + Err(Status::unimplemented("reference fixture")) + } } #[tonic::async_trait] @@ -394,6 +416,8 @@ async fn execute( operation_id: id.into(), account_epoch: epoch, profile_epoch: 1, + session_kind: SessionKind::Unspecified as i32, + target_game: None, }), operation: kind as i32, ..Default::default() @@ -432,6 +456,8 @@ async fn execute_achievements( operation_id: id.into(), account_epoch: epoch, profile_epoch: 1, + session_kind: SessionKind::Unspecified as i32, + target_game: None, }), operation: ProviderOperation::ReadAchievements as i32, achievements: Some(request.into()), @@ -739,6 +765,7 @@ impl Harness { operation_id: id.into(), account_epoch: epoch, profile_epoch: 1, + ..Default::default() }), operation: kind as i32, ..Default::default() diff --git a/docs/development.md b/docs/development.md index 59f598cbb..51d0c912e 100644 --- a/docs/development.md +++ b/docs/development.md @@ -1,5 +1,33 @@ # Native development +## OpenSpec task and design navigation + +Use the repository helper to query OpenSpec's structured task data and retrieve +only the task or design section needed for the current work. It falls back to +reading `tasks.md` directly if the OpenSpec CLI is unavailable. + +```sh +python3 scripts/spec_progress.py status +python3 scripts/spec_progress.py status --change add-third-party-plugins --section 7 +python3 scripts/spec_progress.py next --change add-third-party-plugins --design-section 11 +python3 scripts/spec_progress.py show 7.7 +python3 scripts/spec_progress.py outline +python3 scripts/spec_progress.py outline --section 11 +``` + +Use `next` to print progress, the full next pending task and, optionally, one +numbered section from `design.md` in a single helper invocation. Add `--section` +to select the next pending task within a task section. When more than one change +is active or available, pass `--change` to avoid selecting one implicitly. + +`status --json` exposes the raw apply payload; `show --line-numbers` and +`outline --json` are available when exact source locations or machine-readable +output are useful. For code navigation in repositories with a `.codegraph/` +index, use `codegraph explore ""` before broad +text searches. Keep design documents targeted: inspect the outline first, then +retrieve the relevant numbered section rather than printing a large `design.md` +in full. + See [CONTRIBUTING.md](../CONTRIBUTING.md) for the commit-message convention used by developers and AI agents. @@ -48,10 +76,52 @@ helper `scripts/bundled_plugins.py` to derive the bundled plugin executables fro `plugins/*.toml`, and fails with an actionable message when Python 3.11+ is missing. Native Linux and Windows builds require their corresponding prerequisites above. -This change does not configure hosted CI runners; its verification commands are -run locally, and cross-compilation does not replace native OS acceptance. +CI runs the Linux checks and a Windows cross-compilation check; cross-compilation +does not replace native OS acceptance. + +### Native Windows acceptance + +Cross-compiled checks (`cargo xwin check` or `cargo xwin test`) show that the +Windows build compiles; they are not native acceptance. Record native Windows +runs in [windows-verification.md](windows-verification.md), keep a change's +native Windows acceptance task open until such a run is recorded, and do not +claim native Windows execution in a pull request without one. + +## Scoped verification for implementation tasks + +Start with the smallest checks that exercise the changed behavior: the focused test +or test filter, formatting for changed Rust files, `git diff --check`, and the +relevant OpenSpec validation. Expand to the directly affected crate when the +change crosses module boundaries or lacks a focused test. Run workspace-wide +tests, Clippy or builds when the change affects shared contracts across crates, +a focused check exposes an integration issue, the task explicitly requires the +broader check, or release readiness is being evaluated. Do not run the full +project test suite by default for a scoped task. Record any unrun broader checks +as such instead of implying they passed. + +For example: + +```sh +cargo test --locked -p gamenode-app custom_launch_without_its_own_grant +``` + +Supervised Linux launch fixtures, including the reviewed shared-resource launch, spawn the host +binary in its internal helper mode. They skip when `GAMENODE_TEST_HELPER_BINARY` is unset; point it +at a built binary to exercise them: + +```sh +cargo build --locked -p gamenode-app --bin gamenode --no-default-features +GAMENODE_TEST_HELPER_BINARY="$PWD/target/debug/gamenode" \ + cargo test --locked -p gamenode-app --lib reviewed_shared_resource_use +``` + +## Full workspace and release checks (both platforms) -## Required checks (both platforms) +These broader checks are appropriate for workspace integration, release +readiness or when a change specifically calls for them. They are not the default +validation for every individual implementation task; use +[Scoped verification for implementation tasks](#scoped-verification-for-implementation-tasks) +first. ```sh pnpm --dir ui build @@ -212,6 +282,7 @@ without touching the native host: | Unavailable watched folder | `?watches=unavailable` seeds `D:\Jogos` and the unavailable `E:\Itch`; `?library=variants` also includes them | | Pending backup changes | Settings › **Backups**, change the destination, the automatic switch or the copies kept; the changed dots and unsaved bar appear until **Save changes** or **Revert** (no fixture is pre-dirty) | | Stopped community plugin | Settings › **Plugins**; **Prateleira Local** starts stopped. **Start** creates its session and **Stop** stops it again | +| Live third-party plugin lifecycle | `?plugins=lifecycle` adds a signed Dolphin provider with two games. Settings › **Plugins** › **Details** removes it from the sidebar and library immediately; **Accept, install and enable** in the import form reinstalls it, and the rescan adds a third game. **Disable** marks the plugin unavailable but keeps its cached games visible | | Nightly cache | Settings › **Tools** › **Download cache**; 0.8.0-pre1 is the Nightly row and 0.7.9 is In use | | Non-Windows mode | `?platform=linux` hides the General › Startup card, the Epic card and the Windows-only Tools/ports surfaces, and makes DRM-free games and Backups report that they are unavailable | @@ -249,6 +320,8 @@ default fixture; the default counts stay unchanged. | Marked as not a game | `steam:1302` | Wallpaper Foundry | Not-a-game note; no suggestions | | DRM-free running | `manual:brasa` | Brasa | Running session timer, matched `ongoing`, launch arguments, save folder, active protection and 12 backups | | DRM-free unmatched | `manual:drift` | Drift | Unmatched DRM-free row with two scored suggestions | +| GameCube-emulated | `dolphin:pikmin` | Pikmin | Match dialog narrowed to NGC by default; **Show all** adds the Switch release | +| Wii-emulated | `dolphin:metroid` | Metroid Prime | Match dialog narrowed to Wii; the platform-less release stays hidden until **Show all** | | Family shared, not installed | `steam:7` | Glass Garden | Install primary and the Steam Family note | | Hidden | `steam:900` | Hidden Harbor | Hidden until **Show hidden** | @@ -398,7 +471,11 @@ Use the **Details panel** toggle and these fixtures: - **Match** — `?library=variants`, select **Neon Courier 2088**, then **Review…**. The ambiguous row opens three candidates at 96%, 74% and 38%; selecting one - changes the preview and **Match** commits it. + changes the preview and **Match** commits it. Select **Pikmin** (`dolphin:pikmin`) + or **Metroid Prime** (`dolphin:metroid`) to exercise the platform filter: the + dialog shows only the entry's platform (NGC or Wii) until **Show all** is used, + and an answer with no matching platform shows the filtered-empty notice instead + of a failed search. The other rows declare no platform and keep the full list. - **Add to GameNode** — select a matched game and choose **Add to GameNode**. The dialog has the five statuses and collection counts. **New collection** creates a collection; the name **Collection limit** answers with the localized @@ -615,7 +692,7 @@ scripts/dev-windows-wsl.sh ``` The launcher builds the Windows desktop and its bundled plugins under -`target/windows-hmr`, verifies the plugins sit beside the host, prepares its +`windows-hmr` in the Cargo target directory (`target/windows-hmr` by default), verifies the plugins sit beside the host, prepares its backup assets, starts a local Vite server, and opens the Windows app. It forces the real Tauri bridge rather than the UI mock. It uses the same Windows Credential Manager entry and local application data as the installed app, so an existing session can be restored and changes diff --git a/docs/fixtures/plugin-target-compatibility.json b/docs/fixtures/plugin-target-compatibility.json new file mode 100644 index 000000000..140e0b649 --- /dev/null +++ b/docs/fixtures/plugin-target-compatibility.json @@ -0,0 +1,55 @@ +{ + "schema": 1, + "id": "org.example.target-compatibility", + "kind": "extension", + "name": "Target Compatibility Example", + "version": "1.0.0", + "api": { "min": "1.6.0", "max": "1.6.0" }, + "publisher": { "key_id": "fixture", "public_key": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=" }, + "license": { "expression": "MIT", "files": ["licenses/LICENSE"] }, + "targets": [ + { + "os": "windows", + "arch": "x86_64", + "abi": "msvc", + "entrypoint": "bin/windows-x64/plugin.exe", + "requires": { + "windows": { + "product": "client", + "min_version": "10.0", + "min_build": 22000, + "max_build": 26100 + } + }, + "tested_on": [{ "product": "windows-11", "release": "23H2" }] + }, + { + "os": "linux", + "arch": "x86_64", + "abi": "gnu", + "entrypoint": "bin/linux-gnu-x64/plugin", + "requires": { + "linux": { + "libc": { "family": "glibc", "min_version": "2.36" }, + "distributions": [ + { "id": "debian", "versions": ["13", "13.1"] }, + { "id": "fedora", "versions": ["43"] } + ] + } + }, + "tested_on": [{ "distribution": "debian", "version": "13" }] + }, + { + "os": "linux", + "arch": "x86_64", + "abi": "musl", + "entrypoint": "bin/linux-musl-x64/python-plugin", + "requires": { + "linux": { + "libc": { "family": "musl", "min_version": "1.2.4" } + } + }, + "tested_on": [{ "distribution": "alpine", "version": "3.21" }] + } + ] +} diff --git a/docs/fixtures/save-descriptor-roadmap.json b/docs/fixtures/save-descriptor-roadmap.json new file mode 100644 index 000000000..89641d802 --- /dev/null +++ b/docs/fixtures/save-descriptor-roadmap.json @@ -0,0 +1,55 @@ +{ + "documentary_only": true, + "example_schema_version": 1, + "records": [ + { + "id": "unclassified", + "artifact_kind": "unknown", + "format": null, + "logical_size_bytes": 131072, + "content_binding": null, + "last_loaded": null, + "image": {"kind": "illustrative_artwork", "producer": "fictional-art-plugin", "captured_at": null, "logical_reference": "example-art"}, + "extensions": {"example.future": {"schema_version": 7, "unrecognized_field": {"retain": true}}} + }, + { + "id": "battery-save", + "artifact_kind": "in_game_save", + "profile_id": "example-battery-profile", + "format": {"id": "example.battery", "version": "1", "size_constraints": {"minimum_bytes": 8192, "maximum_bytes": 32768, "source": "fictional-producer-format-description"}}, + "logical_size_bytes": 8192, + "content_binding": {"game_id": "example-game-a", "variant": "fictional-region-r1", "content_fingerprint": null}, + "compatibility": {"outcome": "compatible", "producer": "fictional-runtime-plugin", "observed_at": "2026-11-14T12:00:00Z", "basis": "fictional-format-description", "source_runtime": "example-runtime-a@1", "target_runtime": "example-runtime-b@2", "limitations": ["Only the stated in-game format and content variant; no save-state claim"]}, + "last_loaded": null + }, + { + "id": "runtime-state", + "artifact_kind": "save_state", + "profile_id": "example-state-profile", + "format": {"id": "example.runtime-state", "version": "4", "size_constraints": null}, + "source_runtime": {"id": "example-runtime-a", "version": "1", "core": "example-core@4"}, + "content_binding": {"game_id": "example-game-a", "variant": "fictional-region-r1", "content_fingerprint": {"algorithm": "sha256", "digest": "1111111111111111111111111111111111111111111111111111111111111111", "producer": "fictional-runtime-plugin"}}, + "slot": {"namespace": "example.runtime-a", "name": "quick-slot"}, + "compatibility": {"outcome": "unknown", "producer": "fictional-runtime-plugin", "target_runtime": "example-runtime-b@2", "basis": "No evidence for another runtime's state format"}, + "last_loaded": {"producer": "fictional-runtime-plugin", "observed_at": "2026-11-14T12:05:00Z", "basis": "reported-successful-load", "runtime": "example-runtime-a@1", "artifact_id": "runtime-state", "game_id": "example-game-a"}, + "image": {"kind": "save_associated_capture", "producer": "fictional-runtime-plugin", "captured_at": "2026-11-14T12:05:01Z", "association_basis": "producer-reported-artifact-association", "logical_reference": "example-capture"} + }, + { + "id": "shared-card", + "artifact_kind": "shared_container", + "format": {"id": "example.virtual-card", "version": null, "size_constraints": null}, + "backing_resource": "example-card-resource", + "affected_games": ["example-game-a", "example-game-b"], + "entries": [{"artifact_id": "battery-save", "slot": {"namespace": "example.card", "name": "slot-a"}}, {"artifact_id": null, "slot": {"namespace": "example.card", "name": "slot-b"}}], + "whole_container_restore_authorized": false + }, + { + "id": "converted-save", + "artifact_kind": "in_game_save", + "format": {"id": "example.destination-battery", "version": "2", "size_constraints": null}, + "import": {"source_artifact_id": "battery-save", "original_producer": "fictional-runtime-plugin", "importer": "fictional-import-plugin"}, + "conversion": {"input_artifact_id": "battery-save", "input_fingerprint": null, "converter": "fictional-converter", "converter_version": "0.1", "source_format": "example.battery@1", "target_format": "example.destination-battery@2", "source_runtime": "example-runtime-a@1", "target_runtime": "example-runtime-b@2", "observed_at": "2026-11-14T12:10:00Z", "parameters": {"example_mode": "preserve-original"}, "validation": "unknown", "known_losses": null, "original_preserved": true}, + "last_loaded": null + } + ] +} diff --git a/docs/linux-verification.md b/docs/linux-verification.md index c245f7f1c..62eaf02db 100644 --- a/docs/linux-verification.md +++ b/docs/linux-verification.md @@ -57,9 +57,9 @@ No item below is marked as executed by this change's automated checks. systemd user units). - [ ] Sync preferences persist across restarts and remain keyboard accessible. -The process adapter's Linux unit test asserts `Unsupported` for listing and -watching. This tests the adapter contract; it does not replace the native -window-close and integration checks above. +The process adapter's Linux unit tests cover `/proc` listing, real parent identity, +reused-PID refusal and confirmed exit watching. Native playtime, window-close and +integration acceptance above still require a native Linux run. ## Issue #2: experimental tar launcher diff --git a/docs/local-state.md b/docs/local-state.md index 57d7053ed..07fc3ee2b 100644 --- a/docs/local-state.md +++ b/docs/local-state.md @@ -59,13 +59,32 @@ preference leaves the latest geometry in place. | Table | Holds | | --- | --- | | `library_entries` | Every game a provider has detected, keyed `:`, with its install folder, extra scan fields, `installed`, `owned` and `family_shared` flags and first/last seen times. Rows are never deleted: a game a completed scan no longer finds is marked `installed = 0`, so its matches and cover return with it. | +| `library_installations` | The opaque installation id plugins see for each library entry, keyed by entry key. The id is 128 random bits assigned the first time a plugin projection needs it and never changed, so it survives rescans, renames and match changes without revealing the store id or a path. Rows are never deleted. | +| `library_display_overrides` | The display name a provider's plugin set for one of its own entries, keyed by entry key, with a per-entry revision that starts at 1 and only grows. The detected name stays in `library_entries`; clearing an override sets the name to `NULL` and keeps the row so the revision keeps counting. | +| `library_artwork_overrides` | The cover a provider's plugin set for one of its own entries, keyed by entry key: `file` names an image in the covers folder (`plugin--.jpg` or `.png`, decoded, shrunk to fit 600 x 900 and re-encoded by the host) that only that entry uses, with a per-entry revision that starts at 1 and only grows. The matched game's own cover is never touched; clearing an override sets `file` to `NULL` and keeps the row so the revision keeps counting. | +| `plugin_custom_launch_recipes` | Plugin-scoped launch recipes keyed by owner and recipe id, with an installation id, revision and typed JSON. The JSON contains opaque host handles rather than executable paths or secret values; paths and secrets are resolved by the host when launching. | +| `library_launch_recipe_selection` | One user's active recipe per library entry, including its plugin identity, recipe and detected-target revisions, and the fingerprint of the exact launch plan the user approved. A missing row means the detected target remains selected; stale rows are retained until the user repairs the recipe or explicitly returns to the detected target. | +| `plugin_runtime_resources` | Plugin-owned approved runtime resources, keyed by owner and runtime id with a revision and typed JSON. Executable locations remain host-resolved and are never exposed as plugin supplied paths. | +| `plugin_runtime_content_bindings` | Plugin-owned bindings between a GameNode game and a runtime content item for an installation, with revision checks so content moves or runtime changes invalidate the previous launch plan. | +| `plugin_runtime_catalog_state` | Per-owner revision for the runtime resource catalog, advanced when its resources or bindings change so an existing launch approval cannot survive catalog edits. | +| `plugin_bundles` | One installed bundle: its id, name, version, publisher fingerprint, SHA-256 of the signed `bundle.json` and the Unix time the mapping was recorded. A bundle only groups packages; it owns no payload, grant or session. | +| `plugin_bundle_components` | The components of an installed bundle: plugin id, kind (`provider` or `extension`), component archive SHA-256 and package version. A plugin id belongs to at most one bundle; a standalone package has no row. Removing a row removes the grouping only, never the component package. | +| `plugin_bundle_history` | One previous mapping of an installed bundle, archived by a bundle update: bundle id, version, name, publisher fingerprint, SHA-256 of the signed `bundle.json`, the original installed time and when it was archived. It exists only so a rollback can restore the component set and package versions that were active before the update; it owns no payload, grant or session. | +| `plugin_bundle_history_components` | The component rows of one archived bundle mapping: plugin id, kind, component archive SHA-256 and package version. Restoring a version moves these rows back into `plugin_bundle_components` and removes the history entry. | | `provider_scans` | Per provider, the time of the last successful scan and the last error, plus the last owned (`last_catalog_at`, `catalog_error`) and family (`last_family_at`, `family_error`) catalog sync. A failed scan or catalog phase records the error and keeps the previous facts. | | `store_accounts` | The last connected account of a store provider: `provider`, `account_id`, optional `account_name` and optional `last_verified_at`. It holds no cookie, token or password. | | `auto_matches` | The GameNode game ids the server reported for a store id, per `(category, uid)` and PC. An empty list means the server knows no game. | -| `chosen_matches` | The user's own match per `(account_id, entry_key)`. A null `game_id` means "no GameNode game". Each account keeps its own choices. | +| `chosen_matches` | The explicit match per `(account_id, entry_key)`, made by the user or, through the plugin API, by the entry's own provider plugin (`source` is `user` or `plugin`; a plugin never replaces a `user` choice). A null `game_id` means "no GameNode game". Each account keeps its own choices. | | `favorites` | Each account's favorite GameNode games per `(account_id, game_id)`, with `is_favorite`, `pending` (a local change GameNode has not confirmed) and `updated_at`. A false, confirmed row is deleted. Favorites survive sign-out and stay hidden from other accounts. | | `games` | GameNode game name, release year, cover URL and cover state (`cover_file`, `cover_failed_at`) for display without the network. | +Migration `0025_plugin_bundles.sql` adds the two bundle tables as additive STRICT +tables. An upgraded database keeps every existing row, and packages installed on +their own stay ungrouped because no bundle row exists for them. +Migration `0026_plugin_bundle_history.sql` adds the two history tables used only +by bundle update rollback; it is additive, starts empty and changes no current +mapping. + Saving a provider's scan is one transaction: it either fully applies or leaves the previous entries as they were. Migration `0006_store_accounts_and_catalog.sql` adds the independent `owned`/`family_shared` entry facts, the four catalog sync @@ -99,6 +118,28 @@ application data directory (`DataPaths::covers_dir`). The folder is created on first use. Files are written atomically and are kept when a game is uninstalled or the user signs out. Unreferenced files are not cleaned up yet. +## Third-party plugin storage + +The private key/value data of third-party plugins is stored outside the application database, in +`plugin-data////storage.sqlite3` below the application +data directory (`DataPaths::plugin_data_dir`). There is one small SQLite file per plugin and account +profile, created the first time the plugin writes a `PERSISTENT` value; reading never creates one. +Directory names are the identity with unsafe characters written as `%XX` (or a digest when the name +would be too long), so no name can leave the folder. The `entries` table holds each key, value, +revision and optional expiry, and `meta` the highest revision ever used so revisions keep growing +across deletions and restarts. Session-only values are never written to disk. + +The same file holds the folders the user approved for the plugin's file access, in a `file_roots` +table (store schema version 2): per installation and kind, the folder (a canonical path, kept only +by the host), the volume and node it had when approved, the operations allowed, the library entries +that shared it, and when it was approved or revoked. These rows are not charged to the plugin's +quota, and the plugin never sees them: it receives only opaque handles. + +The location is for the user and the host only: the plugin API never accepts or returns it. Nothing +cleans these folders up yet (unused-data cleanup and the uninstall keep/delete choice are separate +tasks), so removing a plugin leaves its data in place. A store written by a newer version is refused +and left untouched, and a damaged file is reported as unavailable, never replaced. + Opening a fresh database creates migration history and applies every migration. A step 1 database gains the library tables and keeps its settings; a step 1 build refuses the upgraded database under its newer-schema rule and @@ -127,6 +168,40 @@ reopen, durable settings, ordered upgrade (including from a step 1 database), rollback and unchanged newer-schema files, and for rescans, uninstalls, failed scans, per-account matches, the layout and sign-out. +## Durable shared data pool + +Public shared-data records a plugin publishes with `storage.persist` are stored outside the +application database, in `plugin-shared-data.gnpersistence` below the application data directory. The +file is separate from `gamenode.sqlite3` and from the private plugin stores, so a durable +publication can outlive its producer session without making private storage public. It is created +the first time a durable publication is accepted; a session-only publication is never written to +disk. + +The host derives an opaque owner key from the signed plugin identity and the active account +profile, and records the profile generation that last wrote. A plugin request never supplies or +sees that key, a path or a physical location. + +| Table | Holds | +| --- | --- | +| `shared_records` | One published record: host record id, owner key, dataset and optional resource id, optional category, sharing class, schema id and version, structured JSON fields or opaque payload (exactly one), host-assigned provenance (plugin id, publisher fingerprint, profile id, declared developer, origin, package version and digest), observed and received times, update and optional expiry times, producer sequence and observation id, record revision, pool revision and the logical bytes it is charged. `(owner_key, dataset_id, resource_id)` is unique: a publish with that resource id replaces the previous record in place and keeps its record id, while a publish without one appends a new record with a new host id. | +| `shared_state` | The persisted monotonic pool revision shared by lists and watches; it only grows and survives restarts. | +| `shared_owners` | The opaque owner key and the profile generation it last accepted. A write from an older profile generation fails closed. | +| `shared_retention` | Per-owner age and byte limits chosen by the user. Missing values mean no age limit and the host default size ceiling. | + +A record is charged its identifiers, provenance, payload and a small fixed overhead. Expiry is +bounded by the producer's requested time-to-live and the existing maximum. Retention pruning +removes expired rows first and then, when the owner crosses its age or byte limit, the oldest +unprotected rows up to a bounded number per pass. Protection is host-only and never set by a +plugin, and pruning one owner never removes another owner's rows. Usage (record count, logical +bytes, effective limits) is available to the host for settings; the plugin API exposes neither a +stored value nor a physical path. + +A session-only publication keeps today's behavior: it stays in the in-memory broker and ends with +the producer's session. A durable publication requires both `data.publish` and `storage.persist`; +a missing `storage.persist` is an explicit failure, never a session-only downgrade. Schema +upgrades run in order and keep existing records, a database written by a newer build is refused +and left untouched, and a damaged file is reported as unavailable rather than replaced. + ## Playtime (migration `0003_playtime.sql`) `playtime_sessions` holds `id`, `account_id`, `entry_key`, nullable `game_id`, diff --git a/docs/pc-ports.md b/docs/pc-ports.md index 9dde061c5..2173fa3d4 100644 --- a/docs/pc-ports.md +++ b/docs/pc-ports.md @@ -281,8 +281,8 @@ can run. GameNode only checks that the folder has `eboot.bin` and `sce_sys/param ### The pinned PS4 PKG extractor (task 1.2) The overlay pins [`paulomanrique/ps4-pkg-extractor`](https://github.com/paulomanrique/ps4-pkg-extractor). -It is a small command-line tool with an open licence that runs on Windows and fails with a -clear message for an encrypted retail package. +It is a small command-line tool with an open licence that runs on Windows, and GameNode +maps its decryption failures to a clear encrypted-package message. | Finding | Value | | --- | --- | @@ -294,11 +294,41 @@ clear message for an encrypted retail package. | Executable inside the tool folder | `pkgextract.exe`, at the archive root | | Argument template | `["{package}", "-o", "{out}", "--overwrite"]` | +The public metadata was checked against the GitHub release on 2026-11-21: the release +`v0.0.1` (published 2026-03-06) publishes +`pkgextract-x86_64-pc-windows-msvc.zip` with the API digest +`sha256:0c736ee02779fb5cf4403a91da23f94fdaa72debf995be0c400ac9c36acee63a`, which matches +the overlay pin. The README documents the `pkgextract.exe` binary and the +`pkgextract ` usage; the source shows `-o/--output` and `-f/--overwrite`, so the +long `--overwrite` in the template is accepted. The Unlicense text is in the repository. + +### Extractor evaluation + +Public command-line extractors were compared for a Windows build, a clear licence, CLI +use, output layout and update handling. Only the selected tool is pinned; the others are +recorded so a future overlay update can revisit the choice. + +| Candidate | Licence | Windows CLI | Output and update handling | Decision | +| --- | --- | --- | --- | --- | +| `paulomanrique/ps4-pkg-extractor` `v0.0.1` | Unlicense | `.zip` with `pkgextract.exe` | Writes the game tree directly under `-o `; one package per run and no merge, so GameNode merges the update (D8) | **Pinned** | +| `Antti/orbis` `v0.6.0` | Apache-2.0 | `.zip` with the `orbis` CLI | `extract` writes the game tree; `install update.pkg --base ... --merge` merges in place but needs a prior extraction and keeps a `.orbis-install` sidecar, so it is a stateful two-command flow that does not fit the single-run `{package}`/`{update}`/`{out}` template | Not pinned; candidate for a future overlay update | +| `mathisto/pkgextract` | LGPL-3.0 | Single-file `PkgTool.exe` | Writes game files under `\uroot`, so the recipe would need a fixed subfolder | Not pinned | +| `murums04/ps4-pkg-extractor-ui` | GPL-3.0 | No; desktop GUI | Queues games and updates into title folders, but is not scriptable | Not pinned | + +`paulomanrique/ps4-pkg-extractor` was chosen because its output lands at the slot's +output root, its single-package CLI maps directly to `{package}` and `{out}`, and its +Unlicense has no redistribution conditions for the pinned helper. Its dependency on +`orbis-pkg-util` (MIT OR Apache-2.0) skips package entries whose key it lacks and reports +decryption failures from the package or PFS layer. The runner maps output that names an +encrypted package, a decryption failure or a missing key to the encrypted-package failure +below; if the tool fails without naming encryption, the output folder fails the slot's +markers and the job reports the missing markers instead. + The tool's usage is `pkgextract -o `. It takes **one package per run** and has no update or merge option. It also refuses an output folder that already exists unless `--overwrite` is passed; the runner pre-creates an empty output folder, so -the template must keep that flag. Those facts were checked against a base and update -package from a dump the developer owns on Windows: +the template must keep that flag. The maintainer's Windows check, recorded here when the +pin was authored, used a base and update package from a dump the developer owns: - the base package produced 28,830 files (31.5 GB); - the update package produced a partial tree of 442 files: 423 replace files in the base @@ -436,8 +466,10 @@ process group elsewhere) so cancelling or quitting kills its process tree. Its w directory is the staging folder. Its arguments come only from the overlay template: `{package}`, `{update}` and `{out}` are replaced with canonicalized paths, each as its own argument, and no other braces are allowed. Combined stdout and stderr keep the last -64 KiB for the failure details. If the output looks like an encrypted retail package, the -job fails with a message that GameNode ships no keys. +64 KiB for the failure details. A single run is stopped after six hours by default, so a +hung tool cannot hold the install worker; the timeout and cancellation are polled every +25 ms and either one kills the whole process tree. If the output looks like an encrypted +retail package, the job fails with a message that GameNode ships no keys. A tool that takes one package per run is run twice when the slot has an update. The base extracts straight into the slot's output folder. The update extracts into diff --git a/docs/plugin-api-field-contracts.md b/docs/plugin-api-field-contracts.md new file mode 100644 index 000000000..06f107eb7 --- /dev/null +++ b/docs/plugin-api-field-contracts.md @@ -0,0 +1,47 @@ +# Plugin API field contracts + +The checked [endpoint field policy fixture](../crates/plugin-protocol/contracts/endpoint_field_policy.json) +is derived from [OpenSpec design section 18](../openspec/changes/add-third-party-plugins/design.md#18-per-endpoint-typing-and-extensible-catalogs). +It records each route's rigid request and response fields, extension or opaque-byte allowance, +access model, and protobuf contract status. +The fixture test requires every current `PluginHost`, `ProviderHost`, `ResourceHost`, Saves, +Locations, StorageDiagnostics, Computer, GamePresence, and GamePerformance RPC to appear exactly +once with matching generated request/response types. The formerly planned save-profile, location, +report-query, and aggregate routes now have typed protobuf contracts and checked service catalogs. + +The `ProviderHost.Exchange` entry is bidirectional. Its event-family table separately classifies +readiness, account status, catalog chunks, operation results, and runtime-session observations. +Exchange commands/results retain typed operation, account/profile/session context, and correlation +fields. Only explicitly designated descriptive domain records may contain namespaced extensions. +Secrets and login cookies are excluded from generic metadata export. Settings retain their closed +form schema. Configuration-window lifecycle messages carry typed session/profile/window handles +and outcomes. + +The matrix is a wire-contract inventory, not a claim that every described API is mounted by the +desktop host. These protobuf contracts do not imply that host-service implementations are +complete or callable. + +The runtime-session Exchange family now has typed `RuntimeSessionReport` and +`RuntimeSessionResult` messages with `game.sessions.report` authorization and correlated outcomes. +One plugin may implement adapters for several runtimes; Core consumes only the common lifecycle +reports and does not contain emulator-specific detection. The first report is limited to the +authenticated extension's host-selected game and installation and an approved content/runtime +binding. To report another game or installation from the same running runtime instance, the +extension requests a context using proposed identifiers; the host resolves the current library and +binding, checks the active session/profile/grant and requires a fresh, non-rememberable user +confirmation. Reports for the new context must carry the opaque host-issued context id. It is +session-only, bound to the runtime instance and approved target/revisions, expires after 30 seconds +without an accepted report, and does not survive a session restart. A new context requires fresh +active evidence and confirmation. + +Adapters should report at least every 10 seconds. `observed_at` is Unix time in seconds; the host +rejects a report more than 30 seconds old or more than 5 seconds in the future. Report expiry is +measured independently from host monotonic receipt time, so plugin wall clocks cannot extend a +session. Each game transition closes the prior interval at the last accepted observation and starts +the new one at the approved event timestamp; time between them stays unattributed. `GamePresence` +is descriptive metadata: it cannot start, extend or confirm a measured playtime session. +Runtime-session observations are sensitive and may be projected through Data only under the +relevant sharing consent; process handles, credentials and launch tokens are never part of that +projection. + +Rust SDK patch preservation is covered by `crates/plugin-sdk/tests/reference_host.rs`. diff --git a/docs/plugin-api-permissions.md b/docs/plugin-api-permissions.md new file mode 100644 index 000000000..813810843 --- /dev/null +++ b/docs/plugin-api-permissions.md @@ -0,0 +1,1555 @@ +# Plugin API 1.6 method permissions + +This page maps the API 1.6 methods to their required grants. `ResourceHost` +routes are listed in the checked +[`resource_host.json`](../crates/plugin-protocol/contracts/resource_host.json) +catalog; Saves, Locations, StorageDiagnostics, Computer, GamePresence and +GamePerformance routes are listed in +[`domain_host.json`](../crates/plugin-protocol/contracts/domain_host.json). Both +catalogs record ownership, permission, pagination, quota, revision, idempotency +and commit-time authorization. Contract tests compare every catalog route to +the generated protobuf descriptors. Unknown routes remain `UNIMPLEMENTED`. + +The route tables below describe the API contract, not a claim that every route +is currently served. The implemented resource adapters cover library reads, +presentation, storage, files, network, notifications, standard launch/install, +jobs, backups, tools, PC ports, logical libraries/roots and the four `Data*` +methods. Saves and Locations also have handlers; +custom launches and the other domain services remain +unimplemented. `DescribeApi` lists exactly the served methods; generated +bindings alone do not establish availability. The persisted +`PermissionGrantStore` has not yet been wired into RPC sessions: handlers +check the grants negotiated for the session. Treat checks described for +unserved handlers as requirements, not evidence of runtime enforcement. + +| Methods | Permission | +| --- | --- | +| `LibraryList`, `LibraryGet`, `LibraryWatch` | `library.read` (whole-library reads require `library.read.all`) | +| `MetadataUpdate` | `library.metadata.write` | +| `FavoritesList`, `FavoritesSet` | `favorites.read`, `favorites.write` | +| `MatchingSearch`, `MatchingAssign` | `matching.read`, `matching.write` | +| `ArtworkRead`, `ArtworkSet` | `artwork.read`, `artwork.write` | +| `GamesRequestLaunch` | `game.launch` | +| `GamesProposeCustomLaunch`, `GamesRequestCustomLaunch`, `GamesRemoveCustomLaunch` | `game.custom_launch` | +| `GamesRequestInstall` | `games.install` | +| `StorageGet`, `StoragePut`, `StorageDelete` | `storage.read`, `storage.write`, `storage.delete`; durable writes additionally require `storage.persist` | +| `FilesRequestAccess`, `FilesList`, `FilesRead`, `FilesWrite`, `FilesDelete` | corresponding `files.read`, `files.write`, `files.delete` grants, plus explicit game/root approval | +| `NetworkFetch` | `network.fetch` | +| `NotificationsPublish` | `notifications.publish` | +| `BackupsList`, `BackupsRequestCreate`, `BackupsRequestRestore` | `backups.read`, `backups.create`, `backups.restore` | +| `LibrariesList`, `LibrariesGet`, `LibrariesWatch` | `library.roots.read` | +| `LibrariesCreate`, `LibrariesAddRoot` | `library.roots.create` | +| `LibrariesUpdate`, `LibrariesUpdateRoot` | `library.roots.update` | +| `LibrariesRemove`, `LibrariesRemoveRoot` | `library.roots.delete` | +| `RuntimesList`, `RuntimesGet`, `RuntimesWatch` | `game.runtime.read` | +| `RuntimesRegister` | `game.runtime.create` | +| `RuntimesRequestAccess` | `game.runtime.create`; the host picker approves one exact executable | +| `RuntimesUpdate` | `game.runtime.update` | +| `RuntimesRemove` | `game.runtime.delete` | +| `GamesRegisterContent` | `library.discovery` | +| `StorageDiagnosticsPublishBenchmark`, `StorageDiagnosticsPublishSmart` | `storage.diagnostics.publish` | +| `ComputerPublishHardware` | `computer.hardware.publish` | +| `GamePresencePublish`, `GamePresenceClear` | `game.presence.publish` | +| `GamePerformancePublishSamples`, `GamePerformanceEndSeries` | `game.performance.publish` | +| `DataPublish` | `data.publish`; `PERSISTENT` additionally requires `storage.persist`. Accepts custom datasets; `SESSION_ONLY` stays in host memory and `PERSISTENT` enters the owner-scoped public pool | +| `DataGet`, `DataList`, `DataWatch` | authenticated resource session plus owner access or the host's current dataset/record sharing policy; selectors request authorized scopes but grant no access | +| `PersistenceGetUsage`, `PersistenceListEntries`, `PersistenceDeleteEntries`, `PersistenceClear`, `PersistenceSetRetentionPolicy` | `storage.persist`, restricted to the caller's namespace | +| `ToolsList`, `ToolsRequestApply`, `ToolsRequestRemove` | `tools.read`, `tools.apply`, `tools.remove` | +| `PortsList`, `PortsDetail`, `PortsRequestInstall` | `ports.read`, `ports.install` | +| `JobsGet`, `JobsWatch`, `JobsCancel` | the permission of the operation that created the job, plus ownership of the job (see [Jobs](#jobs)) | + +The domain services use these grants. This build serves the `Saves`, `Locations` and `StorageDiagnostics` methods listed below; the remaining service rows describe reserved methods: + +| Service methods | Permission | +| --- | --- | +| `Saves.ListProfiles`, `Saves.GetProfile` | `game.saves.read` | +| `Saves.CreateProfile` | `game.saves.create` | +| `Saves.UpdateProfile` | `game.saves.update` | +| `Saves.RemoveProfile` | `game.saves.delete` | +| `Locations.Inspect`, `GetSize`, `GetAccess`, `GetLastModified`, `GetFingerprint`, `Compare`, `WatchAvailability` | `game.storage.inspect` or `game.saves.inspect`, according to the approved resource | +| `StorageDiagnostics.List`, `Get`, `Watch` | `storage.diagnostics.read` plus the user's explicit sensitive-data projection review | +| `Computer.List`, `Get`, `Watch` | `computer.hardware.read` plus the user's explicit sensitive-data projection review | +| `GamePresence.List`, `Get`, `Watch` | `game.presence.read` plus the user's explicit sensitive-data projection review | +| `GamePerformance.List`, `Get`, `Watch`, `QuerySeries`, `Aggregate` | `game.performance.read` and either the selected common category/record grant or the explicit sensitive-data projection review | + +`GamesRequestLaunch` has a dedicated `GameLaunchRequest` and `game.launch` +grant. It uses the approved detected target and stored parameters without +per-call overrides. The custom-launch proposal, execution, and removal methods +use `CustomLaunchRequest` where applicable and the independent +`game.custom_launch` grant. Custom recipes require their own user review and +cannot be authorized by `game.launch`. `GamesRequestLaunch` and `GamesRequestInstall` are served +and need the user's intent, described under [Launching and installing](#launching-and-installing); +the custom-launch methods are not served yet. + +## Common data is an explicit per-query choice + +List/get/watch and relevant data queries use an optional typed +`CommonDataSelector`. Its `categories` list supports game paths, game +performance history, runtime catalogs, content availability, library roots and +save profiles; `selected_record_ids` names individual published records. A +category selector requires its category grant, while each selected id requires +its record grant and does not require category-wide access. Omitting the +selector or sending it empty returns only data visible to the caller in its own +scope. Selectors request data; they do not grant authority. The contract +requires the host to check each requested scope on every query. Activation +grants only make queries eligible and do not trigger reads or delivery. +Sensitive/custom datasets still require their separate sharing review, and +secrets remain excluded. `Data.Get`, `Data.List` and `Data.Watch` accept this +selector in the current host. `Runtimes.List`, `Runtimes.Get` and +`Runtimes.Watch` accept only `RUNTIME_CATALOG`; the shared projection includes +producer provenance and extension namespaces but never an executable handle. +`Library.List`, `Library.Get` and `Library.Watch` accept only +`CONTENT_AVAILABILITY`; the projection adds safe content/runtime identities +without paths, handles or bytes. Every other category on those domain routes is +`UNIMPLEMENTED`. `Data.Publish` creates custom-class records and +does not classify them as one of the common categories. The category enum is a +set of consent scopes, not a guarantee that every domain data source is +currently populated; see [Shared plugin data](plugin-shared-data.md) for the +served producer/consumer contract and its source limitations. Other domain +routes remain unserved unless `DescribeApi` says otherwise. + +The former `include_common` boolean and string `selected_categories` fields +remain deprecated at their original wire numbers for draft-client decoding. +Hosts must ignore them for authorization and data inclusion. + +## Host-side authorization audit + +The mounted provider API retains a bounded recent history (256 entries) of +authorization denials for diagnostics and permission UI. Each record identifies +the acting plugin and provider, requested permission, denial reason, and grant +revision. The history is available only to host code; it is not exposed through +plugin RPCs. Session credentials, operation identifiers, cookies, and request +payloads are omitted. This is currently an in-memory denial history for the +provider API; it is not yet a unified audit stream for all API 1.6 services. +The separate permission-grant store has a bounded persisted domain-mutation +audit model, but it is not yet connected to live RPC authorization. + +## Library reads + +`LibraryList`, `LibraryGet` and `LibraryWatch` are plugin-initiated, so they do +not belong to a provider operation. `OpenSession` returns a `resource_context` +for sessions that negotiated API 1.6 or later; every Library request carries it. +It is bound to the session, its kind and target game, and the active profile. It +adds no authority: the session still needs `library.read`, and a context from +before a profile change is stale. A missing account profile is `UNAVAILABLE`, an +unknown or foreign context is denied, and a missing grant is `PERMISSION_DENIED` +with a recorded audit event. + +- **Scope.** With `library.read` a plugin sees only entries of its own provider. + Naming another provider in `provider_id` does not widen that. `library.read.all` + admits every provider and `provider_id` then narrows the result. A foreign + installation is reported as `NOT_FOUND`, indistinguishable from an unknown id. +- **Identity.** `installation_id` is 128 random bits assigned and stored by the + host the first time an entry is projected; it never changes across rescans, + renames or match changes and reveals neither the store id nor a path. `game_id` + is the matched GameNode game, or empty when the entry has no single match. + Several installations may share one `game_id`. An entry is projected only once + its id is stored, so a failed write hides it instead of issuing a temporary id. +- **Get.** The installation is the target. `game_id` alone works when exactly one + admitted installation matches it; with several the call fails with + `FAILED_PRECONDITION` and the caller names an `installation_id`. Naming both + requires them to agree. +- **Fields.** Entries carry provider, name, install state (`installed`, `owned`, + `shared`), a revision and the two ids. They carry no store id, install folder, + scan fields, credentials or account data. `version` is empty. +- **Pagination.** Entries are ordered by `installation_id`. The page size defaults + to 50 and is capped at 200. A cursor is signed by the host and bound to the + query, session, profile, grant revision and library revision, and it expires + after 5 minutes. A cursor from another query or session, an expired one, or one + issued before the library changed fails with `FAILED_PRECONDITION` and no + entries; the caller restarts the list. A cursor the host did not issue is + `INVALID_ARGUMENT`. +- **Watch.** `after_revision = 0` starts at the current revision without a + backlog. Otherwise the host replays up to 256 retained events after that + revision; an older position is `FAILED_PRECONDITION` (list again and watch from + its revision) and a future one is `OUT_OF_RANGE`. Events are `upserted` or + `removed`. Each delivery rechecks the session, profile and grants, and the + stream ends with the denial when they change. A session holds at most 8 watches, + and a watcher that falls behind is ended and must list again. +- **Common data.** Selecting a common-data category or record (for example the + runtime-availability projection) is refused with `UNIMPLEMENTED` rather than + silently narrowed; that projection is planned with task 14.4. + +## Display metadata and favorites + +`MetadataUpdate` (`library.metadata.write`), `FavoritesList` (`favorites.read`) and +`FavoritesSet` (`favorites.write`) use the same resource context as the Library reads and only +ever reach the caller's own provider's entries, whatever other grants it holds. + +- **Display name.** `display_name` is the only writable field. A request with another key in + `display_fields`, or with none, is `INVALID_ARGUMENT`. The value is trimmed, at most 256 bytes + and free of control characters; an empty value clears the override. The override is stored apart + from the detected facts, so clearing restores the detected name. While set it is the library + title, ahead of the matched game's name and the detected name, and it is exposed as + `LibraryEntry.display_name` (empty when unset) next to the unchanged `name`. +- **Target.** The installation is named by `installation_id` (required). A `game_id`, if given, + must be that installation's current match. A foreign or unknown installation is `NOT_FOUND`, + even for a plugin that holds `library.read.all`. +- **Revision.** `expected_revision` must be the entry's `metadata_revision`: 0 until the name is + first written, then the revision of the last change, which only grows (clearing counts). An + obsolete revision returns `MUTATION_OUTCOME_REVISION_CONFLICT` with the current revision and + writes nothing. Writing the value the entry already has is `MUTATION_OUTCOME_ALREADY_APPLIED` + with an unchanged revision; a change is `MUTATION_OUTCOME_APPLIED` with the new revision. +- **Favorites.** A favorite belongs to the GameNode game, never to the entry, and a rematch does + not move it. `FavoritesList` returns the favorite state of each GameNode game matched by an + entry of the caller's provider, ordered by game id, with the Library paging and cursor rules + (its own cursors; a changed library or another query makes one stale). `FavoritesSet` needs an + own entry currently matched to that game, otherwise `NOT_FOUND`, which is also the answer for a + game only another provider has. It goes through the same local-first path as the user's own + star, so syncing to GameNode still follows the user's sync setting. Setting the state the game + already has is `ALREADY_APPLIED`. `profile_id` must be empty or the active profile's id, or the + call is `FAILED_PRECONDITION`. +- **No favorite revision.** Favorites carry no revision: `expected_revision` must be 0, replies + and list entries carry revision 0, and a write is a desired-state, last-write-wins setting. This + deviates from per-resource revisions on purpose, because the local state has no revision to + guard and an idempotent boolean has nothing to conflict with. +- **Idempotency.** Every mutation needs an `idempotency_key` of 1 to 128 bytes without control + characters. The host remembers committed outcomes per plugin and profile for 24 hours, at most + 1024 keys per plugin; a retry of the same key and request returns the original outcome, while + the same key with another request is `FAILED_PRECONDITION`. Conflicts are not remembered. The + table is in memory, so a replay after a restart is not recognized; it still fails safely, + because metadata is guarded by its revision and favorites are idempotent by nature. +- **Commit and ordering.** Mutations run one at a time. Authorization, including the grant + revision, is checked again where the change commits (under the engine lock for favorites, on + the storage worker for metadata), so a revocation that wins the race stops the write. A failed + database write is `UNAVAILABLE`. + +## Matching + +`MatchingSearch` (`matching.read`) and `MatchingAssign` (`matching.write`) use the same resource +context as the Library reads. They reuse the library's own match policy, so a plugin never opens or +disturbs the match dialog the user may have open. + +- **Search.** One bounded page of GameNode catalog games for a title. `query` is trimmed, 1 to 128 + bytes and free of control characters. `page_size` defaults to 20 and is capped at 50; a + catalog search has no further pages, so `next_cursor` is always empty and a non-empty `cursor` + is `INVALID_ARGUMENT`. `platform` is reserved and must be empty, because the catalog has no + platform filter. Each `MatchCandidate` carries `game_id`, `title` and `release_year` (0 when + unknown); `platform` and `confidence` are empty because the catalog has neither, and the host + never invents a score. A plugin may start 20 searches per minute (across its sessions in a + profile); more is `RESOURCE_EXHAUSTED`. Search spends the user's verified GameNode session, so + without a verified, online session, or when GameNode cannot answer, it is `UNAVAILABLE`: an + unavailable catalog is never reported as an empty result. +- **Assign.** Matches one of the caller's own entries to a GameNode game. The entry is named by + `installation_id` (required); `provider_id` and `provider_game_id` are reserved and must be + empty, and `gamenode_game_id` is required. A foreign or unknown installation is `NOT_FOUND`, + even with `library.read.all`. The game must be one the host already knows (in the library's game + records) or one of the last 256 games plugin searches returned; any other game is `NOT_FOUND`, + so a plugin finds a game with `MatchingSearch` before assigning it. +- **Revision.** `expected_revision` is the entry's `LibraryEntry.revision`, which changes whenever + the entry's matched game, name, install state, display metadata or cover changes. A stale revision + returns `MUTATION_OUTCOME_REVISION_CONFLICT` with the current revision and writes nothing; the + plugin rereads the entry and retries. A change returns `MUTATION_OUTCOME_APPLIED` with the entry's + revision afterwards, and `resource_id` is the installation id. +- **Already applied.** An entry that already has an explicit choice of that game, made by the user + or by a plugin, is `MUTATION_OUTCOME_ALREADY_APPLIED` with its current revision, whatever + `expected_revision` says, and nothing is written. An entry that is only matched automatically is + not the same: assigning the same game stores an explicit choice, so later automatic rematching + keeps the game. +- **The user's choice wins.** The stored choice records who made it. A plugin can set or replace + its own choices, but when the user chose a game, or chose "no GameNode game", for the entry in the + match dialog, `MatchingAssign` is `FAILED_PRECONDITION` and changes nothing. The user choosing + again, including the game a plugin picked, makes the choice theirs; "forget my choice" in the + library removes it whoever made it. A plugin cannot clear a match. +- **Effects.** The choice is stored through the same path as the user's pick: it is per account, + survives a restart, and playtime totals are submitted for the new match as they are for the + user's own. A favorite stays on the game it was set on and is never moved by a rematch. +- **Idempotency and commit.** The idempotency, serialization and commit-time authorization rules of + the other mutations apply. Conflicts and refusals are not remembered, so a retry with the same + key and a fresh request is evaluated again. + +### Matching limits + +The matching limits are constants in `crates/app/src/plugin_host/resources/matching.rs` and +`crates/core/src/library/plugin_match.rs`. They were chosen by reasoning from limits the host +already has, not from measurements, and are open to change after a capacity review. + +| Limit | Value | Why | +| --- | --- | --- | +| Search query | 1 to 128 bytes | Titles are short. Half of the 256 characters the user's own match dialog accepts, and the same 128 bytes as idempotency keys and provider ids, so a plugin cannot use the user's session to send large payloads. | +| Results per search | default 20, at most 50, one page | The GameNode search endpoint is asked for 20 results (`SEARCH_LIMIT` in `crates/api/src/game.rs`), so 20 is what the user's own dialog shows and is the practical maximum today. 50 leaves headroom if that changes and stays well under the 200-item page cap of the Library lists. The catalog has no paging, so there is no cursor. | +| Searches per plugin | 20 per 60 seconds, per plugin and profile | One search every 3 seconds on average. That is enough for interactive matching of a screenful of entries and low enough that a plugin cannot turn the user's verified GameNode session into a bulk crawler. The window is a plain sliding minute and only counts accepted attempts. | +| Assignable offered games | 256, oldest dropped first | Bounds the memory a plugin can occupy with search results. Matches the 256 events the library watch retains, and is large enough for several searches of 20 results. Games already in the library's records are always assignable. | +| Installation id in Assign | at most 128 bytes | Host-issued ids are 128 random bits as hex; the bound only rejects abuse before lookup. | +| `release_year` in `MatchCandidate` | additive field, 0 when unknown | Titles alone do not separate remakes and reboots. The catalog already returns the year, and the user's dialog shows it. | + +Search spends the user's session, so the rate limit is the one most worth revisiting once there are +real plugins; the others only bound size. + +## Artwork + +`ArtworkRead` (`artwork.read`) and `ArtworkSet` (`artwork.write`) use the same resource context as +the Library reads and only ever reach the caller's own provider's entries, whatever other grants +it holds. The one artwork kind is the library **cover**: `artwork_kind` is `"cover"` or empty, and +anything else is `INVALID_ARGUMENT`. + +- **Target.** The entry is named by `installation_id` (required, at most 128 bytes). A `game_id`, + if given, must be that installation's current match. A foreign or unknown installation is + `NOT_FOUND`, even with `library.read.all`, and `ArtworkSet` does not decode a single byte for it. +- **Set is an override of the entry, not of the game.** The image becomes the cover of that one + entry. The matched game's own cover, which every entry of the game shares, is never touched, and + neither are other entries or other providers. The override is stored apart from the detected + facts and exposed as `LibraryEntry.artwork_revision`; it is the entry's cover in the library + until it is cleared. An empty `encoded_image` (with an empty `media_type`) clears it and + restores the game's cover. A `media_type` with no image is `INVALID_ARGUMENT`. +- **The host stores its own picture.** The bytes are untrusted. They are bounded first, then + decoded, shrunk and encoded again on a blocking worker; what is stored is the host's output, so + metadata (EXIF, ICC), trailing data and anything else the decoder skipped never reach the disk + or another reader. See the limits below. Refused images are `INVALID_ARGUMENT` with a message + naming the reason: not a PNG, JPEG or WebP picture, a `media_type` that does not match the + bytes, an animation, too many pixels, a damaged file or too many bytes. Nothing is written for + a refused image. +- **Revision.** `expected_revision` must be the entry's `artwork_revision`: 0 until a cover is + first set, then the revision of the last change, which only grows (clearing counts). An obsolete + revision returns `MUTATION_OUTCOME_REVISION_CONFLICT` with the current revision and writes + nothing. Setting the picture the entry already has (the same bytes after processing) is + `MUTATION_OUTCOME_ALREADY_APPLIED` with an unchanged revision; a change is + `MUTATION_OUTCOME_APPLIED` with the new revision, and `resource_id` is the installation id. + A cover change also changes `LibraryEntry.revision`. +- **Read.** `ArtworkRead` returns the cover the entry shows: the plugin's override if it set one, + else the matched game's own cover when it is already on this device. Nothing is downloaded for a + read, so an entry with no cover yet, a missing file or no matched game is `NOT_FOUND`. The reply + has the encoded image, its `media_type`, its `byte_length` and the entry's `artwork_revision` + (0 while the cover is the game's own). `max_bytes` is the caller's budget: 0 means the 5 MiB + maximum, a larger value is capped to it, and an image bigger than the budget is + `RESOURCE_EXHAUSTED` (nothing is truncated). +- **Resource references.** The image comes inline (`encoded_image`) or from a file the plugin may + read (`file_handle`, with `media_type` set as for inline bytes). Giving both, or a `file_handle` + with no `media_type`, is `INVALID_ARGUMENT`. The handle is the only reference there is: there is + no field that names a path or a URL, and a made-up, edited, expired or other-session handle is + `NOT_FOUND` like any other. The handle is checked as for `FilesRead`, and more: + - the plugin needs `files.read` besides `artwork.write` (without it, `PERMISSION_DENIED` and + nothing is read); + - it must be a regular-file handle of a current approval of **this same installation**; a handle + from the approval of another of the plugin's entries is `PERMISSION_DENIED` and a directory is + `FAILED_PRECONDITION`. A revoked approval or a revoked grant stops it at once; + - the host reads the file itself, at most 4 MiB plus one byte, on the plugin's namespace worker, + so a file over the bound is refused as "larger than 4194304 bytes" (the inline wording) without + being read whole, and the bytes then go through the same worker-side decode, pixel check and + re-encode as inline bytes. A damaged file or one whose type does not match is refused the same + way. The plugin never holds the bytes, and the host stores only its own picture; + - a retry is answered before the file is read again, from the handle and the declared type, so a + file that has since changed or gone does not change the answer to the same key. A different + file needs a different key, and `files.read` is checked again at commit. +- **Idempotency and commit.** The idempotency, serialization and commit-time authorization rules of + the other mutations apply. A retried key is answered before its image is decoded. The file is + written before the database row and the replaced file is deleted after it, so a crash leaves at + worst an unreferenced file, never a row that points at nothing. + +### Artwork limits + +The limits are constants in `crates/platform/src/plugin_artwork.rs` and +`crates/app/src/plugin_host/resources/artwork.rs`. Like the matching limits they were chosen by +reasoning from limits the host already has, not from measurements, and are open to change after a +capacity review. D31 had already fixed the formats (static PNG, JPEG, WebP) and that bytes and +pixels are bounded; the numbers are engineering detail. + +| Limit | Value | Why | +| --- | --- | --- | +| Encoded image | at most 4 MiB, inline or read from a file by handle | Plugin messages are capped at 8 MiB; this leaves room for the request around the bytes. The host's own cover downloads are capped at 5 MiB, and a 4 MiB source is far more than a cover needs. | +| Source pixels | at most 4096 x 4096 (16,777,216), no side over 8192 | A cover is shown at a few hundred pixels, so 16 megapixels is generous. The pixel count is read from the file header and checked *before* decoding, so a small file that expands into a huge bitmap is refused without allocating it. The side limit keeps thin strips from bypassing the count. | +| Decode memory | 128 MiB allocation limit; two decodes at once | A 16-megapixel RGBA16 image is 128 MiB. Two concurrent decodes bound what plugin pictures can occupy at any moment to a quarter gigabyte; more wait. | +| Stored size | fits in 600 x 900, aspect kept, never enlarged | The library grid draws covers at roughly 200 to 300 pixels wide; 600 x 900 (2:3, like the game covers) is about twice that for high-density screens. Stored covers are at most a few hundred KiB, so a plugin cannot grow the covers folder much, and each entry keeps at most one override file. | +| Output format | JPEG (quality 88), or PNG when a pixel is transparent | Covers are JPEG everywhere else. Transparency would be lost in JPEG, and a fully opaque alpha channel is not worth a larger PNG. | +| Formats | static PNG, JPEG, WebP | From D31. GIF, BMP, SVG and anything else are refused by signature; animated PNG (APNG) and animated WebP are refused. The signature decides, not the declared `media_type`, which must agree. | +| Read budget | `max_bytes` 0 means 5 MiB, capped at 5 MiB | The largest cover the host stores is a downloaded one at the 5 MiB download cap. | +| Installation id | at most 128 bytes | Same as the other mutations. | + +There is no per-plugin rate limit for `ArtworkSet`. Writes are serialized, at most two pictures are +decoded at once and a retried key does no decoding, which bounds CPU and memory but not how often a +plugin may replace its cover. Revisit this with the rate limits once there are real plugins. + +## Private storage + +`StorageGet` (`storage.read`), `StoragePut` (`storage.write`, plus `storage.persist` for durable +writes) and `StorageDelete` (`storage.delete`) keep a plugin's own small, non-secret data. They use +the same resource context as the other services and need no other grant. + +- **The namespace is the plugin, not a request field.** Data belongs to the authenticated plugin id, + its pinned publisher fingerprint and the active GameNode account profile. A request carries a + `key` and nothing that could name another owner, a path or another profile, and a key that looks + like a path or an identity (`../x`, `org.other/k`) is just a key in the caller's own namespace. + Two plugins, two publishers of the same plugin id and two accounts never see each other's keys, + usage or quota. Official providers use trusted host adapters instead and get + `FAILED_PRECONDITION`. +- **Durability is explicit.** `StoragePut.durability` must be `SESSION_ONLY` or `PERSISTENT`; + `UNSPECIFIED` is `INVALID_ARGUMENT`. A `PERSISTENT` write without `storage.persist` is + `PERMISSION_DENIED` (the denial detail names `storage.persist`) and stores nothing, in memory or on + disk: the host never turns it into a volatile success. `SESSION_ONLY` needs only `storage.write`. + Reads and deletes of values already stored need only `storage.read` and `storage.delete`, so + revoking `storage.persist` stops new durable writes without hiding or trapping existing data. +- **Two layers, one key space.** A *session-only* value stays in the host's memory and is discarded + when the plugin's last open session ends or the account profile changes. A *persistent* value + survives restarts until it is deleted or expires. A key lives in one layer at a time: writing it + with the other durability moves it (its previous copy is removed), and `StorageGetReply.durability` + says where it is now. +- **Revisions.** A key's revision is 0 while it does not exist and `expected_revision` of the next + put or delete must equal it, so a first write sends 0. An obsolete revision returns + `MUTATION_OUTCOME_REVISION_CONFLICT` with the current revision and changes nothing. Revisions come + from one counter per namespace that survives deletions, layer moves and restarts, so a key that is + deleted and created again never repeats a revision a stale writer may still hold. A put always + writes (`MUTATION_OUTCOME_APPLIED`); deleting a key that is not there is + `MUTATION_OUTCOME_ALREADY_APPLIED` with revision 0, whatever `expected_revision` says. +- **Lifetime.** `ttl_seconds` 0 means the value does not expire; otherwise it expires that many + seconds after the write, up to 30 days (`INVALID_ARGUMENT` beyond). `expires_at` (Unix seconds, + 0 for none) is returned by the put and the get. An expired value is a key that does not exist and + frees its space. +- **Quota.** Each layer of a namespace may hold `QUOTA_BYTES` (16 MiB) of logical data. A write + that would exceed it is `RESOURCE_EXHAUSTED` ("nothing was changed") and leaves every stored value, + including the one it would have replaced, as it was: durable writes check the quota and write in + one transaction. The put reply carries `usage_bytes` and `quota_bytes` of the layer written. +- **Idempotency and commit.** Writes and deletes need an idempotency key like the other mutations. A + retry with the same request returns the original outcome without writing again; the same key with + another request is `FAILED_PRECONDITION`; a revision conflict or a failure is not remembered. The + caller's grants and the grant revision are checked again immediately before the first change, so a + revocation that wins the race stops the write. +- **No physical paths.** Replies and errors never contain a path or the name of a file. Durable data + is in a private store the host keeps for the plugin and the account, below its own data folder; + only the user, through the host's own administration, can see where. A plugin cannot ask for it, + and the Files service excludes every host persistence folder. +- **Non-secret versus Secret.** Storage is for preferences, caches and bookkeeping. It is not + encrypted and the host does not treat it as sensitive. Credentials, tokens and anything that must + not be readable by other software on the machine go through the provider `Secret` service, which + maps a logical key to the OS credential store (see "Provider secrets" in the development guide). + Secrets are never kept here. + +### Storage limits + +The constants are in `crates/platform/src/plugin_storage.rs`. The value size and the 16 MiB quota +come from the design; the rest were chosen by reasoning, not measured, and are open to change. + +| Limit | Value | Why | +| --- | --- | --- | +| Key | 1 to 256 bytes, no control characters | Keys are names, not data; the bound keeps the index small. | +| Value | at most 1 MiB | From the design. A value is read and written whole, and plugin messages are capped at 8 MiB. | +| Quota per layer | 16 MiB of logical bytes | From the design ("16 MiB private-data quota"). The 64 MiB managed total of the design also covers data of other services, which are not implemented yet. | +| Per-entry overhead | 64 bytes charged on top of key and value | An empty value must not be free, or a plugin could keep millions of keys without being charged. With it, 16 MiB holds at most about 260,000 entries. | +| Lifetime | `ttl_seconds` 0 (none) to 30 days | A plugin cannot ask for a lifetime it cannot also be cleaned up after; long-lived data uses no expiry. | +| Layers | quota applies to each layer alone | The session-only layer is host memory, so 16 MiB per plugin is the most it can hold; the durable layer has its own 16 MiB. | + +The quota counts logical bytes, not the size of the store file, which is larger (SQLite pages and +indexes). There is no per-plugin rate limit on writes; they are serialized per namespace, which +bounds contention but not frequency. The `Persistence*` methods and the host's future per-file +cleanup screen cover private storage; the durable public pool below has its own usage, deletion +and uninstall choice. + +## Durable shared public pool + +`DataPublish` with `PERSISTENT` writes to a host-owned public pool that is separate from private +`StoragePut(PERSISTENT)` data and from `plugin-persistence.sqlite3`. The request needs +`data.publish` plus `storage.persist`; without the second grant it is `PERMISSION_DENIED` and +nothing is stored, in memory or on disk. `SESSION_ONLY` remains the default and never reaches the +pool. + +- **Ownership and provenance.** The host derives the owner from the authenticated plugin id, + pinned publisher fingerprint and active account profile, and assigns the record id, revision, + provenance and timestamps. A request cannot name an owner, path or namespace. +- **Actual durability.** `DataMutationReply.durability` and `DataRecord.durability` report the + mode actually stored (`SESSION_ONLY` or `PERSISTENT`) and `expires_at` reports the expiry; there + is no silent downgrade. `UNSPECIFIED` in a request is `INVALID_ARGUMENT`. +- **Cross-session reads.** A consumer with the current category or selected-record grant can read + a durable record while the producer is stopped. Revocation, profile change, expiry and retention + fence reads and queued watches immediately; the producer does not have to reconnect. +- **Limits.** One record is at most 1 MiB. Each owner has a 64 MiB logical byte limit, an optional + user age limit (up to 365 days) and a producer TTL of at most 30 days. A write for the same + producer/dataset/resource replaces that producer's own record; another owner's record is never + replaced. Quota pruning removes the owner's oldest unprotected rows first and reports reclaimed + bytes. Protection and the retained-size/usage view are host-only. +- **Uninstall and reuse.** Uninstall offers keep or delete for a producer's durable records. + Keep archives them under the original owner: reads, lists, watches, usage and automatic pruning + skip them, and a reinstall cannot replace or read them before a separate confirmed host reuse + review. Delete removes only that owner's rows. Another owner's rows, private storage, grants and + library history are untouched. Bundle and component uninstall apply the same choice to every + component they removed. +- **No paths.** Replies and errors carry logical sizes, counts, limits and timestamps only. The + physical pool file and the private plugin stores are never exposed to plugins. The host's own + settings surface may show the managed files and their measured allocation (see + `docs/plugin-shared-data.md`); that accounting is a host command, not a route, so a plugin + cannot read it. +- **Publisher key change.** A changed publisher fingerprint is a new identity for both the private + store and the pool. Old records do not become readable and old grants do not apply. A designed + re-trust may be followed by a host-only, explicitly confirmed migration of compatible data; there + is no plugin RPC for its preview, apply or rollback, secrets and grants are never migrated, and + the new identity needs fresh sharing and retention reviews. + +## Files + +`FilesRequestAccess`, `FilesList` and `FilesRead` (`files.read`), `FilesWrite` (`files.write`) and +`FilesDelete` (`files.delete`) let a plugin work on files of a game installation. They are the +only way a plugin touches the user's files through the API, and they are closed by default: the +three grants are separate, off at installation, and even with them a plugin reaches only a folder +**the user approved for that plugin and that one installation**. + +- **Approval is the user's, per plugin and installation.** `FilesRequestAccess` names an + `installation_id` (one of the caller's own library entries; a `game_id`, if given, must be its + match), the operations wanted (`read`, `write`, `delete`) and the kinds of folder + (`installation`, `save`, `prefix`; empty means `installation`). It carries no path. The host asks + the user to choose the folder (starting at the installation's folder for `installation`) and then + to confirm the final scope: folder, operations and every game that shares it. A refusal is + `PERMISSION_DENIED`; a build with no approval dialog connected is `FAILED_PRECONDITION`; the + user has five minutes to answer; only one approval per plugin waits at a time (`ABORTED`). + Each requested operation needs its grant first, so the user is never asked for something the + plugin may not even request. +- **A plugin may suggest where the folder is.** `declared_locations` (additive) holds, per kind + `save` or `prefix`, where that folder usually is: an ordered list (earlier is preferred, at most 8 + per kind), each with a `location` and a one-line `description`. A suggestion is **only shown to the + user**, who takes one or chooses another folder; it grants nothing, and approval still needs the + user's confirmation of the full scope. + - `location` is an absolute path (`/opt/games/x`, `C:\Games\x`) or starts with a placeholder the + host expands: `{home}`, `{documents}`, `{appdata}` and `{localappdata}` (Windows), `{xdg_data}` + and `{xdg_config}` (Linux), optionally followed by plain names separated by `/` or `\`. + The text is at most 1024 bytes without control characters. + - A well-formed suggestion that cannot apply on this system is **dropped without an error**: a + placeholder or a drive or share path of the other system, a system folder that does not exist + (such as `{documents}` with no XDG user directory), a folder inside GameNode's private data, or + a duplicate. One list can therefore serve every platform. + - What is wrong with the request itself is `INVALID_ARGUMENT`, before the user is asked: an + unknown placeholder, a relative path (`saves/x`, `~/x`), `..`, an empty, overlong or + control-character text, a kind that is not `save` or `prefix` (the host already knows where an + installation is), more than 8 for one kind, or a description over 120 bytes, over one line or + with control or disguising characters (the notification text rules). The message never echoes + the location. + - Each suggestion reaches the approver labelled as declared by the plugin and not verified, with + whether the folder exists (only existence is checked: nothing is listed, opened or read). The + folder to start on is the host's own suggestion (an installation's known folder), else the first + suggestion that exists. The approver shows the description as plain text. + - The plugin is told nothing about which suggestions exist, which were shown or which was taken: + the reply is the same handles as without any suggestion. The suggestions of an approval that + already stands and covers the request are not looked at, and a read-only approval is not widened + by a suggestion: asking for `write` asks the user again. + - The approval records how the folder was chosen: `declared` if it is the same folder (by + canonical path) as a suggestion of the plugin, `user` otherwise. It is shown to the user, not + to the plugin. +- **What is remembered.** The approval is stored per plugin and account profile (beside its private + storage, not charged to its quota) and replaced when the same installation and kind are approved + again. Asking for the same or fewer operations later returns handles without asking; asking for + more asks again. It holds only while the set of games sharing the folder is still the one the user + confirmed: a game added to or removed from the folder, or a changed or replaced folder, stops it + (`FAILED_PRECONDITION`, "request access again") until it is approved again. +- **Shared folders.** The games that "share" a folder are the library entries, of any provider, + whose install folder is the root, inside it or contains it (links resolved). Approving a parent + such as a library folder names every game under it, and grants nothing across them beyond what + was confirmed and the operations approved: an approved read-only parent does not allow + writes, and a plugin approved for one game's folder has no way to name a sibling's. +- **Handles are opaque and belong to a session.** `FileHandle.handle` (and each `FileEntry.handle`, + and the `resource_id` of a write or delete) is a sealed token: it carries the approval and a + relative path but cannot be read, edited, forged, kept past the session or used by another + session, and two for the same file differ. A malformed, foreign, edited or revoked handle is + `NOT_FOUND`, all the same. The reply never contains an absolute path. +- **Every call re-checks.** From the handle the host re-derives: the approval exists and is not + revoked, it allows that operation, the games sharing the folder are the confirmed set, the folder + is still the approved one (same volume and node), and the plugin's grant for the operation is held + now. All of that, and the file work, run under the plugin's namespace lock, and a write or delete + rechecks the grants right before it changes anything, so a revocation cannot slip in between. +- **Confinement.** Below the root only plain path components exist. `..`, empty or absolute names, + separators, control characters and names over 255 bytes are refused before the disk is touched. + Symbolic links, junctions and other reparse points are never followed at any depth (a link is not + listed and naming one is `PERMISSION_DENIED`), so a folder swapped for a link after a listing is + refused when used; a directory on another volume is refused; devices, pipes and sockets do not + exist for the plugin. On Linux every step is an `openat` with `O_NOFOLLOW` from a directory + handle. On Windows each component is checked as a reparse point and the opened handle's final + path must be exactly the root plus the requested components. +- **The host's own folders are excluded.** The application data folder (database, private + plugin storage, packages, credentials) is reserved: it cannot be approved, a root inside it is + refused, and when an approved parent contains it the folder is not listed and nothing beneath it + can be reached. This holds even if the user picks a parent that contains it. +- **List.** `FilesList` takes a directory handle and returns entries sorted by name with opaque + child handles, size and modification time (Unix seconds); directories have size 0. `page_size` 0 + is 100, at most 200. The cursor is bound to the session and the directory; an edited or foreign + cursor is `INVALID_ARGUMENT`. A directory with more than 20,000 entries is `RESOURCE_EXHAUSTED` + instead of a partial list. +- **Read.** `FilesRead` returns up to `max_bytes` from `offset` (0 means 1 MiB; at most 4 MiB), + `next_offset` and `eof`. A directory handle is `FAILED_PRECONDITION`. +- **Write.** With `name` empty, `file_handle` is an existing file: `contents` go at `offset`, which + may not pass the end of the file (`OUT_OF_RANGE`), and with `truncate` the file ends where the + write does. With `name` set, `file_handle` is a directory handle and the file `name` is created, + or overwritten, inside it; a new file can only be written from offset 0, and a refused write + creates nothing. New names are one plain component that is valid on every platform: no + separators, `.`/`..`, `< > : " | ? *`, trailing space or dot, or reserved device names + (`CON`, `NUL`, `COM1`...), else `INVALID_ARGUMENT`. One call carries at most 4 MiB + (`INVALID_ARGUMENT`, write in several calls) and a file may not grow past 512 MiB + (`RESOURCE_EXHAUSTED`). The reply's `resource_id` is the handle of the written file. +- **Delete.** `FilesDelete` removes one regular file. Directories are never deleted, and nothing a + link points to is. +- **No revisions.** Files carry no revision: `expected_revision` must be 0. +- **Idempotency.** Writes and deletes need an idempotency key like the other mutations. A retry of + the same request returns the original outcome without acting again (so a retried append applies + once, and a retried delete is not `NOT_FOUND`); the same key for another request is + `FAILED_PRECONDITION`. `FilesRequestAccess` needs a key for its shape but is naturally + idempotent: an existing approval is reused. +- **Errors** never contain a path. `PERMISSION_DENIED` is outside the approved access, a missing + approval for the operation or an operating-system refusal; `NOT_FOUND` a missing file or unusable + handle; `FAILED_PRECONDITION` the approved folder or its sharing changed, or the wrong kind of + entry; `UNAVAILABLE` an I/O failure. +- **Not a sandbox.** These rules govern what the *API* does for a plugin. A plugin that runs as the + user can still use the operating system directly; nothing here confines native code. + +### File limits + +The constants are in `crates/platform/src/plugin_files.rs` and `crates/app/src/plugin_host/files.rs`. +None of the numbers comes from the design or a measurement: they were chosen by reasoning and are +open to change after a capacity review. + +| Limit | Value | Why | +| --- | --- | --- | +| Bytes per read or write call | at most 4 MiB (read default 1 MiB) | Plugin messages are capped at 8 MiB; 4 MiB leaves room for the request and bounds memory per call. Bigger files are moved in pieces. | +| Size of a file a plugin may grow | 512 MiB | Saves and memory cards are small; this keeps a runaway plugin from filling a disk in one chain of calls. It does not bound the total a plugin may write. | +| Entries read from one directory | 20,000 | A listing sorts and pages the whole directory each call, so the work per page is bounded. A larger directory is refused rather than cut short. | +| List page | default 100, at most 200 | Same as the other paged services. | +| Path depth, name length | 64 components, 255 bytes | Common filesystem limits; keeps handles small. | +| Path carried in a handle | at most 2,048 bytes | Entries deeper than that are not listed. | +| Time to answer an approval | 5 minutes | Long enough to find a folder, short enough not to leave a plugin waiting forever. | +| Remembered canonical library folders | 60 seconds | The sharing check runs on every call; this avoids resolving every library folder each time. | + +No per-plugin rate limit exists for file calls. Mutations of one plugin are serialized, and its +private-storage calls wait while one of its file calls runs, because both use the plugin's +namespace lock. + +### What is not covered yet + +- The suggestions of `declared_locations` reach the approver (`RootRequest.declared` and + `.preselected`), but no real dialog shows them yet: the approval dialog is task 10.9, which also + shows the "declared by the plugin, not verified" label, the existence marker and a folder chooser. + The Windows expansion of `{appdata}`, `{localappdata}`, `{documents}` and drive or share paths is + unit-tested through a stand-in for the system folders and type-checked for Windows, but has not + run on Windows. +- The approval dialog belongs to the settings UI (section 10). Until a build connects one + (`FileAccess::set_approver`), `FilesRequestAccess` answers `FAILED_PRECONDITION` for a new + approval; existing approvals keep working. +- The sharing check knows only the library's install folders. A save or prefix folder outside every + install folder may be shared with games the host cannot see; the confirmation names the games it + knows and the user judges the rest. +- Revoking an approval is a store operation the settings UI will call; no plugin API revokes one. +- Approval is limited to the caller's own library entries. Saves and runtime handles that exist + without a library entry arrive with the save-profile and location services. +- The Windows implementation was type-checked for the Windows target but has not been run; see + "Limitations" in `docs/development.md` for native acceptance. + +## Network fetch + +`NetworkFetch` (`network.fetch`) lets a plugin ask the host to fetch an HTTPS URL. The host is the +one on the network, so every rule below is enforced before data reaches the plugin. + +- **Two things are needed: the grant and an approved origin.** An origin is exactly scheme, host + and port (`https://api.example.com`, or `https://api.example.com:8443`); the default port is left + out and the host is lowercased. There are no wildcards, no paths and no prefixes: `www.` or + another subdomain, another port, `http`, and `api.example.com.evil.test` are all other origins. + Nothing is reachable until the user approves one, and the approved set is asked again for every + fetch and for every redirect, so approving, widening, narrowing or revoking takes effect on the + next call and stops a fetch already running. A refusal for scope is `PERMISSION_DENIED` with + the `DENIAL_REASON_SCOPE_DENIED` detail naming `network.fetch`, and is audited. +- **Only public addresses.** The host name is resolved by the client's own resolver, and the + connection is refused when **any** answer is loopback, private (10/8, 172.16/12, 192.168/16), + link-local (including the cloud metadata address 169.254.169.254), shared address space + (100.64/10), unique-local or site-local IPv6, multicast, unspecified, documentation, benchmarking, + reserved, Teredo, or an IPv4-mapped, NAT64 or 6to4 form that embeds such an IPv4 address. The + client connects to exactly the addresses that passed, so a name cannot pass the check and then + point elsewhere. A URL that names an address (`127.0.0.1`, `[::1]`, `2130706433`, `0x7f.1`) is + judged the same way before connecting. This holds even for an origin the user approved: a + plugin cannot use the host to reach the user's own machine or network. +- **Redirects** are followed by the host, at most 5, and every target must be an https URL of an + approved origin, checked before anything is sent to it. A redirect to an unapproved origin ends + the fetch with `PERMISSION_DENIED`; the plugin is never told where it pointed and the redirect + response's body is never read. `Authorization`, `Cookie` and `Proxy-Authorization` that the plugin + sent do not follow a redirect to another origin. 303, and POST after 301/302, continue as a GET + without a body; 307 and 308 repeat the method and body. +- **No credentials of GameNode.** The host adds none: no cookies, no authorization, no referer, + no GameNode session or token. The only header it adds is a `User-Agent` + (`GameNode-Desktop/ plugin-fetch`), which the plugin may replace. A plugin may send its own + `Authorization` or `Cookie` for its own service. +- **Nothing is shared between fetches.** There is no connection pool, no cookie jar and no + proxy. The system proxy settings are deliberately ignored: a proxy resolves names itself and would + bypass the address check. +- **Request shape.** `url` is an https URL of at most 2,048 bytes with no user name or password + (the fragment is dropped); `method` is empty (GET), `GET`, `HEAD`, `POST`, `PUT`, `PATCH` or + `DELETE`; at most 32 headers, names that are valid tokens (compared in lowercase, no + repeats), values of at most 4,096 bytes without control characters; the headers the host controls + (`Host`, `Content-Length`, `Transfer-Encoding`, `Connection`, `Upgrade`, `TE`, `Expect`, + `Proxy-*`, `Via`, `Forwarded`, `X-Forwarded-*`) cannot be sent. A body is at most 1 MiB and only for + POST, PUT, PATCH and DELETE. Anything else is `INVALID_ARGUMENT`, and nothing is fetched. +- **Bounds.** `max_response_bytes` 0 means 1 MiB and is capped at 8 MiB. A response over the budget + is `RESOURCE_EXHAUSTED`: it is refused as soon as the `Content-Length` or the bytes read exceed + the budget, and nothing is truncated. The budget counts the bytes on the wire: the host does not + decompress, so a plugin that sends `Accept-Encoding` receives the compressed bytes. `timeout_ms` 0 + or above 30 seconds means 30 seconds, and one deadline covers the whole fetch (every redirect and + the body); expiry is `DEADLINE_EXCEEDED`. +- **Reply.** `status_code` is the HTTP status of the final response (any status, including 4xx and + 5xx, is a reply, not an error). `headers` are lowercase, repeated headers joined with `, `, at + most 64 and 32 KiB (the rest are dropped). `body` is the opaque response. `final_origin` is the + origin of the final response, never a path, an address or the redirect chain. +- **Errors never say where.** `UNAVAILABLE` is "could not be reached" (DNS failure, connection + failure or a certificate that is not accepted), with nothing about addresses or names; + `FAILED_PRECONDITION` is too many redirects; `RESOURCE_EXHAUSTED` is also what a plugin gets + when it is over its allowance of running fetches (4 per plugin, 16 for all plugins; extra + fetches are not queued). +- **Not a sandbox.** Native plugins can still open their own sockets. This API controls what the + *host* fetches for them. + +### Network limits + +The 8 MiB response, 30 s deadline, exact HTTPS origins and the address and redirect checks come +from the design. The rest were chosen by reasoning, not measured, and are open to change. + +| Limit | Value | Why | +| --- | --- | --- | +| Response | 8 MiB cap, default 1 MiB | Design cap; the default keeps a careless call small. | +| Deadline | 30 s cap and default | Design cap. | +| Redirects | 5 | Browsers allow 20; legitimate API flows rarely need more than two, and each hop is another origin check and connection. | +| Request body | 1 MiB | Plugin messages are capped at 8 MiB; requests are small API calls. | +| URL, headers | 2,048 bytes; 32 headers of at most 4,096 bytes | Common server limits. | +| Response headers returned | 64, 32 KiB | Keeps a reply small. | +| Concurrent fetches | 4 per plugin, 16 in all | Bounds sockets and memory; over the allowance is `RESOURCE_EXHAUSTED`, not a queue. | + +There is no per-plugin rate limit and no total-bytes quota, so a plugin may fetch repeatedly. + +### What is not covered yet + +- The source of approved origins belongs to plugin activation and the permission store. Until it + is connected (`NetworkAccess::set_scopes`), no origin is approved and every fetch is denied. +- The client has been tested against local plain-HTTP servers with its address check relaxed, and + against the real strict client for the destinations it must refuse. A fetch over real TLS to a + public server has not been run in this environment. +- Proxy-only networks are not supported (system proxies are ignored on purpose). + +## Notifications + +`NotificationsPublish` (`notifications.publish`) lets a plugin ask Core to show a short notice. It +is plain text, attributed to the plugin, and it can do nothing but be read. + +- **Attribution is the host's.** The notice is shown as "From plugin ``", where the id is + the authenticated plugin of the session. The request has no field for a name, an icon or a + sender, so a plugin cannot pose as Core or as another plugin. +- **Text.** `title` is required, one line, at most 120 bytes. `body` is optional, at most 512 + bytes and 8 lines. Both are trimmed. Control characters (other than the line breaks of a body) + and characters that can disguise text are `INVALID_ARGUMENT`: bidirectional overrides and + isolates, zero-width space, word joiner, byte-order mark, line and paragraph separators, + interlinear annotation and tag characters. Joiners that real text needs (emoji sequences, + several scripts) are allowed. `locale` is a language tag of letters, digits and hyphens (such + as `en`, `pt-BR`) or empty. +- **Severity** is empty (info) or one of `info`, `success`, `warning`, `error`; anything else is + `INVALID_ARGUMENT`. +- **Localization.** `translations` (at most 8) are other versions of the text, each with its own + non-empty `locale`; a locale may appear once, the main text's included. Core shows the version + for the user's language: the exact locale, then the same language (the region-less tag first), + then the main `title`/`body`. Matching ignores case. A notice with no translation matching is shown + in the plugin's main text. +- **No markup, links or actions.** The host never interprets the text and passes it on exactly. Core + renders every field as plain text: ` [x](javascript:alert(2)) y'; + expect(plainText(hostile, 999, true)).toBe(hostile); + }); + + it('answers an empty string for anything that is not a string', () => { + for (const value of [undefined, null, 5, {}, []]) { + expect(plainText(value, 10)).toBe(''); + } + }); +}); + +describe('noticeSource', () => { + it('labels with the plugin id, made plain', () => { + expect(noticeSource(notice([['', 't', '']]))).toBe('org.example.plugin'); + const forged = { ...notice([['', 't', '']]), pluginId: 'Trusted \u202eevil' }; + expect(noticeSource(forged)).toBe('Trusted evil'); + }); +}); diff --git a/ui/src/api/pluginNotices.ts b/ui/src/api/pluginNotices.ts new file mode 100644 index 000000000..3f7a422b2 --- /dev/null +++ b/ui/src/api/pluginNotices.ts @@ -0,0 +1,92 @@ +import { listen, type UnlistenFn } from '@tauri-apps/api/event'; +import { getMockHost, mockEnabled } from './mock'; + +/** The Tauri event the host emits when a plugin asks Core to show a notification. */ +export const PLUGIN_NOTICE_EVENT = 'plugin:notification'; + +export type PluginNoticeSeverity = 'info' | 'success' | 'warning' | 'error'; + +/** One version of a notification's text, in `locale` (empty when the plugin gave none). */ +export interface PluginNoticeText { + locale: string; + title: string; + body: string; +} + +/** + * A notification a plugin published. Everything in it is untrusted text: `pluginId` is the + * authenticated plugin id (set by the host, not the plugin), and `texts` holds the plugin's main + * text first, then its translations. + */ +export interface PluginNotice { + pluginId: string; + severity: PluginNoticeSeverity; + texts: PluginNoticeText[]; +} + +/** The longest title and body shown, matching the host's bounds. */ +export const NOTICE_TITLE_MAX = 120; +export const NOTICE_BODY_MAX = 512; + +// Characters that can make text pretend to be something else: C0/C1 controls (line breaks are +// handled separately), bidirectional overrides, invisible separators and tag characters. The host +// refuses them; they are removed again here so a notification never depends on that check. +// eslint-disable-next-line no-control-regex +const CONTROLS = /[\u0000-\u0009\u000B-\u001F\u007F-\u009F]/g; +const DISGUISES = + /[\u061C\u200B\u200E\u200F\u2028\u2029\u202A-\u202E\u2060\u2066-\u2069\uFEFF\uFFF9-\uFFFB]|[\u{E0000}-\u{E007F}]/gu; + +/** + * Makes untrusted text safe to show as plain text: no controls or disguising characters, at most + * `max` characters, and (unless `multiline`) a single line. Markup is not touched: it is rendered + * as text by React and never interpreted. + */ +export function plainText(raw: unknown, max: number, multiline = false): string { + if (typeof raw !== 'string') return ''; + // Line endings are settled first, so a lone carriage return stays a break and is not deleted. + let text = raw.replace(DISGUISES, '').replace(/\r\n?/g, '\n').replace(CONTROLS, ''); + if (!multiline) text = text.replace(/\n+/g, ' '); + text = text.trim(); + return Array.from(text).slice(0, max).join(''); +} + +function language(locale: string): string { + return locale.trim().toLowerCase().replace('_', '-').split('-')[0] ?? ''; +} + +/** + * The text to show for the user's `locale`: an exact match, then the same language (the + * region-less tag first), then the plugin's main text. Case does not matter. The result is already + * made plain. + */ +export function pickText(notice: PluginNotice, locale: string): PluginNoticeText { + const texts = notice.texts.filter((text) => typeof text?.title === 'string'); + const main = texts[0] ?? { locale: '', title: '', body: '' }; + const wanted = locale.trim().toLowerCase().replace('_', '-'); + const same = (text: PluginNoticeText) => text.locale.trim().toLowerCase().replace('_', '-'); + const chosen = + texts.find((text) => text.locale !== '' && same(text) === wanted) ?? + texts.find((text) => text.locale !== '' && same(text) === language(locale)) ?? + texts.find((text) => text.locale !== '' && language(text.locale) === language(locale)) ?? + main; + return { + locale: chosen.locale, + title: plainText(chosen.title, NOTICE_TITLE_MAX), + body: plainText(chosen.body, NOTICE_BODY_MAX, true), + }; +} + +/** The label a notification is attributed with: the plugin id, made plain. */ +export function noticeSource(notice: PluginNotice): string { + return plainText(notice.pluginId, 128); +} + +/** Subscribes to plugin notifications; the mock host feeds the same handler. */ +export async function subscribeToPluginNotices( + handler: (notice: PluginNotice) => void, +): Promise { + if (mockEnabled) { + return (await getMockHost()).subscribePluginNotices(handler); + } + return listen(PLUGIN_NOTICE_EVENT, (event) => handler(event.payload)); +} diff --git a/ui/src/api/pluginQueryKeys.ts b/ui/src/api/pluginQueryKeys.ts new file mode 100644 index 000000000..6753e93dd --- /dev/null +++ b/ui/src/api/pluginQueryKeys.ts @@ -0,0 +1,14 @@ +/** Shared React Query keys for host-owned plugin settings state. */ +export const pluginQueryKeys = { + inventory: ['plugin-inventory'] as const, + updatePreferences: ['plugin-update-preferences'] as const, + availableUpdates: ['plugin-update-available'] as const, + permissions: (pluginId: string, profileId: string, publisherFingerprint?: string) => + ['plugin-permissions', profileId, pluginId, ...(publisherFingerprint ? [publisherFingerprint] : [])] as const, + sharedData: (pluginId: string, profileId: string, publisherFingerprint?: string) => + ['plugin-shared-data-policies', profileId, pluginId, ...(publisherFingerprint ? [publisherFingerprint] : [])] as const, + durableUsage: (pluginId: string, profileId: string) => + ['plugin-durable-usage', profileId, pluginId] as const, + storageLocations: ['plugin-storage-locations'] as const, + configuration: (pluginId: string) => ['plugin-configuration', pluginId] as const, +}; diff --git a/ui/src/api/pluginRuntimeApprovals.ts b/ui/src/api/pluginRuntimeApprovals.ts new file mode 100644 index 000000000..0354ad929 --- /dev/null +++ b/ui/src/api/pluginRuntimeApprovals.ts @@ -0,0 +1,97 @@ +import { listen, type UnlistenFn } from '@tauri-apps/api/event'; +import { getMockHost, mockEnabled } from './mock'; +import { plainText } from './pluginNotices'; + +export const PLUGIN_RUNTIME_SELECT_EVENT = 'plugin:runtime-approval-select'; +export const PLUGIN_RUNTIME_CLOSED_EVENT = 'plugin:runtime-approval-closed'; + +export interface RuntimeExecutableCandidate { + displayName: string; + packageManager: string; + packageId: string; + version: string; + /** The exact program path the user would approve; shown, never sent back to the plugin. */ + path: string; +} + +export interface RuntimeSelectionPrompt { + id: string; + pluginId: string; + publisherFingerprint: string; + runtimeName: string; + runtimeVersion: string; + platform: string; + supportedFormats: string[]; + hints: string[]; + candidates: RuntimeExecutableCandidate[]; +} + +/** One active runtime executable approval, as the plugin settings list shows it. */ +export interface PluginRuntimeApproval { + /** The owned runtime this approval belongs to. */ + runtimeId: string; + /** The canonical executable path the user approved. */ + path: string; + /** Unix seconds. */ + approvedAt: number; +} + +export function cleanRuntimeSelection(raw: unknown): RuntimeSelectionPrompt | null { + if (!raw || typeof raw !== 'object') return null; + const row = raw as Record; + if (typeof row.id !== 'string' || row.id.length < 16 || row.id.length > 128) return null; + const pluginId = plainText(row.pluginId, 256); + if (!pluginId) return null; + const publisherFingerprint = typeof row.publisherFingerprint === 'string' + && /^[0-9a-f]{64}$/.test(row.publisherFingerprint) + ? row.publisherFingerprint + : ''; + const candidates = Array.isArray(row.candidates) + ? row.candidates.slice(0, 32).flatMap((entry) => { + if (!entry || typeof entry !== 'object') return []; + const candidate = entry as Record; + const path = plainText(candidate.path, 4096); + if (!path) return []; + return [{ + displayName: plainText(candidate.displayName, 256), + packageManager: plainText(candidate.packageManager, 128), + packageId: plainText(candidate.packageId, 256), + version: plainText(candidate.version, 128), + path, + }]; + }) + : []; + return { + id: row.id, + pluginId, + publisherFingerprint, + runtimeName: plainText(row.runtimeName, 256), + runtimeVersion: plainText(row.runtimeVersion, 128), + platform: plainText(row.platform, 64), + supportedFormats: Array.isArray(row.supportedFormats) + ? row.supportedFormats + .filter((value): value is string => typeof value === 'string') + .map((value) => plainText(value, 128)) + .filter(Boolean) + .slice(0, 32) + : [], + hints: Array.isArray(row.hints) + ? row.hints + .filter((value): value is string => typeof value === 'string') + .map((value) => plainText(value, 256)) + .filter(Boolean) + .slice(0, 32) + : [], + candidates, + }; +} + +export async function subscribeToRuntimeSelections(handler: (prompt: unknown) => void): Promise { + if (mockEnabled) return (await getMockHost()).subscribeRuntimeSelections(handler); + return listen(PLUGIN_RUNTIME_SELECT_EVENT, (event) => handler(event.payload)); +} + +export async function subscribeToRuntimePromptsClosed(handler: (id: string) => void): Promise { + if (mockEnabled) return (await getMockHost()).subscribeRuntimePromptsClosed(handler); + return listen(PLUGIN_RUNTIME_CLOSED_EVENT, (event) => handler(event.payload)); +} diff --git a/ui/src/api/pluginSettings.ts b/ui/src/api/pluginSettings.ts new file mode 100644 index 000000000..9881d8cb1 --- /dev/null +++ b/ui/src/api/pluginSettings.ts @@ -0,0 +1,76 @@ +export interface PluginConfigurationModes { + externalDeclared: boolean; + externalAuthorized: boolean; + declarativeDeclared: boolean; + declarativeAuthorized: boolean; +} + +export interface PluginConfigurationStatus { + status: 'open' | 'focused' | 'unavailable' | 'denied' | 'timedOut' | 'failed'; + windowId: string | null; + message: string | null; +} + +export type PluginSettingsValue = + | { type: 'boolean'; value: boolean } + | { type: 'text'; value: string } + | { type: 'number'; value: number } + | { type: 'choice'; value: string }; + +export interface PluginSettingsContext { + plugin_id: string; + provider_id: string; + session_id: string; + profile_epoch: number; + form_handle: string; +} + +export interface PluginSettingsText { + fallback: string; + translations: Record; +} + +export type PluginSettingsKind = + | { type: 'boolean' } + | { type: 'text'; min_length: number; max_length: number } + | { type: 'number'; min: number; max: number; step: number } + | { type: 'choice'; options: Array<{ id: string; label: PluginSettingsText }> }; + +export interface PluginSettingsField { + id: string; + label: PluginSettingsText; + help?: PluginSettingsText | null; + kind: PluginSettingsKind; + default: PluginSettingsValue; +} + +export interface PluginSettingsForm { + schema_version: number; + form_id: string; + schema_revision: string; + configuration_revision: string; + title: PluginSettingsText; + fields: PluginSettingsField[]; +} + +export type PluginSettingsOutcome = + | { type: 'form'; form: PluginSettingsForm; values: Record } + | { type: 'applied'; configuration_revision: string; persistence: 'persisted' | 'session_only' } + | { type: 'field_errors'; errors: Record } + | { type: 'revision_conflict'; configuration_revision: string } + | { type: 'failed'; failure: string }; + +export interface PluginSettingsReply { + context: PluginSettingsContext; + outcome: PluginSettingsOutcome; +} + +export type ConfigurationChoice = 'external' | 'form' | 'denied' | 'absent'; + +/** A declared capability is never treated as permission; only an authorized surface is selectable. */ +export function selectPluginConfiguration(modes: PluginConfigurationModes): ConfigurationChoice { + if (modes.externalDeclared && modes.externalAuthorized) return 'external'; + if (modes.declarativeDeclared && modes.declarativeAuthorized) return 'form'; + if (modes.externalDeclared || modes.declarativeDeclared) return 'denied'; + return 'absent'; +} diff --git a/ui/src/api/ports.ts b/ui/src/api/ports.ts index 43c7de982..b1126e8cf 100644 --- a/ui/src/api/ports.ts +++ b/ui/src/api/ports.ts @@ -341,7 +341,10 @@ export interface PortPreferencesPatch { * `entries` and `provenance` are already merged with the GameNode overlay and filtered to * Windows entries; the UI does not see hidden or Linux-only entries. */ +export interface PortPluginSource { path: string; directory: boolean; } +export interface PortPluginRequest { id: string; catalogId: string; pluginId: string; publisherFingerprint: string; sources: PortPluginSource[]; } export interface PortsView { + pluginRequest?: PortPluginRequest | null; catalog: PortCatalogStatus; entries: PortEntryView[]; /** Provenance by registration key (`drmfree:`). */ @@ -473,6 +476,7 @@ export interface PortSuppliedChoice { /** `ports_install` request. */ export interface PortInstallRequest { + pluginRequestId?: string; catalogId: string; /** Parent folder chosen by the user; the host creates a subfolder inside it. */ parentFolder: string; diff --git a/ui/src/api/sharedResources.ts b/ui/src/api/sharedResources.ts new file mode 100644 index 000000000..12ceda9b7 --- /dev/null +++ b/ui/src/api/sharedResources.ts @@ -0,0 +1,27 @@ +/** One host-resolved game/installation in a shared emulator resource's affected scope. */ +export interface PluginSharedResourceGame { + installationId: string; + gameId: string; + name: string; +} + +/** + * A declared shared emulator save resource awaiting or holding user consent. The host resolves + * the affected games and backing location; a plugin cannot supply either as authority. + */ +export interface PluginSharedResourceReview { + pluginId: string; + publisherFingerprint: string; + profileId: string; + profileName: string; + gameId: string; + installationId: string; + runtimeId: string; + resourceId: string; + displayName: string; + affectedGames: PluginSharedResourceGame[]; + /** `pending`, `current` or `stale`. */ + consent: 'pending' | 'current' | 'stale'; + /** True when the approval or affected set can no longer be resolved. */ + unavailable: boolean; +} diff --git a/ui/src/api/types.ts b/ui/src/api/types.ts index cee61c23d..2c7b879d9 100644 --- a/ui/src/api/types.ts +++ b/ui/src/api/types.ts @@ -344,10 +344,50 @@ export interface DetailView { membership: Membership; achievementBackend: boolean; achievements: AchievementSummary | null; + detectedTarget?: DetectedTargetView | null; /** Best-first suggestions for an unmatched or ambiguous entry. */ suggestions: SuggestionView[]; } +export type DetectedTargetSpec = + | { uri: string } + | { executable: { root: string; path: string; arguments: string[]; workingDirectory: string } }; + +export interface DetectedTargetView { + spec: DetectedTargetSpec; + revision: number; + approved: boolean; + available: boolean; + +} + +export interface LaunchRecipeOption { + pluginId: string; + publisherFingerprint: string; + recipeId: string; + recipeRevision: number; + /** Runtime/version and launch arguments; empty when the host cannot summarize it. */ + summary?: string; +} + +export interface LaunchRecipeSelection { + entryKey: string; + ownerKey: string; + pluginId: string; + publisherFingerprint: string; + recipeId: string; + recipeRevision: number; + baseTargetRevision: number; + approvedPlanFingerprint: string; +} + +export interface LaunchRecipeChoices { + targetRevision: number; + detectedDefaultAvailable: boolean; + selected: LaunchRecipeSelection | null; + recipes: LaunchRecipeOption[]; +} + export type EmptyState = | { noGames: { stores: string[] } } | { noInstalled: { provider: string | null } } @@ -813,6 +853,8 @@ export type Reason = | 'noMatchedGames' | 'checkingMembership' | 'membershipUnavailable' + | 'targetNeedsApproval' + | 'targetUnavailable' | { alreadyInLibrary: EntryStatus | null }; export type Availability = 'available' | { disabled: Reason }; @@ -851,6 +893,18 @@ export type SearchFailure = | 'rejected' | 'failed'; +/** The platform narrowing the match dialog derives from the entry's record. */ +export interface MatchPlatformFilter { + /** The entry's declared platform, normalized to lowercase (for example `gamecube`). */ + platform: string; + /** The platform's display name (for example `GameCube`). */ + label: string; + /** The catalog abbreviations an option may report for this platform. */ + aliases: string[]; + /** Whether options outside the platform are hidden. On by default when the platform is known. */ + enabled: boolean; +} + export interface MatchDialogView { entryKey: string; detectedName: string; @@ -861,6 +915,10 @@ export interface MatchDialogView { results: MatchOption[]; selected: MatchOption | null; noResults: boolean; + /** The platform narrowing derived from the entry, when it declares one. */ + platformFilter: MatchPlatformFilter | null; + /** How many options the active platform filter hides. */ + filteredOut: number; error?: SearchFailure | null; searchBlocked?: Reason | null; current: MatchStatus; @@ -1081,7 +1139,12 @@ export interface LibraryView { export type LaunchKind = 'play' | 'install'; -export type LaunchError = 'noHandler' | 'unsupported' | 'incomplete' | 'failed'; +export type LaunchError = + | 'noHandler' + | 'unsupported' + | 'incomplete' + | 'recipeNeedsAttention' + | 'failed'; export type LaunchState = 'opening' | { failed: LaunchError }; @@ -1393,6 +1456,7 @@ export type ToolOperationStatus = | { failed: { message: string; code?: ToolOperationErrorCode | null } }; export interface ToolModalView { + pluginRequest?: { pluginId: string; publisherFingerprint: string; remove: boolean } | null; entryKey: string; title: string; installDir: string; @@ -1486,17 +1550,590 @@ export interface StoreAccountView { canRemoveCredential: boolean; } +export interface PluginUpdatePreferences { + periodicChecks: boolean; +} + +export type PlaytimeAccountingMode = 'disabled' | 'application_open'; + +export interface PlaytimeCapabilities { + identifiesGameplay: boolean; + identifiesPauses: boolean; + withoutPauseDetection: PlaytimeAccountingMode; +} + +export interface PluginPlaytimeInfo { + pluginId: string; + name: string; + version: string; + playtime: PlaytimeCapabilities; + accountingEnabled: boolean; +} + +export interface AvailablePluginUpdate { + pluginId: string; + name: string; + installedVersion: string; + versions: string[]; +} + +export interface AvailablePluginRollback { + pluginId: string; + name: string; + activeVersion: string; + versions: string[]; +} + +export type PluginCompatibilityState = 'compatible' | 'incompatible' | 'indeterminate'; + +export type PluginCompatibilityReason = + | 'operatingSystemMismatch' | 'architectureMismatch' | 'abiMismatch' + | 'unknownOperatingSystem' | 'unknownArchitecture' | 'unknownAbi' + | 'emulationRejected' | 'emulationUnknown' + | 'windowsProductMismatch' | 'windowsVersionTooOld' | 'windowsVersionTooNew' + | 'windowsBuildTooOld' | 'windowsBuildTooNew' + | 'windowsProductUnknown' | 'windowsVersionUnknown' | 'windowsBuildUnknown' + | 'linuxLibcMismatch' | 'linuxLibcVersionTooOld' | 'linuxLibcUnknown' + | 'linuxDistributionMismatch' | 'linuxDistributionVersionMismatch' | 'linuxDistributionUnknown' + | 'noAdditionalRequirements' | 'requirementsMalformed' | 'requirementsSatisfied'; + +/** One signed target. The nested manifest declarations keep their manifest (snake_case) names. */ +export interface PluginTargetDeclaration { + os: string; + arch: string; + abi: string; + entrypoint: string; + requires?: { + windows?: { + product?: 'client' | 'server' | null; + min_version?: string | null; + max_version?: string | null; + min_build?: number | null; + max_build?: number | null; + } | null; + linux?: { + libc?: { family: 'glibc' | 'musl'; min_version: string } | null; + distributions?: Array<{ id: string; versions: string[] }> | null; + } | null; + } | null; + /** Author-tested environments: informational only, never part of the verdict. */ + tested_on: Array<{ + product?: string | null; + release?: string | null; + distribution?: string | null; + version?: string | null; + }>; +} + +export interface PluginTargetAssessment { + target: PluginTargetDeclaration; + verdict: { + state: PluginCompatibilityState; + reasons: PluginCompatibilityReason[]; + unknownFacts: string[]; + }; +} + +/** Effective execution facts and the per-target verdicts the host derived for a signed package. */ +export interface PluginCompatibilityDetails { + state: PluginCompatibilityState; + ambiguous: boolean; + os?: string | null; + release?: string | null; + product?: 'client' | 'server' | 'unknown' | null; + build?: number | null; + architecture?: string | null; + abi?: string | null; + libc?: { family: 'gnu' | 'musl'; version?: string | null } | { family: 'unknown' } | null; + emulation: 'native' | 'emulated' | 'unknown'; + targets: PluginTargetAssessment[]; +} + +export interface ExtensionReadinessSelection { + installationId: string; + revision: string; + profileEpoch: string; +} + +export interface PluginUpdateReview { + pluginId: string; + installedVersion: string; + candidateVersion: string; + addedPermissions: string[]; + removedPermissions: string[]; + changedPermissions: string[]; + permissionChanges: Array<{ + id: string; + installedScope: string; + candidateScope: string; + installedRequired: boolean; + candidateRequired: boolean; + }>; + addedNativeAccess: string[]; + removedNativeAccess: string[]; + apiChanged: boolean; + installedApi: string; + candidateApi: string; + licenseChanged: boolean; + installedLicense: string; + candidateLicense: string; + installedLicenseFiles: string[]; + candidateLicenseFiles: string[]; + installedLicenseNotices: string[]; + candidateLicenseNotices: string[]; + installedPlaytime: PlaytimeCapabilities; + candidatePlaytime: PlaytimeCapabilities; + playtimeChanged: boolean; + publisherChanged: boolean; + installedPublisherKeyId: string; + candidatePublisherKeyId: string; + publisherFingerprint: string; + changedDataSchemas: string[]; + preservesPriorData: boolean; + isDowngrade: boolean; + requiresManualApproval: boolean; + compatibilityDetails?: PluginCompatibilityDetails; + extensionTargets?: Array<{ + name: string; + providerId: string; + selection: ExtensionReadinessSelection; + }>; +} + +export interface PluginBundleComponent { + pluginId: string; + pluginKind: 'provider' | 'extension'; + name: string; + version: string; + status: 'installed' | 'missing' | 'unavailable' | 'failed' | 'incompatible'; + session: 'active' | 'stopped'; + enabled?: boolean; + runtimeAvailable?: boolean; + publisherFingerprint?: string; + compatibilityDetails?: PluginCompatibilityDetails; + nativeAccess: string[]; +} + export interface PluginInfo { providerId: string; pluginId: string; + pluginKind: 'provider' | 'extension' | 'bundle'; name: string; - /** Version from the trusted descriptor, or the build package version. */ - version: string; source: 'official' | 'community'; status: 'installed' | 'missing' | 'unavailable' | 'failed' | 'incompatible'; capabilities: string[]; session: 'active' | 'stopped'; nativeAccess: string[]; + /** Version from the trusted descriptor or verified package manifest. */ + version?: string; + enabled?: boolean; + runtimeAvailable?: boolean; + /** The pinned publisher of a third-party plugin; absent for the bundled ones. */ + publisherFingerprint?: string; + compatibilityDetails?: PluginCompatibilityDetails; + /** The installed bundle this entry represents; absent for standalone packages. */ + bundleId?: string; + bundleName?: string; + bundleVersion?: string; + bundleComponentKind?: 'provider' | 'extension'; + bundlePublisherFingerprint?: string; + /** Every component of an aggregated bundle entry, each with its own status. */ + bundleComponents?: PluginBundleComponent[]; +} + +/** One permission requested by a verified package manifest. */ +export interface PluginImportPermissionReview { + id: string; + required: boolean; + scope: string; + reason: string; + /** + * What stops working when the user denies this optional permission. Required permissions + * cannot be denied, so they never carry an impact. + */ + impactIfDisabled?: string; +} + +export interface PluginImportReview { + token: string; + pluginId: string; + providerId?: string; + name: string; + version: string; + publisherKeyId: string; + publisherFingerprint: string; + pinnedFingerprint?: string; + trust: 'trusted' | 'untrusted' | 'changed'; + license: string; + licenseFiles: string[]; + licenseNotices: string[]; + permissionIds: string[]; + requestedPermissions: PluginImportPermissionReview[]; + /** Emulator or runtime platforms declared by the signed bundle manifest. */ + supportedPlatforms?: string[]; + nativeAccess: string[]; + playtime: PlaytimeCapabilities; + compatibility: 'compatible' | 'incompatible' | 'unknown'; + compatibilityReason?: string; + compatibilityDetails?: PluginCompatibilityDetails; +} + +/** The identity shown once for a whole bundle review. */ +export interface PluginBundleIdentity { + id: string; + name: string; + version: string; + publisherKeyId: string; + publisherFingerprint: string; +} + +export type PluginBundleComponentAvailability = + | { status: 'available' } + | { status: 'unavailable'; reason: 'noCompatibleTarget' | 'ambiguousTarget' }; + +/** One component inside a bundle review; the embedded review is the package review. */ +export interface PluginBundleComponentReview { + kind: 'provider' | 'extension'; + availability: PluginBundleComponentAvailability; + review: Omit; +} + +export interface PluginBundleLicenseComponent { + pluginId: string; + expression: string; + files: string[]; + notices: string[]; +} + +/** The bundle-wide license view shown in the single review header. */ +export interface PluginBundleLicenseSummary { + expressions: string[]; + components: PluginBundleLicenseComponent[]; +} + +export interface PluginBundleImportReview { + token: string; + bundle: PluginBundleIdentity; + trust: 'trusted' | 'untrusted' | 'changed'; + pinnedFingerprint?: string; + license: PluginBundleLicenseSummary; + components: PluginBundleComponentReview[]; +} + +/** One component's permission decisions submitted from a grouped bundle review. */ +export interface BundleComponentPermissionSubmission { + pluginId: string; + expectedProfileId: string; + expectedPublisherFingerprint: string; + expectedRevision: number; + decisions: PluginPermissionDecision[]; +} + +export interface BundleComponentPermissionOutcome { + pluginId: string; + snapshot?: PluginPermissionSnapshot; + error?: string; +} + +export interface BundlePermissionResult { + components: BundleComponentPermissionOutcome[]; +} + +/** The result of one bundle uninstall; partial failures are named, not collapsed. */ +export interface BundleUninstallOutcome { + bundleId: string; + removed: Array<{ pluginId: string; version: string; stopped: boolean }>; + failures: Array<{ pluginId: string; version: string; error: string }>; + dataRetention: 'kept' | 'deleted'; +} + +export interface BundleImportInstallOutcome { + bundleId: string; + components: Array<{ + pluginId: string; + kind: 'provider' | 'extension'; + version: string; + active: boolean; + /** True when the host enabled this component for the active profile right after install. */ + activated: boolean; + /** Present when the component stayed installed but could not be activated. */ + activationError?: string; + /** Present when the reviewed permission decisions could not be saved. */ + permissionError?: string; + }>; +} + +export interface PluginImportInstallOutcome { + pluginId: string; + activated: boolean; + /** Present when the package stayed installed but could not be activated. */ + activationError?: string; +} + +export interface AvailableBundleUpdate { + bundleId: string; + name: string; + installedVersion: string; + versions: string[]; +} + +export interface AvailableBundleRollback { + bundleId: string; + name: string; + activeVersion: string; + versions: string[]; +} + +/** One component's old/new facts in a bundle update or rollback review. */ +export interface BundleComponentUpdateReview { + pluginId: string; + kind: 'provider' | 'extension'; + installedVersion: string; + candidateVersion: string; + addedPermissions: string[]; + removedPermissions: string[]; + changedPermissions: string[]; + permissionChanges: Array<{ + id: string; + installedScope: string; + candidateScope: string; + installedRequired: boolean; + candidateRequired: boolean; + }>; + addedNativeAccess: string[]; + removedNativeAccess: string[]; + apiChanged: boolean; + installedApi: string; + candidateApi: string; + availability: PluginBundleComponentAvailability; + compatibility: 'compatible' | 'incompatible' | 'unknown'; + compatibilityReason?: string; + compatibilityDetails?: PluginCompatibilityDetails; + publisherChanged: boolean; + isDowngrade: boolean; +} + +/** The grouped review of one bundle release or rollback target. */ +export interface BundleUpdateReview { + bundleId: string; + name: string; + installedVersion: string; + candidateVersion: string; + bundleSha256: string; + publisherFingerprint: string; + components: BundleComponentUpdateReview[]; + addedPermissions: string[]; + removedPermissions: string[]; + changedPermissions: string[]; + requiresManualApproval: boolean; + isDowngrade: boolean; + isRollback: boolean; +} + +export interface BundleUpdateOutcome { + bundleId: string; + previousVersion: string; + version: string; + components: Array<{ + pluginId: string; + kind: 'provider' | 'extension'; + previousVersion: string; + version: string; + active: boolean; + }>; +} + +export type BundleRollbackOutcome = BundleUpdateOutcome; + +/** Host-owned effective permission state for the currently active account profile. */ +export interface PluginPermissionSnapshot { + pluginId: string; + publisherFingerprint: string; + profileId: string; + grantRevision: number; + requestedPermissions: Array<{ + permission_id: string; + required: boolean; + allowed_scopes: PluginGrantScope[]; + }>; + /** Rust grant records retain their serialized snake_case protocol fields. */ + effectiveGrants: Array<{ + permission_id: string; + required: boolean; + scope: Record; + state: 'granted' | 'denied' | 'unsupported'; + }>; +} + +export type PluginGrantScope = + | { scope: 'own-creator'; category: 'runtime' | 'library-root' | 'save-profile' } + | { scope: 'public-category'; category: 'runtime' | 'library-root' | 'save-profile' } + | { scope: 'selected-records'; category: 'runtime' | 'library-root' | 'save-profile'; record_ids: string[] } + | { scope: 'declared'; value: string } + | { scope: 'own-private-namespace' }; + +export interface PluginPermissionDecision { + permission_id: string; + scope: PluginGrantScope; + granted: boolean; +} + +export type SharedDataCategory = + | 'gamePaths' + | 'gamePerformanceHistory' + | 'runtimeCatalog' + | 'contentAvailability' + | 'libraryRoots' + | 'saveProfiles'; + +export interface SharedDataCatalogRecord { + sourcePluginId: string; + sourcePublisherFingerprint: string; + datasetId: string; + class: 'common' | 'sensitive' | 'custom'; + category: SharedDataCategory | null; + recordId: string; + fields: string[]; +} + +export interface SharedDataSourcePolicy { + sourcePluginId: string; + sourcePublisherFingerprint: string; + datasetId: string; + class: 'sensitive' | 'custom'; + fields: string[]; + history: boolean; + live: boolean; +} + +export interface PluginSharedDataSnapshot { + pluginId: string; + publisherFingerprint: string; + profileId: string; + policyRevision: number; + commonCategories: SharedDataCategory[]; + selectedRecordIds: string[]; + /** Host metadata only; records contain no payload values. */ + catalog: SharedDataCatalogRecord[]; + sourcePolicies: SharedDataSourcePolicy[]; +} + +export interface SharedDataSourcePolicyDecision extends SharedDataSourcePolicy {} + +export interface PluginSharedDataPolicyUpdate { + profileId: string; + expectedPublisherFingerprint: string; + expectedRevision: number; + commonCategories: SharedDataCategory[]; + selectedRecordIds: string[]; + sourcePolicies: SharedDataSourcePolicyDecision[]; +} + +/** Logical durable-pool usage of one producer. The host discloses no physical path. */ +export interface PluginDurableUsage { + pluginId: string; + profileId: string; + recordCount: number; + logicalBytes: number; + maxBytes: number; + maxAgeSeconds: number | null; + oldestUpdatedAt: number | null; +} + +/** The outcome of deleting one producer's retained durable records. */ +export interface PluginDurableDeletion { + pluginId: string; + profileId: string; + removedRecords: number; + reclaimedBytes: number; + usage: PluginDurableUsage; +} + +/** + * One host-managed physical file holding plugin data. Host administration only: these paths are + * never part of a plugin reply. + */ +export interface PluginStorageLocation { + pluginId: string; + kind: 'durable_shared' | 'private_persistence'; + path: string; + scope: 'namespace' | 'pool'; + fileBytes: number; + logicalBytes: number; + records: number; + protectedRecords: number; + archivedRecords: number; + oldestUsedAt: number | null; + maxBytes: number | null; + maxAgeSeconds: number | null; +} + +/** The durable pool file, counted once because every producer shares it. */ +export interface PluginStoragePool { + path: string; + fileBytes: number; + logicalBytes: number; + overheadBytes: number; + owners: number; + maxOwnerBytes: number; +} + +/** Host-only physical accounting of the active profile's plugin data. */ +export interface PluginStorageAccounting { + profileId: string; + locations: PluginStorageLocation[]; + pool: PluginStoragePool | null; + privateRootBytes: number; +} + +/** One owner's non-empty dataset or private store, as presented for review, without a path. */ +export interface StorageCleanupCandidate { + candidateId: string; + kind: 'durable_shared' | 'private_persistence'; + pluginId: string; + profileId: string; + records: number; + protectedRecords: number; + archivedRecords: number; + logicalBytes: number; + physicalBytesEstimate: number; + oldestUpdatedAt: number | null; + maxBytes: number | null; + maxAgeSeconds: number | null; +} + +/** A single-use cleanup review the user must confirm. */ +export interface StorageCleanupReview { + token: string; + generatedAt: number; + candidates: StorageCleanupCandidate[]; +} + +/** One selected candidate's measured result; a partial failure is named, not collapsed. */ +export interface StorageCleanupResult { + candidateId: string; + kind: 'durable_shared' | 'private_persistence'; + pluginId: string; + status: 'completed' | 'failed'; + removedRecords: number; + reclaimedBytes: number; + error?: string | null; +} + +/** The measured result of one confirmed cleanup; the token cannot be reused. */ +export interface StorageCleanupReport { + token: string; + removedRecords: number; + reclaimedBytes: number; + skippedProtectedRecords: number; + results: StorageCleanupResult[]; +} + +/** Host-owned configuration availability; no plugin preference values are included. */ +export interface PluginConfigurationState { + pluginId: string; + available: boolean; + revision: string | null; } export interface Snapshot { @@ -1565,6 +2202,7 @@ export type LibraryInput = | 'openMatch' | 'closeMatch' | { setMatchQuery: string } + | { setMatchPlatformFilter: { enabled: boolean } } | 'searchMatch' | { pickMatch: { gameId: number; now: number } } | { selectMatch: { gameId: number } } diff --git a/ui/src/components/ui/OptionCard.test.tsx b/ui/src/components/ui/OptionCard.test.tsx index 54366bb92..4785275e2 100644 --- a/ui/src/components/ui/OptionCard.test.tsx +++ b/ui/src/components/ui/OptionCard.test.tsx @@ -2,7 +2,7 @@ import { useState } from 'react'; import { describe, expect, it, vi } from 'vitest'; import { screen, waitFor } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; -import { IconBookmark, IconDeviceGamepad2, IconTrophy } from '@tabler/icons-react'; +import { IconBookmark, IconDeviceGamepad2, IconInfinity, IconTrophy } from '@tabler/icons-react'; import { OptionCard, OptionCardGroup } from './OptionCard'; import { Pill } from './Pill'; import { renderUi } from './testUtils'; @@ -71,6 +71,16 @@ describe('OptionCard', () => { ); }); + it('lets a long status label wrap instead of clipping it', () => { + renderUi( + , + ); + + const label = screen.getByText('Em andamento'); + expect(label).toHaveClass('whitespace-normal', 'leading-note'); + expect(label).not.toHaveClass('truncate'); + }); + it('renders a match row as a listbox option with cover, meta and pill', () => { renderUi( ( > { useBatchMatchDriver(library, accountId); const dialog = library?.matchDialog; + const open = dialog != null; useEffect(() => { - if (!dialog) return; - - // Focus query input when dialog opens - inputRef.current?.focus(); - }, [dialog]); + // Focus the query field once when the dialog opens. A new snapshot (for example after + // selecting an option) must not pull focus back out of the option list. + if (open) inputRef.current?.focus(); + }, [open]); if (!dialog) return null; @@ -77,6 +78,10 @@ export const MatchDialog: React.FC = () => { commands.libraryInput('searchMatch'); }; + const handlePlatformFilter = (enabled: boolean) => { + commands.libraryInput({ setMatchPlatformFilter: { enabled } }); + }; + const handleSelect = (gameId: number) => { commands.libraryInput({ selectMatch: { gameId } }); }; @@ -275,7 +280,7 @@ export const MatchDialog: React.FC = () => { >

-
+ { } /> + {dialog.platformFilter && ( +
+ + handlePlatformFilter(event.currentTarget.checked) + } + /> + {dialog.platformFilter.enabled && ( + + )} +
+ )}
{dialog.searching && ( @@ -299,6 +333,32 @@ export const MatchDialog: React.FC = () => {
)} + {dialog.filteredOut > 0 && + optionCount === 0 && + !dialog.searching && + !dialog.error && ( +
+ + {formatI18n( + t('Library::No {} results'), + dialog.platformFilter?.label ?? '', + )} + + + +
+ )} + {dialog.noResults && (
{ui} , ); + + return { ...result, queryClient }; } describe('Dialogs Feature Tests', () => { @@ -134,6 +136,8 @@ describe('Dialogs Feature Tests', () => { ], }, noResults: false, + platformFilter: null, + filteredOut: 0, canClear: true, current: { matched: { gameId: 102, source: 'automatic' } }, ...overrides, @@ -286,6 +290,40 @@ describe('Dialogs Feature Tests', () => { }); }); + it('keeps focus on the option list when a new snapshot arrives', async () => { + const { queryClient } = renderWithProviders( + , + makeMatchSnapshot(), + 'en', + ); + + // Let the dialog's opening focus settle before the option list takes focus. + await waitFor(() => { + expect(screen.getByTestId('match-search-input')).toHaveFocus(); + }); + const candidate = screen.getByTestId('candidate-101'); + candidate.focus(); + expect(document.activeElement).toBe(candidate); + + // Selecting an option arrives as a fresh dialog view. That update must not + // pull focus back to the search field, or the next arrow key would be lost. + const next = makeMatchSnapshot(); + next.library!.matchDialog!.selected = + next.library!.matchDialog!.candidates[0]; + act(() => { + queryClient.setQueryData(SNAPSHOT_QUERY_KEY, next); + }); + + await waitFor(() => { + expect(screen.getByTestId('match-preview')).toHaveTextContent( + 'Hades II', + ); + }); + + expect(document.activeElement).toBe(candidate); + expect(screen.getByTestId('match-search-input')).not.toHaveFocus(); + }); + it('renders covers from the asset protocol and never from a remote result URL', () => { const snapshot = makeMatchSnapshot(); const dialog = snapshot.library!.matchDialog!; @@ -372,6 +410,126 @@ describe('Dialogs Feature Tests', () => { ); }); + const gamecubeFilter = { + platform: 'gamecube', + label: 'GameCube', + aliases: ['NGC', 'GC', 'GCN', 'GameCube'], + enabled: true, + }; + + it('shows the derived platform filter, on by default, and sends the toggle', () => { + const libraryInputSpy = vi.spyOn(commands, 'libraryInput'); + const { unmount } = renderWithProviders( + , + makeMatchSnapshot({ platformFilter: gamecubeFilter, filteredOut: 1 }), + 'en', + ); + + expect(screen.getByTestId('match-platform-filter')).toHaveTextContent( + 'Platform: GameCube', + ); + const platformSwitch = screen.getByRole('switch', { + name: 'Platform: GameCube', + }); + expect(platformSwitch).toBeChecked(); + + fireEvent.click(platformSwitch); + expect(libraryInputSpy).toHaveBeenCalledWith({ + setMatchPlatformFilter: { enabled: false }, + }); + + fireEvent.click(screen.getByTestId('match-show-all-btn')); + expect(libraryInputSpy).toHaveBeenCalledWith({ + setMatchPlatformFilter: { enabled: false }, + }); + + unmount(); + + renderWithProviders( + , + makeMatchSnapshot({ platformFilter: gamecubeFilter }), + 'pt-BR', + ); + expect(screen.getByTestId('match-platform-filter')).toHaveTextContent( + 'Plataforma: GameCube', + ); + expect(screen.getByTestId('match-show-all-btn')).toHaveTextContent( + 'Mostrar tudo', + ); + }); + + it('explains a filtered-empty answer and offers show all instead of a failed search', () => { + const libraryInputSpy = vi.spyOn(commands, 'libraryInput'); + const { unmount } = renderWithProviders( + , + makeMatchSnapshot({ + candidates: [], + results: [], + selected: null, + platformFilter: gamecubeFilter, + filteredOut: 2, + }), + 'en', + ); + + const notice = screen.getByTestId('match-filtered-empty-notice'); + expect(notice).toHaveTextContent('No GameCube results'); + expect(notice).toHaveTextContent('Show all'); + expect(screen.queryByTestId('match-no-results-notice')).not.toBeInTheDocument(); + expect(screen.getByTestId('match-search-input')).toBeInTheDocument(); + + fireEvent.click(screen.getByTestId('match-filtered-empty-show-all')); + expect(libraryInputSpy).toHaveBeenCalledWith({ + setMatchPlatformFilter: { enabled: false }, + }); + + unmount(); + + const pt = renderWithProviders( + , + makeMatchSnapshot({ + candidates: [], + results: [], + selected: null, + platformFilter: gamecubeFilter, + filteredOut: 2, + }), + 'pt-BR', + ); + expect(screen.getByTestId('match-filtered-empty-notice')).toHaveTextContent( + 'Nenhum resultado de GameCube', + ); + + pt.unmount(); + + // A failed search keeps its own error and does not look like a narrowed answer. + renderWithProviders( + , + makeMatchSnapshot({ + candidates: [], + results: [], + selected: null, + platformFilter: gamecubeFilter, + filteredOut: 2, + error: 'failed', + }), + 'en', + ); + expect(screen.getByTestId('match-error-notice')).toBeInTheDocument(); + expect( + screen.queryByTestId('match-filtered-empty-notice'), + ).not.toBeInTheDocument(); + }); + + it('shows no platform filter for an entry without a declared platform', () => { + renderWithProviders(, makeMatchSnapshot(), 'en'); + + expect(screen.queryByTestId('match-platform-filter')).not.toBeInTheDocument(); + expect( + screen.queryByTestId('match-filtered-empty-notice'), + ).not.toBeInTheDocument(); + }); + it('renders search error notices and searchBlocked notice in en and pt-BR', () => { const errorSnap = makeMatchSnapshot({ error: 'rejected', diff --git a/ui/src/features/library/ContextMenu.test.tsx b/ui/src/features/library/ContextMenu.test.tsx index 47c36eb2a..f996b7a27 100644 --- a/ui/src/features/library/ContextMenu.test.tsx +++ b/ui/src/features/library/ContextMenu.test.tsx @@ -107,6 +107,40 @@ describe('ContextMenu', () => { expect(screen.queryByTestId('context-menu-remove')).not.toBeInTheDocument(); }); + it('starts the selected trusted extension for the selected game and operation', async () => { + const target = row({ gamenode: { status: 'playing', collectionIds: [], entryId: 'entry-1' } }); + const library = makeLibrary({ + rows: [target], + selected: ['steam:1'], + detail: detailFor(target), + // A ROM store has no native launch; the extension is what makes Play possible. + actions: { + ...singleActions, + play: { disabled: 'noLaunchRule' as const }, + }, + }); + const extension = { + providerId: 'extension:org.example.helper', + pluginId: 'org.example.helper', + pluginKind: 'extension' as const, + name: 'Helper', + source: 'community' as const, + status: 'installed' as const, + capabilities: [], + session: 'stopped' as const, + nativeAccess: [], + publisherFingerprint: 'a'.repeat(64), + }; + vi.spyOn(commands, 'availablePluginExtensions').mockResolvedValue([extension]); + const start = vi.spyOn(commands, 'startExtensionAction').mockResolvedValue(undefined); + open(library); + + const parent = await screen.findByTestId('context-menu-start-with-extension'); + fireEvent.click(parent); + fireEvent.click(await screen.findByTestId('context-menu-extension-org.example.helper-play')); + await waitFor(() => expect(start).toHaveBeenCalledWith('steam:1', 'org.example.helper', 'play')); + }); + it('anchors at the pointer near the footer without correcting for a menu height', () => { const target = row(); const library = makeLibrary({ diff --git a/ui/src/features/library/ContextMenu.tsx b/ui/src/features/library/ContextMenu.tsx index 54647df86..227c414a5 100644 --- a/ui/src/features/library/ContextMenu.tsx +++ b/ui/src/features/library/ContextMenu.tsx @@ -27,6 +27,7 @@ import { getMatchedGameId, useLibraryView, type EntryStatus, + type PluginInfo, type Reason, } from '../../api'; import { @@ -81,6 +82,11 @@ export const ContextMenu: React.FC = () => { } | null>(null); const [statusOpen, setStatusOpen] = useState(false); const [collectionsOpen, setCollectionsOpen] = useState(false); + const [extensionsOpen, setExtensionsOpen] = useState(false); + const [extensionActions, setExtensionActions] = useState<{ + play: PluginInfo[]; + install: PluginInfo[]; + }>({ play: [], install: [] }); const isOpen = contextMenu.open && contextMenu.entryKey != null; const entryKey = contextMenu.entryKey ?? ''; @@ -91,10 +97,47 @@ export const ContextMenu: React.FC = () => { const row = rows.find((candidate) => candidate.key === entryKey) ?? null; const detail = library?.detail && library.detail.row.key === entryKey ? library.detail : null; + useEffect(() => { + if (!isOpen || !row || isMulti || getMatchedGameId(row.status) == null) { + if (extensionActions.play.length > 0 || extensionActions.install.length > 0) { + setExtensionActions({ play: [], install: [] }); + } + return; + } + let cancelled = false; + const load = async () => { + const [play, install] = await Promise.all([ + // A provider without its own launch rule (for example a ROM store) relies on an + // extension for Play, so an installed row must still offer the extension action. + row.installed + ? commands.availablePluginExtensions('play') + : Promise.resolve([]), + !row.installed + ? commands.availablePluginExtensions('install') + : Promise.resolve([]), + ]); + // The common no-extension result is already the initial state; avoid a needless + // asynchronous render for every ordinary library menu opening. + if ( + !cancelled && + (play.length > 0 || install.length > 0 || extensionActions.play.length > 0 || extensionActions.install.length > 0) + ) { + setExtensionActions({ play, install }); + } + }; + void load().catch(() => { + if (!cancelled) setExtensionActions({ play: [], install: [] }); + }); + return () => { + cancelled = true; + }; + }, [isOpen, isMulti, row?.key, row?.installed, row?.status]); + useEffect(() => { if (!isOpen) { setStatusOpen(false); setCollectionsOpen(false); + setExtensionsOpen(false); } }, [isOpen]); @@ -163,6 +206,18 @@ export const ContextMenu: React.FC = () => { policyReason(actions.install) !== 'noInstallRule'; const toolsReason = single?.running ? formatReason('running', t) : ''; const changeMatch = actions?.changeMatch ?? false; + const extensionChoices = [ + ...extensionActions.play.map((plugin) => ({ plugin, operation: 'play' as const })), + ...extensionActions.install.map((plugin) => ({ plugin, operation: 'install' as const })), + ]; + + const startWithExtension = (plugin: PluginInfo, operation: 'play' | 'install') => { + if (!single) return; + void commands.startExtensionAction(single.key, plugin.pluginId, operation).catch(() => { + pushToast('danger', t('Library::The extension could not be started.')); + }); + close(); + }; const openPage = (page: { game: { id: number } }) => { void commands.openGameNodePage(page).catch(() => { @@ -328,6 +383,48 @@ export const ContextMenu: React.FC = () => { )} + {single && matched && extensionChoices.length > 0 && ( + + + setExtensionsOpen((open) => !open)} + leftSection={} + rightSection={} + > + {t('Library::Start with extension')} + + + + {extensionChoices.map(({ plugin, operation }) => ( + startWithExtension(plugin, operation)} + > + {formatI18n( + t('Library::{} · {}'), + plugin.name, + t(operation === 'play' ? 'Library::Play' : 'Library::Install'), + )} + + ))} + + + )} + {single?.installed && installPath !== '' && ( { + it('requires approval before a detected launch target can be used', async () => { + const reviewSpy = vi.spyOn(commands, 'reviewDetectedTarget').mockResolvedValue(undefined); + const detail = createDetail({ + detectedTarget: { + spec: { + executable: { + root: 'C:\\Games\\Hades', + path: 'Hades.exe', + arguments: [], + workingDirectory: '', + }, + }, + revision: 3, + approved: false, + available: true, + }, + }); + renderDetail(createSnapshot(createLibrary([detail.row], detail))); + expect(screen.getByTestId('detected-target-review')).toHaveTextContent('Hades.exe'); + fireEvent.click(screen.getByTestId('approve-detected-target')); + await waitFor(() => expect(reviewSpy).toHaveBeenCalledWith(detail.row.key, 3)); + }); + beforeEach(() => { resetUiStore(); vi.restoreAllMocks(); @@ -213,6 +236,30 @@ describe('DetailPane', () => { vi.useRealTimers(); }); + it('stops only supervised launches for the selected entry', async () => { + const user = userEvent.setup(); + const list = vi.spyOn(commands, 'customLaunchIds').mockResolvedValue([41, 42]); + const stop = vi.spyOn(commands, 'customLaunchStop').mockResolvedValue(undefined); + renderDetail(createSnapshot(createLibrary([createRow()], createDetail()))); + await user.click(screen.getByTestId('detail-more-btn')); + const action = await screen.findByRole('menuitem', { name: 'Stop custom launch' }); + expect(list).toHaveBeenCalledWith('steam:620'); + await user.click(action); + await waitFor(() => expect(stop).toHaveBeenCalledTimes(2)); + expect(stop).toHaveBeenCalledWith(41); + expect(stop).toHaveBeenCalledWith(42); + }); + + it('reports when termination cannot be confirmed', async () => { + const user = userEvent.setup(); + vi.spyOn(commands, 'customLaunchIds').mockResolvedValue([41]); + vi.spyOn(commands, 'customLaunchStop').mockRejectedValue(new Error('unknown state')); + renderDetail(createSnapshot(createLibrary([createRow()], createDetail()))); + await user.click(screen.getByTestId('detail-more-btn')); + await user.click(await screen.findByRole('menuitem', { name: 'Stop custom launch' })); + expect(await screen.findByText('Could not confirm that the launch stopped. Try again.')).toBeInTheDocument(); + }); + it('shows the matched Steam sections and sends the single-game status change', async () => { const libraryInput = vi.spyOn(commands, 'libraryInput'); const openPage = vi.spyOn(commands, 'openGameNodePage'); diff --git a/ui/src/features/library/DetailPane.tsx b/ui/src/features/library/DetailPane.tsx index cb7f1361c..643655b18 100644 --- a/ui/src/features/library/DetailPane.tsx +++ b/ui/src/features/library/DetailPane.tsx @@ -22,6 +22,7 @@ import { MatchSection } from './detail/MatchSection'; import { AchievementsSection } from './detail/AchievementsSection'; import { MultiSelectionPane } from './detail/MultiSelectionPane'; import { OnThisPcSection } from './detail/OnThisPcSection'; +import { LaunchRecipeSelector } from './detail/LaunchRecipeSelector'; import { entryRegistrationId, isDrmFreeKey, @@ -40,6 +41,8 @@ export const DetailPane: React.FC = () => { const { data: launch } = useSnapshot((s) => s.launch); const { data: storeAccounts } = useSnapshot((s) => s.storeAccounts); const [achievementsOpen, setAchievementsOpen] = React.useState(false); + const [targetActionBusy, setTargetActionBusy] = React.useState(false); + const [targetActionFailed, setTargetActionFailed] = React.useState(false); const detailDragWidth = useUiStore((s) => s.detailDragWidth); const { t } = useI18n(); @@ -128,6 +131,8 @@ export const DetailPane: React.FC = () => { return t('Library::The store application is not installed or cannot be opened.'); case 'unsupported': return t('Library::This store does not support that action.'); + case 'recipeNeedsAttention': + return t('Library::The selected launch recipe needs attention. Review it, choose another recipe, or use the detected default.'); case 'failed': default: return t('Library::The link could not be opened.'); @@ -185,6 +190,37 @@ export const DetailPane: React.FC = () => { const providerAccount = storeAccounts.find( (account) => account.provider === detail?.row.provider, ); + const detectedTarget = detail?.detectedTarget ?? null; + const detectedTargetText = detectedTarget + ? 'executable' in detectedTarget.spec + ? `${detectedTarget.spec.executable.root}\\${detectedTarget.spec.executable.path}` + : detectedTarget.spec.uri + : ''; + const reviewDetectedTarget = async () => { + if (!detail || !detectedTarget) return; + setTargetActionBusy(true); + setTargetActionFailed(false); + try { + await commands.reviewDetectedTarget(detail.row.key, detectedTarget.revision); + } catch { + setTargetActionFailed(true); + } finally { + setTargetActionBusy(false); + } + }; + const repairDetectedTarget = async () => { + if (!detail || !detectedTarget) return; + setTargetActionBusy(true); + setTargetActionFailed(false); + try { + await commands.repairDetectedTarget(detail.row.key, detectedTarget.revision); + } catch { + setTargetActionFailed(true); + } finally { + setTargetActionBusy(false); + } + }; + const nowSeconds = Math.floor(Date.now() / 1000); return ( @@ -270,6 +306,33 @@ export const DetailPane: React.FC = () => {
)} + {detectedTarget && ( +
+
{t('Library::Detected launch target')}
+
{detectedTargetText}
+
+ {!detectedTarget.available + ? t('Library::This target is missing or changed. Locate its executable to repair it.') + : detectedTarget.approved + ? t('Library::Approved. GameNode checks the executable again before launch.') + : t('Library::Review this target before GameNode can start it.')} +
+ {targetActionFailed &&
{t('Library::The target could not be saved or validated.')}
} + {!detectedTarget.approved && detectedTarget.available && ( + + )} + {!detectedTarget.available && 'executable' in detectedTarget.spec && ( + + )} +
+ )} + + {detail && gameId !== null && } + { vi.restoreAllMocks(); }); + it('localizes a known built-in store in the active filter chip', () => { + const active = filters((next) => { + next.stores = ['packagekit']; + }); + const base = makeLibrary(); + const library = makeLibrary({ + providers: [ + { + id: 'packagekit', + name: 'Gerenciador de pacotes Linux', + count: 5, + installedCount: 5, + ownedCount: 0, + sharedCount: 0, + sharedLabel: null, + }, + ], + layout: { ...base.layout, filters: active }, + filterCounts: { + ...base.filterCounts, + stores: [ + { + id: 'packagekit', + name: 'Gerenciador de pacotes Linux', + count: 5, + }, + ], + }, + }); + renderControls(, library); + + expect(screen.getByTestId('library-filter-chip-stores')).toHaveTextContent( + 'Store:Linux Package Manager', + ); + }); + it('renders one joined chip per active facet with copy.md labels', () => { const active = filters((next) => { next.availability = { installed: true, owned: true, shared: false }; diff --git a/ui/src/features/library/batchMatchQueue.test.tsx b/ui/src/features/library/batchMatchQueue.test.tsx index d2ab4a5d0..5ccf3f702 100644 --- a/ui/src/features/library/batchMatchQueue.test.tsx +++ b/ui/src/features/library/batchMatchQueue.test.tsx @@ -48,6 +48,8 @@ function dialogFor(entryKey: string): MatchDialogView { results: [], selected: null, noResults: false, + platformFilter: null, + filteredOut: 0, current: 'unmatched', canClear: false, }; diff --git a/ui/src/features/library/detail/DetailActions.test.tsx b/ui/src/features/library/detail/DetailActions.test.tsx new file mode 100644 index 000000000..a07736f61 --- /dev/null +++ b/ui/src/features/library/detail/DetailActions.test.tsx @@ -0,0 +1,124 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { fireEvent, screen, waitFor } from '@testing-library/react'; +import { + commands, + type Actions, + type DetailView, + type PluginInfo, + type Row, +} from '../../../api'; +import { renderControls } from '../controlsTestUtils'; +import { DetailActions } from './DetailActions'; + +const row: Row = { + key: 'steam:1', + title: 'Game', + detectedName: 'Game', + matchedName: 'Game', + provider: 'steam', + providerName: 'Steam', + installed: true, + owned: true, + shared: false, + running: false, + status: { matched: { gameId: 42, source: 'automatic' } }, + coverFile: null, + playtime: { seconds: 0, source: 'store', lastPlayedAt: null }, + releaseYear: 2020, + addedAt: 0, + isFavorite: false, + hidden: false, + gamenode: null, +}; + +const detail: DetailView = { + running: false, + row, + installDir: '/games/Game', + releaseYear: 2020, + hasArtwork: false, + membership: 'notInLibrary', + achievementBackend: false, + achievements: null, + suggestions: [], +}; + +const actions: Actions = { + selected: 1, + play: { disabled: 'noLaunchRule' }, + install: 'available', + matchGame: 'available', + addToGamenode: 'available', + changeMatch: true, +}; + +const extension: PluginInfo = { + providerId: 'extension:org.example.helper', + pluginId: 'org.example.helper', + pluginKind: 'extension', + name: 'Helper', + source: 'community', + status: 'installed', + capabilities: [], + session: 'stopped', + nativeAccess: [], + publisherFingerprint: 'a'.repeat(64), +}; + +function renderActions() { + return renderControls( + {}} + />, + ); +} + +describe('DetailActions', () => { + beforeEach(() => { + vi.restoreAllMocks(); + }); + + it('offers a trusted extension when the store has no native launch', async () => { + vi.spyOn(commands, 'availablePluginExtensions').mockResolvedValue([extension]); + const start = vi.spyOn(commands, 'startExtensionAction').mockResolvedValue(undefined); + renderActions(); + + const button = await screen.findByTestId('detail-extension-play-btn'); + expect(button).toHaveTextContent('Start with extension · Helper'); + fireEvent.click(button); + await waitFor(() => + expect(start).toHaveBeenCalledWith('steam:1', 'org.example.helper', 'play'), + ); + }); + + it('keeps the normal Play button when the store can launch', async () => { + const available = vi + .spyOn(commands, 'availablePluginExtensions') + .mockResolvedValue([extension]); + renderControls( + {}} + />, + ); + + expect(await screen.findByTestId('detail-play-btn')).toBeInTheDocument(); + expect(screen.queryByTestId('detail-extension-play-btn')).not.toBeInTheDocument(); + expect(available).not.toHaveBeenCalled(); + }); +}); diff --git a/ui/src/features/library/detail/DetailActions.tsx b/ui/src/features/library/detail/DetailActions.tsx index 5c05f9bd0..c527e993c 100644 --- a/ui/src/features/library/detail/DetailActions.tsx +++ b/ui/src/features/library/detail/DetailActions.tsx @@ -5,11 +5,13 @@ import { IconStar, IconStarFilled, } from '@tabler/icons-react'; +import { useEffect, useState } from 'react'; import { commands, type Actions, type DetailView, type GameToolView, + type PluginInfo, } from '../../../api'; import { Button, IconButton } from '../../../components/ui'; import { formatSessionTime } from '../../../hooks/useSessionClock'; @@ -56,6 +58,9 @@ export function DetailActions({ (typeof actions?.install === 'object' && actions.install.disabled !== 'noInstallRule'); const installPrimary = !row.installed && installHasRule; + const [playExtensions, setPlayExtensions] = useState([]); + const [startingExtension, setStartingExtension] = useState(false); + const [extensionError, setExtensionError] = useState(false); const playReason = actions && actions.play !== 'available' ? formatReason(actions.play.disabled, t) @@ -65,6 +70,39 @@ export function DetailActions({ ? formatReason(actions.install.disabled, t) : ''; + useEffect(() => { + let cancelled = false; + if (!row.installed || gameId == null || playReady) { + setPlayExtensions([]); + return; + } + void commands + .availablePluginExtensions('play') + .then((extensions) => { + if (!cancelled) setPlayExtensions(extensions); + }) + .catch(() => { + if (!cancelled) setPlayExtensions([]); + }); + return () => { + cancelled = true; + }; + }, [row.installed, row.key, gameId, playReady]); + + const startWithExtension = async () => { + const plugin = playExtensions[0]; + if (!plugin) return; + setStartingExtension(true); + setExtensionError(false); + try { + await commands.startExtensionAction(row.key, plugin.pluginId, 'play'); + } catch { + setExtensionError(true); + } finally { + setStartingExtension(false); + } + }; + return (
@@ -105,6 +143,17 @@ export function DetailActions({ /> )} + ) : playExtensions.length > 0 && !playReady ? ( + ) : (
- {!isRunning && !installPrimary && !playReady && playReason && ( + {!isRunning && !installPrimary && !playReady && playExtensions.length === 0 && playReason && (
{playReason}
)} + {extensionError && ( +
+ {t('Library::The extension could not be started.')} +
+ )} {!isRunning && installPrimary && !installAvailable && installReason && (
{installReason} diff --git a/ui/src/features/library/detail/LaunchRecipeSelector.test.tsx b/ui/src/features/library/detail/LaunchRecipeSelector.test.tsx new file mode 100644 index 000000000..2e6be71ac --- /dev/null +++ b/ui/src/features/library/detail/LaunchRecipeSelector.test.tsx @@ -0,0 +1,139 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { render, screen, waitFor } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { commands, type LaunchRecipeChoices } from '../../../api'; +import { I18nProvider } from '../../../i18n'; +import { LaunchRecipeSelector } from './LaunchRecipeSelector'; + +const recipe = { + pluginId: 'org.example.launcher', + publisherFingerprint: 'ab'.repeat(32), + recipeId: 'proton-9', + recipeRevision: 3, +}; + +function selection(): NonNullable { + return { + entryKey: 'steam:620', + ownerKey: 'plugin-owner', + ...recipe, + baseTargetRevision: 7, + approvedPlanFingerprint: '', + }; +} + +describe('LaunchRecipeSelector', () => { + afterEach(() => vi.restoreAllMocks()); + + it.each([ + ['en', 'Launch method', 'Use detected default'], + ['pt-BR', 'Método de inicialização', 'Usar padrão detectado'], + ])('lets the user choose a recipe and return to the detected default in %s', async (locale, title, defaultLabel) => { + let selected: LaunchRecipeChoices['selected'] = null; + const choices = vi.spyOn(commands, 'launchRecipeChoices').mockImplementation(async () => ({ + targetRevision: 7, + detectedDefaultAvailable: true, + selected, + recipes: [recipe], + })); + const choose = vi.spyOn(commands, 'selectLaunchRecipe').mockImplementation(async () => { + selected = selection(); + }); + const useDefault = vi.spyOn(commands, 'useDetectedDefault').mockImplementation(async () => { + selected = null; + }); + const user = userEvent.setup(); + + render( + + + , + ); + + expect(await screen.findByText(title)).toBeInTheDocument(); + await user.click(screen.getByTestId('launch-recipe-org.example.launcher-proton-9')); + await waitFor(() => expect(choose).toHaveBeenCalledWith('steam:620', recipe, 7)); + expect(await screen.findByTestId('selected-launch-recipe-status')).toHaveTextContent( + 'Launcher', + ); + expect( + screen.getByTestId('selected-launch-recipe-status'), + ).not.toHaveTextContent('proton-9'); + + await user.click(screen.getByRole('button', { name: defaultLabel })); + await waitFor(() => expect(useDefault).toHaveBeenCalledWith('steam:620', 7)); + await waitFor(() => expect(choices).toHaveBeenCalledTimes(3)); + expect(screen.queryByTestId('use-detected-default')).not.toBeInTheDocument(); + }); + + it('shows the runtime and launch arguments when the host provides a summary', async () => { + const summary = 'Dolphin 2609 — -b -e Pikmin (USA) (Rev 1).rvz'; + let selected: LaunchRecipeChoices['selected'] = null; + vi.spyOn(commands, 'launchRecipeChoices').mockImplementation(async () => ({ + targetRevision: 7, + detectedDefaultAvailable: false, + selected, + recipes: [{ ...recipe, summary }], + })); + vi.spyOn(commands, 'selectLaunchRecipe').mockImplementation(async () => { + selected = selection(); + }); + const user = userEvent.setup(); + + render( + + + , + ); + + const button = await screen.findByRole('button', { name: summary }); + expect(button).not.toHaveTextContent('proton-9'); + await user.click(button); + expect(await screen.findByTestId('selected-launch-recipe-status')).toHaveTextContent( + summary, + ); + }); + + it('shows one method per plugin and never a recipe id', async () => { + vi.spyOn(commands, 'launchRecipeChoices').mockResolvedValue({ + targetRevision: 7, + detectedDefaultAvailable: true, + selected: null, + recipes: [ + recipe, + { ...recipe, recipeId: 'proton-10', recipeRevision: 4 }, + ], + }); + render( + + + , + ); + + const buttons = await screen.findAllByTestId(/^launch-recipe-org\.example\.launcher-/); + expect(buttons).toHaveLength(1); + expect(buttons[0]).toHaveTextContent('Launcher'); + expect(screen.queryByText(/proton-9/)).not.toBeInTheDocument(); + expect(screen.queryByText(/org\.example\.launcher/)).not.toBeInTheDocument(); + }); + + it.each([ + ['en', 'Choose another recipe or return to the detected default', 'Use detected default'], + ['pt-BR', 'Escolha outra receita ou volte ao padrão detectado', 'Usar padrão detectado'], + ])('offers repair when the stored recipe is no longer available in %s', async (locale, alert, defaultLabel) => { + vi.spyOn(commands, 'launchRecipeChoices').mockResolvedValue({ + targetRevision: 8, + detectedDefaultAvailable: true, + selected: { ...selection(), baseTargetRevision: 7 }, + recipes: [], + }); + render( + + + , + ); + + expect(await screen.findByRole('alert')).toHaveTextContent(alert); + expect(screen.getByRole('button', { name: defaultLabel })).toBeEnabled(); + }); +}); diff --git a/ui/src/features/library/detail/LaunchRecipeSelector.tsx b/ui/src/features/library/detail/LaunchRecipeSelector.tsx new file mode 100644 index 000000000..43a6a10b2 --- /dev/null +++ b/ui/src/features/library/detail/LaunchRecipeSelector.tsx @@ -0,0 +1,191 @@ +import React from 'react'; +import { commands, type LaunchRecipeChoices, type LaunchRecipeOption } from '../../../api'; +import { useI18n } from '../../../i18n'; + +interface Props { + entryKey: string; +} + +const KNOWN_LAUNCH_LABELS: Record = { + 'dev.richmont.gamenode.dolphin-emu-launch': 'Dolphin', +}; + +/** A human label for the extension that owns a recipe; recipe ids stay internal. */ +function launchLabel(pluginId: string): string { + const known = KNOWN_LAUNCH_LABELS[pluginId]; + if (known) return known; + const tail = pluginId.split('.').pop() ?? pluginId; + const words = tail.split(/[-_]/).filter(Boolean); + return words.length > 0 + ? words.map((word) => word[0].toUpperCase() + word.slice(1)).join(' ') + : pluginId; +} + +function launchMethodLabel(recipe: LaunchRecipeOption): string { + const summary = recipe.summary?.trim(); + return summary ? summary : launchLabel(recipe.pluginId); +} + +export const LaunchRecipeSelector: React.FC = ({ entryKey }) => { + const { t } = useI18n(); + const [choices, setChoices] = React.useState(null); + const [loading, setLoading] = React.useState(true); + const [busy, setBusy] = React.useState(false); + const [failed, setFailed] = React.useState(false); + + const reload = React.useCallback(async () => { + setLoading(true); + try { + setChoices(await commands.launchRecipeChoices(entryKey)); + setFailed(false); + } catch { + setFailed(true); + } finally { + setLoading(false); + } + }, [entryKey]); + + React.useEffect(() => { + void reload(); + }, [reload]); + + const choose = async (recipe: LaunchRecipeOption) => { + if (!choices) return; + setBusy(true); + setFailed(false); + try { + await commands.selectLaunchRecipe(entryKey, recipe, choices.targetRevision); + await reload(); + } catch { + setFailed(true); + } finally { + setBusy(false); + } + }; + + const useDefault = async () => { + if (!choices) return; + setBusy(true); + setFailed(false); + try { + await commands.useDetectedDefault(entryKey, choices.targetRevision); + await reload(); + } catch { + setFailed(true); + } finally { + setBusy(false); + } + }; + + const selected = choices?.selected ?? null; + const selectedOption = selected + ? choices?.recipes.find( + (recipe) => + recipe.pluginId === selected.pluginId && + recipe.publisherFingerprint === selected.publisherFingerprint && + recipe.recipeId === selected.recipeId && + recipe.recipeRevision === selected.recipeRevision && + selected.baseTargetRevision === choices.targetRevision, + ) + : undefined; + // Historical proposals from failed attempts share the plugin; the user needs one method, not + // one opaque recipe id per attempt. Keep the selected recipe when it still exists. + const visibleRecipes = React.useMemo(() => { + const byPlugin = new Map(); + for (const recipe of choices?.recipes ?? []) { + if (!byPlugin.has(recipe.pluginId)) byPlugin.set(recipe.pluginId, recipe); + } + if (selectedOption) byPlugin.set(selectedOption.pluginId, selectedOption); + return [...byPlugin.values()]; + }, [choices, selectedOption]); + + return ( +
+
+ {t('Library::Launch method')} +
+ {loading ? ( +
+ {t('Library::Loading launch methods…')} +
+ ) : ( + <> + {selected && ( +
+ {selectedOption + ? t('Library::Custom launch method: {}').replace( + '{}', + launchMethodLabel(selectedOption), + ) + : t('Library::The selected recipe changed or is unavailable. Choose another recipe or return to the detected default.')} +
+ )} +
+ {visibleRecipes.map((recipe) => { + const active = + recipe.pluginId === selected?.pluginId && + recipe.publisherFingerprint === selected.publisherFingerprint && + recipe.recipeId === selected.recipeId && + recipe.recipeRevision === selected.recipeRevision && + selected.baseTargetRevision === choices?.targetRevision; + return ( + + ); + })} + {selected && ( + + )} +
+ {!selected && choices && visibleRecipes.length === 0 && ( +
+ {t('Library::No custom launch recipes are available for this game.')} +
+ )} + {selected && !choices?.detectedDefaultAvailable && ( +
+ {t('Library::The detected default is currently unavailable.')} +
+ )} + + )} + {failed && ( +
+ {t('Library::Launch choices could not be saved or refreshed. Check for changes and try again.')} +
+ )} + {!loading && choices?.selected === null && choices && visibleRecipes.length === 0 && ( +
+ {choices.detectedDefaultAvailable + ? t('Library::The detected default is selected.') + : t('Library::No launch method is currently available.')} +
+ )} +
+ ); +}; diff --git a/ui/src/features/library/detail/MoreActionsMenu.tsx b/ui/src/features/library/detail/MoreActionsMenu.tsx index 84f30b643..1ffc8e680 100644 --- a/ui/src/features/library/detail/MoreActionsMenu.tsx +++ b/ui/src/features/library/detail/MoreActionsMenu.tsx @@ -1,8 +1,10 @@ import React from 'react'; import { Menu } from '@mantine/core'; +import { useQuery } from '@tanstack/react-query'; import { IconBookmark, IconCirclePlay, + IconPlayerStop, IconDots, IconDownload, IconFolderOpen, @@ -64,7 +66,16 @@ export function MoreActionsMenu({ }: MoreActionsMenuProps) { const { t } = useI18n(); const [opened, setOpened] = React.useState(false); + const [stoppingLaunch, setStoppingLaunch] = React.useState(false); + const [stopLaunchFailed, setStopLaunchFailed] = React.useState(false); const row = detail.row; + const customLaunches = useQuery({ + queryKey: ['custom-launches', row.key], + queryFn: () => commands.customLaunchIds(row.key), + enabled: opened, + staleTime: 0, + refetchInterval: opened ? 2000 : false, + }); const playReady = actions.play === 'available'; const installHasRule = actions.install === 'available' || @@ -112,6 +123,26 @@ export function MoreActionsMenu({ )} + {(customLaunches.data?.length ?? 0) > 0 && ( + + )} {installHasRule && (
)} + {sources && sources.length > 0 && ( +
+

{t('ports.pluginSources')}

+ {sources.filter((source) => packageMode ? !source.directory : source.directory === (slot.kind === 'folder')).map((source) => ( +
+ + {packageMode && slot.packageOption?.requiresUpdate && } +
+ ))} +
+ )} {slot.acceptedLabels.length > 0 && (

{formatI18n(t('Ports::Accepted: {}'), slot.acceptedLabels.join(', '))} @@ -470,13 +485,14 @@ const RequirementRow: React.FC = ({ */ export const PortSetupModal: React.FC = () => { const { t, locale } = useI18n(); - const { open, catalogId, retryJobId, session } = usePortSetupStore(); + const { open, catalogId, retryJobId, session, pluginRequestId } = usePortSetupStore(); const ports = usePortsView(); const detailQuery = usePortDetail(open ? catalogId : null); const entry = catalogId ? (ports.entries.find((candidate) => candidate.catalogId === catalogId) ?? null) : null; + const pluginReview = ports.pluginRequest?.id === pluginRequestId ? ports.pluginRequest : null; const detail = detailQuery.data ?? null; const requirements = detail?.requirements ?? entry?.requirements ?? []; const release = detail?.selectedRelease ?? releaseFromEntry(entry); @@ -550,6 +566,8 @@ export const PortSetupModal: React.FC = () => { busySlot == null; const handleClose = () => { + if (starting) return; + if (pluginRequestId) void commands.portsDismissPluginSetup(pluginRequestId); closePortSetup(); }; @@ -671,6 +689,7 @@ export const PortSetupModal: React.FC = () => { try { const jobId = await commands.portsInstall({ catalogId: catalogId as string, + ...(pluginRequestId ? { pluginRequestId } : {}), parentFolder, supplied: buildSupplied(requirements, selections), ...(acceptUnverified ? { acceptUnverifiedChecksum: true } : {}), @@ -681,7 +700,8 @@ export const PortSetupModal: React.FC = () => { setStartError(t('Ports::The install could not start.')); return; } - handleClose(); + if (pluginRequestId) void commands.portsDismissPluginSetup(pluginRequestId); + closePortSetup(); } catch (error) { setStartError(installErrorMessage(error, t, locale)); } finally { @@ -771,6 +791,10 @@ export const PortSetupModal: React.FC = () => {

+ {pluginReview &&
+

{t('ports.pluginRequest', { plugin: pluginReview.pluginId })}

+

{pluginReview.publisherFingerprint}

+
} {blockReason && (

{

{t('Ports::Files you need to supply')}

{requirements.map((slot) => ( { + setInteracted(true); + setStartError(null); + setPickErrors((previous) => ({ ...previous, [slot.id]: undefined })); + setSelections((previous) => { + const mode = previous[slot.id]?.mode ?? (slot.packageOption ? 'package' : 'direct'); + const current = previous[slot.id] ?? { mode, path: null, updatePath: null }; + return { ...previous, [slot.id]: { ...current, ...(update ? { updatePath: source.path } : { path: source.path }) } }; + }); + }} key={slot.id} slot={slot} selection={selections[slot.id]} diff --git a/ui/src/features/ports/setup/setup.test.tsx b/ui/src/features/ports/setup/setup.test.tsx index 089dd7c94..63e50fbf4 100644 --- a/ui/src/features/ports/setup/setup.test.tsx +++ b/ui/src/features/ports/setup/setup.test.tsx @@ -24,6 +24,7 @@ import { I18nProvider } from '../../../i18n'; import { resetUiStore } from '../../../store/uiStore'; import { ToastContainer } from '../../settings/ToastContainer'; import { PortFailureDetails, PortSetupHost, openPortSetup } from './index'; +import { PluginPortSetupHost } from './PluginPortSetupHost'; import { portSetupStore, resetPortSetup } from './setupStore'; // --------------------------------------------------------------------------------------- @@ -176,6 +177,7 @@ function renderHost(snapshot: Snapshot, locale = 'en') { + @@ -201,6 +203,39 @@ describe('Port guided setup', () => { vi.restoreAllMocks(); }); + it.each(['en', 'pt-BR'])('reviews a host-issued plugin request and associates approved candidates in %s', async (locale) => { + const slot = makeSlot({ id: 'game', label: 'Game source', kind: 'folder', required: true }); + const entry = makeEntry({ requirements: [slot] }); + const snapshot = makeSnapshot([entry], [], 'D:/Ports'); + snapshot.ports.pluginRequest = { id: 'host-review', catalogId: entry.catalogId, pluginId: '', publisherFingerprint: 'publisher-fingerprint', sources: [{ path: 'D:/Approved/source', directory: true }] }; + vi.spyOn(commands, 'portsDetail').mockResolvedValue(makeDetail(entry)); + const install = vi.spyOn(commands, 'portsInstall').mockResolvedValue('native-job'); + const dismiss = vi.spyOn(commands, 'portsDismissPluginSetup').mockResolvedValue(undefined); + renderHost(snapshot, locale); + await waitFor(() => expect(screen.getByText(//)).toBeInTheDocument()); + expect(screen.getByText('publisher-fingerprint')).toBeInTheDocument(); + expect(screen.getByTestId('port-setup-start')).toBeDisabled(); + expect(install).not.toHaveBeenCalled(); + fireEvent.click(screen.getByRole('button', { name: 'D:/Approved/source' })); + await waitFor(() => expect(screen.getByTestId('port-setup-start')).toBeEnabled()); + clickTestId('port-setup-start'); + await waitFor(() => expect(install).toHaveBeenCalledWith(expect.objectContaining({ pluginRequestId: 'host-review', catalogId: entry.catalogId, supplied: [{ slotId: 'game', path: 'D:/Approved/source' }] }))); + await waitFor(() => expect(dismiss).toHaveBeenCalledWith('host-review')); + }); + + it('preserves an open manual setup when a plugin request arrives', async () => { + const entry = makeEntry(); + const snapshot = makeSnapshot([entry]); + snapshot.ports.pluginRequest = { id: 'host-review', catalogId: entry.catalogId, pluginId: 'fixture.plugin', publisherFingerprint: 'publisher', sources: [] }; + const dismiss = vi.spyOn(commands, 'portsDismissPluginSetup').mockResolvedValue(undefined); + act(() => openPortSetup(entry.catalogId)); + renderHost(snapshot); + await waitFor(() => expect(dismiss).toHaveBeenCalledWith('host-review')); + expect(portSetupStore.state.open).toBe(true); + expect(portSetupStore.state.pluginRequestId).toBeNull(); + expect(screen.queryByText(/fixture.plugin/)).not.toBeInTheDocument(); + }); + it('blocks Start on a required slot, lets an optional slot be skipped, and sends the request', async () => { const required = makeSlot({ id: 'game-folder', diff --git a/ui/src/features/ports/setup/setupStore.ts b/ui/src/features/ports/setup/setupStore.ts index 53df9f5ce..391eaed91 100644 --- a/ui/src/features/ports/setup/setupStore.ts +++ b/ui/src/features/ports/setup/setupStore.ts @@ -8,6 +8,7 @@ import { Store, useStore } from '@tanstack/react-store'; * running in the host after the modal closes, so nothing here tracks progress. */ export interface PortSetupState { + pluginRequestId?: string | null; open: boolean; /** Catalog entry the modal configures; null when no modal was opened yet. */ catalogId: string | null; @@ -27,6 +28,7 @@ export const initialPortSetupState: PortSetupState = { export const portSetupStore = new Store(initialPortSetupState); export interface OpenPortSetupOptions { + pluginRequestId?: string; /** Reuse the stored install plan of this job (Retry from a result). */ retryJobId?: string; } @@ -40,9 +42,11 @@ export function openPortSetup( options: OpenPortSetupOptions = {}, ): void { if (!catalogId) return; + if (portSetupStore.state.open && portSetupStore.state.pluginRequestId && portSetupStore.state.pluginRequestId !== options.pluginRequestId) return; portSetupStore.setState((previous) => ({ open: true, catalogId, + pluginRequestId: options.pluginRequestId ?? null, retryJobId: options.retryJobId ?? null, session: previous.session + 1, })); diff --git a/ui/src/features/settings/PluginActivationPermissions.test.tsx b/ui/src/features/settings/PluginActivationPermissions.test.tsx new file mode 100644 index 000000000..77d34caaa --- /dev/null +++ b/ui/src/features/settings/PluginActivationPermissions.test.tsx @@ -0,0 +1,119 @@ +import { MantineProvider } from '@mantine/core'; +import { fireEvent, render, screen } from '@testing-library/react'; +import { describe, expect, it, vi } from 'vitest'; +import { appTheme } from '../../AppProviders'; +import { I18nProvider } from '../../i18n'; +import type { SharedDataCatalogRecord } from '../../api/types'; +import { PluginActivationPermissions, type PluginActivationPermissionsValue } from './PluginActivationPermissions'; + +const consumerId = 'org.example.consumer'; +const catalog: SharedDataCatalogRecord[] = [ + { + sourcePluginId: 'org.example.source', + sourcePublisherFingerprint: 'SHA256:source', + datasetId: 'org.example.metrics.v1', + class: 'custom', + category: null, + recordId: 'custom-record-1', + fields: ['fps', 'opaque_payload'], + }, + { + sourcePluginId: 'org.example.telemetry', + sourcePublisherFingerprint: 'SHA256:telemetry', + datasetId: 'performance', + class: 'common', + category: 'gamePerformanceHistory', + recordId: 'common-record-1', + fields: ['fps'], + }, +]; + +function renderPermissions( + locale: 'en' | 'pt-BR', + onSave: (value: PluginActivationPermissionsValue) => void, + initialValue?: PluginActivationPermissionsValue, +) { + return render( + + + + + , + ); +} + +describe('PluginActivationPermissions', () => { + it.each([ + ['en', 'Game performance history', 'Save data permissions'], + ['pt-BR', 'Histórico de desempenho dos jogos', 'Salvar permissões de dados'], + ] as const)('defaults to private data and explains separation from retention in %s', (locale, performanceLabel, saveLabel) => { + const onSave = vi.fn(); + renderPermissions(locale, onSave); + + expect(screen.getByRole('switch', { name: performanceLabel })).not.toBeChecked(); + expect(screen.getByRole('checkbox', { name: /common-record-1/ })).not.toBeChecked(); + expect(screen.getByRole('checkbox', { name: 'fps' })).not.toBeChecked(); + expect(screen.getByText(/storage\.persist/i)).toBeInTheDocument(); + expect(screen.getByRole('button', { name: saveLabel })).toBeEnabled(); + + fireEvent.click(screen.getByRole('button', { name: saveLabel })); + expect(onSave).toHaveBeenCalledWith({ commonDataRead: [], selectedRecordIds: [], sourcePolicies: [] }); + }); + + it('saves category, record, and exact source field/history/live choices together', () => { + const onSave = vi.fn(); + renderPermissions('en', onSave); + + fireEvent.click(screen.getByRole('switch', { name: 'Game performance history' })); + fireEvent.click(screen.getByRole('checkbox', { name: /common-record-1/ })); + fireEvent.click(screen.getByRole('checkbox', { name: 'fps' })); + fireEvent.click(screen.getByRole('checkbox', { name: 'opaque_payload' })); + fireEvent.click(screen.getByRole('checkbox', { name: 'Allow historical reads' })); + fireEvent.click(screen.getByRole('checkbox', { name: 'Allow live updates' })); + fireEvent.click(screen.getByRole('button', { name: 'Save data permissions' })); + + expect(onSave).toHaveBeenCalledWith({ + commonDataRead: ['gamePerformanceHistory'], + selectedRecordIds: ['common-record-1'], + sourcePolicies: [{ + sourcePluginId: 'org.example.source', + sourcePublisherFingerprint: 'SHA256:source', + datasetId: 'org.example.metrics.v1', + class: 'custom', + fields: ['fps', 'opaque_payload'], + history: true, + live: true, + }], + }); + }); + + it('restores persisted review choices and lets the user revoke a dataset policy', () => { + const onSave = vi.fn(); + const initialValue: PluginActivationPermissionsValue = { + commonDataRead: ['gamePerformanceHistory'], + selectedRecordIds: ['common-record-1'], + sourcePolicies: [{ + sourcePluginId: 'org.example.source', + sourcePublisherFingerprint: 'SHA256:source', + datasetId: 'org.example.metrics.v1', + class: 'custom', + fields: ['fps'], + history: true, + live: false, + }], + }; + renderPermissions('en', onSave, initialValue); + + expect(screen.getByRole('switch', { name: 'Game performance history' })).toBeChecked(); + expect(screen.getByRole('checkbox', { name: /common-record-1/ })).toBeChecked(); + expect(screen.getByRole('checkbox', { name: 'fps' })).toBeChecked(); + fireEvent.click(screen.getByRole('checkbox', { name: 'fps' })); + fireEvent.click(screen.getByRole('button', { name: 'Save data permissions' })); + + expect(onSave).toHaveBeenCalledWith({ + commonDataRead: ['gamePerformanceHistory'], + selectedRecordIds: ['common-record-1'], + sourcePolicies: [], + }); + }); +}); diff --git a/ui/src/features/settings/PluginActivationPermissions.tsx b/ui/src/features/settings/PluginActivationPermissions.tsx new file mode 100644 index 000000000..7bdf7884e --- /dev/null +++ b/ui/src/features/settings/PluginActivationPermissions.tsx @@ -0,0 +1,224 @@ +import React, { useEffect, useMemo, useState } from 'react'; +import { Switch } from '@mantine/core'; +import type { + SharedDataCategory, + SharedDataCatalogRecord, + SharedDataSourcePolicy, +} from '../../api/types'; +import { useI18n } from '../../i18n'; +import { settingsCard, settingsRow, settingsRowDescription, settingsRowInfo, settingsRowTitle } from './settingsClasses'; + +export interface PluginActivationPermissionsValue { + commonDataRead: SharedDataCategory[]; + selectedRecordIds: string[]; + sourcePolicies: SharedDataSourcePolicy[]; +} + +interface Props { + pluginId: string; + catalog?: SharedDataCatalogRecord[]; + initialValue?: PluginActivationPermissionsValue; + busy?: boolean; + onSave: (value: PluginActivationPermissionsValue) => void; +} + +const COMMON_CATEGORIES: SharedDataCategory[] = [ + 'gamePaths', + 'gamePerformanceHistory', + 'runtimeCatalog', + 'contentAvailability', + 'libraryRoots', + 'saveProfiles', +]; + +function policyKey(policy: Pick): string { + return JSON.stringify([policy.sourcePluginId, policy.sourcePublisherFingerprint, policy.datasetId, policy.class]); +} + +export const PluginActivationPermissions: React.FC = ({ + pluginId, + catalog = [], + initialValue, + busy = false, + onSave, +}) => { + const { t } = useI18n(); + const [commonDataRead, setCommonDataRead] = useState(initialValue?.commonDataRead ?? []); + const [selectedRecordIds, setSelectedRecordIds] = useState(initialValue?.selectedRecordIds ?? []); + const [sourcePolicies, setSourcePolicies] = useState(initialValue?.sourcePolicies ?? []); + + useEffect(() => { + setCommonDataRead(initialValue?.commonDataRead ?? []); + setSelectedRecordIds(initialValue?.selectedRecordIds ?? []); + setSourcePolicies(initialValue?.sourcePolicies ?? []); + }, [initialValue]); + + const datasets = useMemo(() => { + const rows = new Map; + recordIds: Set; + }>(); + for (const record of catalog) { + if (record.sourcePluginId === pluginId || (record.class !== 'sensitive' && record.class !== 'custom')) continue; + const identity = { + sourcePluginId: record.sourcePluginId, + sourcePublisherFingerprint: record.sourcePublisherFingerprint, + datasetId: record.datasetId, + class: record.class, + }; + const key = policyKey(identity); + const row = rows.get(key) ?? { ...identity, fields: new Set(), recordIds: new Set() }; + record.fields.forEach((field) => row.fields.add(field)); + row.recordIds.add(record.recordId); + rows.set(key, row); + } + for (const policy of sourcePolicies) { + const key = policyKey(policy); + const row = rows.get(key) ?? { + sourcePluginId: policy.sourcePluginId, + sourcePublisherFingerprint: policy.sourcePublisherFingerprint, + datasetId: policy.datasetId, + class: policy.class, + fields: new Set(), + recordIds: new Set(), + }; + policy.fields.forEach((field) => row.fields.add(field)); + rows.set(key, row); + } + return [...rows.entries()].map(([key, row]) => ({ ...row, key, fields: [...row.fields].sort() })) + .sort((left, right) => `${left.sourcePluginId}:${left.datasetId}`.localeCompare(`${right.sourcePluginId}:${right.datasetId}`)); + }, [catalog, pluginId, sourcePolicies]); + + const commonRecords = useMemo(() => { + const records = catalog.filter((record) => record.class === 'common' && record.sourcePluginId !== pluginId); + const seen = new Set(records.map((record) => record.recordId)); + for (const recordId of selectedRecordIds) { + if (!seen.has(recordId)) records.push({ + sourcePluginId: t('plugins.activation.unknownSource'), + sourcePublisherFingerprint: '', + datasetId: '', + class: 'common', + category: null, + recordId, + fields: [], + }); + } + return records; + }, [catalog, pluginId, selectedRecordIds, t]); + + const toggle = (values: T[], value: T, update: (next: T[]) => void) => { + update(values.includes(value) ? values.filter((item) => item !== value) : [...values, value]); + }; + const label = (key: string) => t(`plugins.activation.${key}`); + const policyFor = (key: string) => sourcePolicies.find((policy) => policyKey(policy) === key); + const updatePolicy = (key: string, patch: Partial) => { + const dataset = datasets.find((row) => row.key === key); + if (!dataset) return; + setSourcePolicies((current) => { + const existing = current.find((policy) => policyKey(policy) === key); + const next = { + sourcePluginId: dataset.sourcePluginId, + sourcePublisherFingerprint: dataset.sourcePublisherFingerprint, + datasetId: dataset.datasetId, + class: dataset.class, + fields: existing?.fields ?? [], + history: existing?.history ?? false, + live: existing?.live ?? false, + ...existing, + ...patch, + } satisfies SharedDataSourcePolicy; + const other = current.filter((policy) => policyKey(policy) !== key); + if (next.fields.length === 0) return other; + return [...other, next]; + }); + }; + + return ( +
+
+

{label('title')}

+

{label('grantExplanation')}

+
+
+ {label('commonTitle')} +

{label('commonDescription')}

+ {COMMON_CATEGORIES.map((category) => ( +
+
{label(`category.${category}`)}
+ toggle(commonDataRead, category, setCommonDataRead)} color="brand" disabled={busy} /> +
+ ))} +

+ {label('queryPolicy')} +

+
+ +
+ {label('selectedRecordsTitle')} +

{label('selectedRecordsDescription')}

+ {commonRecords.length === 0 ?

{label('noSelectedRecordsAvailable')}

: commonRecords.map((record) => ( + + ))} +
+ +
+ {label('sensitiveTitle')} +

{label('sensitiveDescription')}

+ {datasets.length === 0 ?

{label('noDatasetsAvailable')}

: datasets.map((dataset) => { + const current = policyFor(dataset.key); + return ( +
+

{dataset.datasetId}

+

{label('source')}: {dataset.sourcePluginId} · {dataset.sourcePublisherFingerprint} · {dataset.class}

+ {dataset.fields.map((field) => ( + + ))} +
+ + +
+
+ ); + })} +

+ {label('retentionSeparate')} +

+
+ + +
+ ); +}; diff --git a/ui/src/features/settings/PluginBundleDetails.tsx b/ui/src/features/settings/PluginBundleDetails.tsx new file mode 100644 index 000000000..800641151 --- /dev/null +++ b/ui/src/features/settings/PluginBundleDetails.tsx @@ -0,0 +1,673 @@ +import React, { useMemo, useState } from 'react'; +import { useQueries, useQuery, useQueryClient } from '@tanstack/react-query'; +import { + commands, + type AvailableBundleRollback, + type AvailableBundleUpdate, + type BundleComponentPermissionSubmission, + type BundleUninstallOutcome, + type BundleUpdateReview, + type PluginBundleComponent, + type PluginInfo, + type PluginPermissionSnapshot, +} from '../../api'; +import { pluginQueryKeys } from '../../api/pluginQueryKeys'; +import { useI18n } from '../../i18n'; +import { RememberedConfirmations } from './RememberedConfirmations'; +import { + settingsCard, + settingsPill, + settingsPillSuccess, + settingsPillWarning, + settingsRowDescription, + settingsRowTitle, +} from './settingsClasses'; + +function statusClass(status: PluginBundleComponent['status']) { + return status === 'installed' + ? settingsPillSuccess + : status === 'unavailable' || status === 'incompatible' || status === 'missing' + ? settingsPillWarning + : settingsPill; +} + +function scopeChoiceKey( + snapshot: PluginPermissionSnapshot, + permissionId: string, + scope: unknown, +): string { + return JSON.stringify([ + snapshot.pluginId, + snapshot.publisherFingerprint, + snapshot.profileId, + snapshot.grantRevision, + permissionId, + scope, + ]); +} + +interface PluginBundleDetailsProps { + bundle: PluginInfo; + profileId: string | null; + busy: boolean; + onToggleEnabled: (pluginId: string, enabled: boolean) => Promise; + onRequestUninstall: () => void; + uninstallOutcome: BundleUninstallOutcome | null; + uninstallError: boolean; +} + +/** + * Details of one aggregated bundle entry. Every component keeps its own identity and lifecycle: + * activation is toggled per component, permissions are reviewed and saved per component in one + * grouped submission, and the single uninstall lives on the bundle itself. + */ +export const PluginBundleDetails: React.FC = ({ + bundle, + profileId, + busy, + onToggleEnabled, + onRequestUninstall, + uninstallOutcome, + uninstallError, +}) => { + const { t } = useI18n(); + const queryClient = useQueryClient(); + const components = useMemo(() => bundle.bundleComponents ?? [], [bundle.bundleComponents]); + const [scopeChoices, setScopeChoices] = useState>({}); + const [saving, setSaving] = useState(false); + const [saveError, setSaveError] = useState(false); + const [componentErrors, setComponentErrors] = useState>({}); + const [saved, setSaved] = useState(false); + const [bundleUpdateReview, setBundleUpdateReview] = useState(null); + const [bundleUpdateOperation, setBundleUpdateOperation] = useState< + 'check' | 'review' | 'approve' | 'rollbackReview' | 'rollbackApprove' | null + >(null); + const [bundleUpdateError, setBundleUpdateError] = useState(null); + const [bundleUpdateResult, setBundleUpdateResult] = useState<{ + version: string; + rollback: boolean; + } | null>(null); + const [rollbackConfirmed, setRollbackConfirmed] = useState(false); + + const bundleId = bundle.bundleId ?? ''; + const { data: availableBundleUpdates = [], refetch: refetchBundleUpdates } = useQuery< + AvailableBundleUpdate[] + >({ + queryKey: ['plugin-bundle-updates', bundleId], + queryFn: commands.pluginBundleUpdateAvailable, + enabled: profileId !== null && bundleId.length > 0, + }); + const { data: availableBundleRollbacks = [], refetch: refetchBundleRollbacks } = useQuery< + AvailableBundleRollback[] + >({ + queryKey: ['plugin-bundle-rollbacks', bundleId], + queryFn: commands.pluginBundleRollbackAvailable, + enabled: profileId !== null && bundleId.length > 0, + }); + const bundleUpdate = availableBundleUpdates.find((update) => update.bundleId === bundleId); + const bundleRollback = availableBundleRollbacks.find((rollback) => rollback.bundleId === bundleId); + + const snapshotQueries = useQueries({ + queries: components.map((component) => ({ + queryKey: pluginQueryKeys.permissions( + component.pluginId, + profileId ?? '', + component.publisherFingerprint, + ), + queryFn: async () => { + if (!profileId) throw new Error('plugin permission profile is unavailable'); + const snapshot = await commands.pluginPermissionSnapshot(component.pluginId, profileId); + if (snapshot.publisherFingerprint !== component.publisherFingerprint) { + throw new Error('plugin permission publisher changed'); + } + return snapshot; + }, + enabled: profileId !== null && Boolean(component.publisherFingerprint), + })), + }); + + const savePermissions = async () => { + const snapshots = snapshotQueries.flatMap((query) => (query.data ? [query.data] : [])); + if (snapshots.length === 0) return; + const submissions: BundleComponentPermissionSubmission[] = snapshots.map((snapshot) => ({ + pluginId: snapshot.pluginId, + expectedProfileId: snapshot.profileId, + expectedPublisherFingerprint: snapshot.publisherFingerprint, + expectedRevision: snapshot.grantRevision, + decisions: snapshot.requestedPermissions.flatMap((request) => + request.allowed_scopes.map((scope) => { + const key = scopeChoiceKey(snapshot, request.permission_id, scope); + const persisted = snapshot.effectiveGrants.some( + (grant) => + grant.permission_id === request.permission_id + && JSON.stringify(grant.scope) === JSON.stringify(scope) + && grant.state === 'granted', + ); + return { + permission_id: request.permission_id, + scope, + granted: scopeChoices[key] ?? persisted, + }; + }), + ), + })); + setSaving(true); + setSaveError(false); + setSaved(false); + setComponentErrors({}); + try { + const result = await commands.pluginBundlePermissionsReplace(submissions); + const errors: Record = {}; + for (const component of result.components) { + if (component.error) errors[component.pluginId] = component.error; + } + setComponentErrors(errors); + setScopeChoices({}); + setSaved(true); + await Promise.all( + snapshots.flatMap((snapshot) => [ + queryClient.invalidateQueries({ + queryKey: pluginQueryKeys.permissions( + snapshot.pluginId, + snapshot.profileId, + snapshot.publisherFingerprint, + ), + }), + queryClient.invalidateQueries({ queryKey: pluginQueryKeys.inventory }), + ]), + ); + } catch { + setSaveError(true); + setScopeChoices({}); + await Promise.all( + snapshots.map((snapshot) => + queryClient.invalidateQueries({ + queryKey: pluginQueryKeys.permissions( + snapshot.pluginId, + snapshot.profileId, + snapshot.publisherFingerprint, + ), + }), + ), + ); + } finally { + setSaving(false); + } + }; + + const hasPermissions = snapshotQueries.some( + (query) => (query.data?.requestedPermissions.length ?? 0) > 0, + ); + + const refreshBundleState = async () => { + await Promise.all([ + queryClient.invalidateQueries({ queryKey: pluginQueryKeys.inventory }), + refetchBundleUpdates(), + refetchBundleRollbacks(), + ]); + }; + + const checkBundleUpdates = async () => { + setBundleUpdateOperation('check'); + setBundleUpdateError(null); + setBundleUpdateResult(null); + try { + await commands.pluginBundleUpdateCheck(); + await refreshBundleState(); + } catch { + setBundleUpdateError('plugins.bundle.updateError.check'); + await refreshBundleState(); + } finally { + setBundleUpdateOperation(null); + } + }; + + const reviewBundleUpdate = async (version: string, rollback: boolean) => { + setBundleUpdateOperation(rollback ? 'rollbackReview' : 'review'); + setBundleUpdateError(null); + setBundleUpdateResult(null); + setRollbackConfirmed(false); + try { + setBundleUpdateReview( + rollback + ? await commands.pluginBundleRollbackReview(bundleId, version) + : await commands.pluginBundleUpdateReview(bundleId, version), + ); + } catch { + setBundleUpdateError('plugins.bundle.updateError.review'); + await refreshBundleState(); + } finally { + setBundleUpdateOperation(null); + } + }; + + const approveBundleUpdate = async () => { + if (!bundleUpdateReview) return; + setBundleUpdateOperation('approve'); + setBundleUpdateError(null); + setBundleUpdateResult(null); + try { + const outcome = await commands.pluginBundleUpdateApprove( + bundleUpdateReview.bundleId, + bundleUpdateReview.candidateVersion, + ); + setBundleUpdateReview(null); + setBundleUpdateResult({ version: outcome.version, rollback: false }); + await refreshBundleState(); + } catch { + // A failed persistence leaves the displayed bundle and its saved controls untouched; the + // host state is re-read rather than showing an optimistic version. + setBundleUpdateError('plugins.bundle.updateError.save'); + await refreshBundleState(); + } finally { + setBundleUpdateOperation(null); + } + }; + + const approveBundleRollback = async () => { + if (!bundleUpdateReview || !rollbackConfirmed) return; + setBundleUpdateOperation('rollbackApprove'); + setBundleUpdateError(null); + setBundleUpdateResult(null); + try { + const outcome = await commands.pluginBundleRollbackApprove( + bundleUpdateReview.bundleId, + bundleUpdateReview.candidateVersion, + true, + ); + setBundleUpdateReview(null); + setRollbackConfirmed(false); + setBundleUpdateResult({ version: outcome.version, rollback: true }); + await refreshBundleState(); + } catch { + setBundleUpdateError('plugins.bundle.updateError.save'); + await refreshBundleState(); + } finally { + setBundleUpdateOperation(null); + } + }; + + return ( +
+
+

{bundle.bundleName ?? bundle.name}

+ {t('plugins.community')} + {t(`plugins.status.${bundle.status}`)} +
+

+ {t('plugins.bundle.version')}: {bundle.bundleVersion ?? bundle.version} +

+ {bundle.bundlePublisherFingerprint && ( +

+ {t('plugins.publisherFingerprint')}: {bundle.bundlePublisherFingerprint} +

+ )} + {profileId === null && ( +

{t('plugins.signInRequired')}

+ )} + +
    + {components.map((component, index) => { + const snapshot = snapshotQueries[index]?.data; + const canToggle = profileId !== null + && component.status !== 'incompatible' + && component.runtimeAvailable !== false; + const enabled = component.enabled === true; + return ( +
  • +
    +

    {component.name}

    + + {t(`plugins.bundle.kind.${component.pluginKind}`)} + + + {t(`plugins.status.${component.status}`)} + + {component.pluginKind === 'extension' && component.runtimeAvailable === false && ( + + {t('plugins.bundle.runtimeUnavailable')} + + )} +
    +

    + {t('plugins.identifier')}: {component.pluginId} +

    +

    + {t('plugins.import.version')}: {component.version} +

    + {component.publisherFingerprint && ( +

    + {t('plugins.publisherFingerprint')}: {component.publisherFingerprint} +

    + )} + {profileId !== null && ( +
    + + + {t(enabled ? 'plugins.bundle.enabledFor' : 'plugins.bundle.disabledFor', { + name: component.name, + })} + +
    + )} + {profileId !== null && snapshot && ( +
    + {snapshot.requestedPermissions.length === 0 ? ( +

    {t('plugins.bundle.noPermissions')}

    + ) : snapshot.requestedPermissions.map((request) => ( +
    + + {request.permission_id}{request.required ? ` · ${t('plugins.required')}` : ''} + + {request.allowed_scopes.map((scope) => { + const key = scopeChoiceKey(snapshot, request.permission_id, scope); + const effective = snapshot.effectiveGrants.find( + (grant) => + grant.permission_id === request.permission_id + && JSON.stringify(grant.scope) === JSON.stringify(scope), + ); + const active = effective?.state === 'granted'; + return ( + + ); + })} +
    + ))} + {componentErrors[component.pluginId] && ( +

    + {component.name}: {componentErrors[component.pluginId]} +

    + )} +
    + )} + {component.pluginId && bundle.bundlePublisherFingerprint && component.publisherFingerprint && ( + + )} +
  • + ); + })} +
+ + {profileId !== null && hasPermissions && ( + + )} + {saved && !saveError && ( +

{t('plugins.bundle.permissionsSaved')}

+ )} + {saveError && ( +

{t('plugins.management.failed')}

+ )} + +
+

{t('plugins.bundle.updates.title')}

+ {profileId === null ? ( +

{t('plugins.signInRequired')}

+ ) : ( + <> + + + {bundleUpdate && bundleUpdate.versions.length > 0 && ( +
+

+ {t('plugins.bundle.updates.available', { + version: bundleUpdate.installedVersion, + })} +

+
+ {bundleUpdate.versions.map((version) => ( + + ))} +
+
+ )} + + {bundleRollback && bundleRollback.versions.length > 0 && ( +
+

+ {t('plugins.bundle.updates.rollbackTitle', { + version: bundleRollback.activeVersion, + })} +

+
+ {bundleRollback.versions.map((version) => ( + + ))} +
+
+ )} + + {bundleUpdateOperation !== null && bundleUpdateOperation !== 'check' && ( +

+ {t('plugins.bundle.updates.working')} +

+ )} + {bundleUpdateError && ( +

{t(bundleUpdateError)}

+ )} + {bundleUpdateResult && ( +

+ {t( + bundleUpdateResult.rollback + ? 'plugins.bundle.updates.rollbackComplete' + : 'plugins.bundle.updates.updateComplete', + { version: bundleUpdateResult.version }, + )} +

+ )} + + {bundleUpdateReview && ( +
+

+ {bundleUpdateReview.name}: {bundleUpdateReview.installedVersion} →{' '} + {bundleUpdateReview.candidateVersion} +

+

+ {t('plugins.bundle.updates.bundleHash')}: {bundleUpdateReview.bundleSha256} +

+

+ {t('plugins.bundle.updates.permissionDiff')}: +{bundleUpdateReview.addedPermissions.join(', ') || '—'} + {' · '}±{bundleUpdateReview.changedPermissions.join(', ') || '—'} + {' · '}−{bundleUpdateReview.removedPermissions.join(', ') || '—'} +

+
    + {bundleUpdateReview.components.map((component) => ( +
  • +
    + {component.pluginId} + {t(`plugins.bundle.kind.${component.kind}`)} + + {component.installedVersion} → {component.candidateVersion} + + + {t(`plugins.bundle.availability.${component.availability.status}`)} + +
    + {component.availability.status === 'unavailable' && ( +

    + {t(`plugins.bundle.unavailable.${component.availability.reason}`)} +

    + )} +

    + {t('plugins.import.compatibility')}: {t(`plugins.import.${component.compatibility}`)} +

    +

    + {t('plugins.bundle.updates.permissionDiff')}: +{component.addedPermissions.join(', ') || '—'} + {' · '}±{component.changedPermissions.join(', ') || '—'} + {' · '}−{component.removedPermissions.join(', ') || '—'} +

    + {component.permissionChanges.map((change) => ( +

    + {change.id}: {change.installedScope} → {change.candidateScope} +

    + ))} +
  • + ))} +
+ {bundleUpdateReview.isRollback && ( + + )} +
+ + +
+
+ )} + + )} +
+ + {profileId !== null && ( +
+ +

{t('plugins.bundle.uninstallDescription')}

+
+ )} + + {uninstallOutcome && ( +
+ {uninstallOutcome.failures.length === 0 ? ( +

{t('plugins.bundle.uninstallComplete', { + retention: t(uninstallOutcome.dataRetention === 'deleted' + ? 'plugins.bundle.retention.deleted' + : 'plugins.bundle.retention.kept'), + })}

+ ) : ( + <> +

{t('plugins.bundle.uninstallPartial')}

+
    + {uninstallOutcome.failures.map((failure) => ( +
  • + {failure.pluginId} {failure.version}: {failure.error} +
  • + ))} +
+ + )} +
+ )} + {uninstallError && ( +

{t('plugins.bundle.uninstallFailed')}

+ )} +
+ ); +}; diff --git a/ui/src/features/settings/PluginCompatibilityReview.test.tsx b/ui/src/features/settings/PluginCompatibilityReview.test.tsx new file mode 100644 index 000000000..6e5c28029 --- /dev/null +++ b/ui/src/features/settings/PluginCompatibilityReview.test.tsx @@ -0,0 +1,91 @@ +import { describe, expect, it } from 'vitest'; +import { render, screen, within } from '@testing-library/react'; +import type { PluginCompatibilityDetails, PluginTargetAssessment } from '../../api'; +import { I18nProvider } from '../../i18n'; +import { PluginCompatibilityReview } from './PluginCompatibilityReview'; + +const glibcTarget: PluginTargetAssessment['target'] = { + os: 'linux', arch: 'x86_64', abi: 'gnu', entrypoint: 'bin/linux-gnu/plugin', + requires: { linux: { libc: { family: 'glibc', min_version: '2.31' } } }, + tested_on: [{ distribution: 'ubuntu', version: '22.04' }], +}; + +function details(overrides: Partial): PluginCompatibilityDetails { + return { + state: 'compatible', ambiguous: false, os: 'ubuntu', release: '22.04', architecture: 'x86_64', abi: 'gnu', + libc: { family: 'gnu', version: '2.35' }, emulation: 'native', + targets: [{ target: glibcTarget, verdict: { state: 'compatible', reasons: ['requirementsSatisfied'], unknownFacts: [] } }], + ...overrides, + }; +} + +function renderReview(value: PluginCompatibilityDetails, locale = 'en') { + return render(); +} + +describe('PluginCompatibilityReview', () => { + it('shows a musl host against a glibc target as incompatible with the libc reason', () => { + renderReview(details({ + state: 'incompatible', os: 'alpine', release: '3.19', libc: { family: 'musl', version: '1.2.4' }, abi: 'musl', + targets: [{ target: glibcTarget, verdict: { state: 'incompatible', reasons: ['linuxLibcMismatch', 'abiMismatch'], unknownFacts: [] } }], + })); + const section = screen.getByRole('region', { name: 'Compatibility with this system' }); + expect(within(section).getAllByText('Incompatible').length).toBeGreaterThan(0); + expect(section).toHaveTextContent('The C library family does not match (glibc and musl are not interchangeable).'); + expect(within(section).getByText('musl 1.2.4')).toBeInTheDocument(); + expect(section).toHaveTextContent('C library: glibc 2.31 or newer'); + expect(section).toHaveTextContent('No target of this package is compatible with this system, so it cannot be activated.'); + expect(section).not.toHaveTextContent('Activation is still allowed'); + }); + + it('does not treat unknown mandatory facts as compatible', () => { + renderReview(details({ + state: 'indeterminate', libc: { family: 'unknown' }, + targets: [{ target: glibcTarget, verdict: { state: 'indeterminate', reasons: ['linuxLibcUnknown'], unknownFacts: ['libc'] } }], + })); + const section = screen.getByRole('region', { name: 'Compatibility with this system' }); + expect(section).toHaveTextContent('Cannot be determined'); + expect(section).toHaveTextContent('The C library could not be determined.'); + expect(section).toHaveTextContent('Could not be determined: libc'); + expect(section).toHaveTextContent('cannot be activated'); + expect(section).not.toHaveTextContent('A target of this package is compatible'); + }); + + it('keeps author-tested coverage separate from a compatible but untested system', () => { + renderReview(details({ os: 'fedora', release: '40' })); + const section = screen.getByRole('region', { name: 'Compatibility with this system' }); + expect(within(section).getAllByText('Compatible')).toHaveLength(2); + expect(section).toHaveTextContent('Compatible with this system, but the author has not listed it as tested.'); + expect(section).toHaveTextContent('Author-tested environments (informational): ubuntu 22.04'); + }); + + it('reports a tested system and a package without tested environments', () => { + const { unmount } = renderReview(details({})); + expect(screen.getByRole('region')).toHaveTextContent('This system matches an environment the author tested.'); + unmount(); + renderReview(details({ targets: [{ target: { ...glibcTarget, tested_on: [] }, verdict: { state: 'compatible', reasons: ['requirementsSatisfied'], unknownFacts: [] } }] })); + expect(screen.getByRole('region')).toHaveTextContent('The author lists no tested environments.'); + }); + + it('blocks activation text when several targets are compatible', () => { + renderReview(details({ ambiguous: true, state: 'incompatible' })); + expect(screen.getByRole('region')).toHaveTextContent('More than one target is compatible'); + }); + + it('renders the same facts in pt-BR', () => { + renderReview(details({ + state: 'incompatible', libc: { family: 'musl', version: '1.2.4' }, + targets: [{ target: glibcTarget, verdict: { state: 'incompatible', reasons: ['linuxLibcMismatch'], unknownFacts: [] } }], + }), 'pt-BR'); + const section = screen.getByRole('region', { name: 'Compatibilidade com este sistema' }); + expect(section).toHaveTextContent('Incompatível'); + expect(section).toHaveTextContent('A família da biblioteca C não corresponde (glibc e musl não são intercambiáveis).'); + expect(within(section).getByText('musl 1.2.4')).toBeInTheDocument(); + expect(section).toHaveTextContent('Ambientes testados pelo autor (informativo): ubuntu 22.04'); + }); + + it('shows pt-BR compatible-but-untested activation state', () => { + renderReview(details({ os: 'fedora', release: '40' }), 'pt-BR'); + expect(screen.getByRole('region')).toHaveTextContent('Compatível com este sistema, mas o autor não o listou como testado.'); + }); +}); diff --git a/ui/src/features/settings/PluginCompatibilityReview.tsx b/ui/src/features/settings/PluginCompatibilityReview.tsx new file mode 100644 index 000000000..28a7ff35e --- /dev/null +++ b/ui/src/features/settings/PluginCompatibilityReview.tsx @@ -0,0 +1,150 @@ +import React from 'react'; +import type { + PluginCompatibilityDetails, + PluginCompatibilityState, + PluginTargetAssessment, +} from '../../api'; +import { useI18n } from '../../i18n'; +import { settingsPill, settingsPillSuccess, settingsPillWarning, settingsRowDescription, settingsRowTitle } from './settingsClasses'; + +type Translate = (key: string, params?: Record) => string; + +function verdictClass(state: PluginCompatibilityState): string { + if (state === 'compatible') return settingsPillSuccess; + if (state === 'incompatible') return settingsPillWarning; + return settingsPill; +} + +function libcLabel(libc: PluginCompatibilityDetails['libc'], t: Translate): string | null { + if (!libc) return null; + const family = t(`plugins.compat.libc.${libc.family}`); + return 'version' in libc && libc.version ? `${family} ${libc.version}` : family; +} + +/** Plain-language declarations from the signed target requirements; absent ones are omitted. */ +function requirementLines(target: PluginTargetAssessment['target'], t: Translate): string[] { + const lines: string[] = []; + const windows = target.requires?.windows; + if (windows?.product) lines.push(t('plugins.compat.requirement.windowsProduct', { value: t(`plugins.compat.product.${windows.product}`) })); + if (windows?.min_version || windows?.max_version) { + lines.push(t('plugins.compat.requirement.windowsVersion', { min: windows.min_version ?? '—', max: windows.max_version ?? '—' })); + } + if (windows?.min_build != null || windows?.max_build != null) { + lines.push(t('plugins.compat.requirement.windowsBuild', { min: windows.min_build ?? '—', max: windows.max_build ?? '—' })); + } + const linux = target.requires?.linux; + if (linux?.libc) { + lines.push(t('plugins.compat.requirement.libc', { + family: t(`plugins.compat.libc.${linux.libc.family === 'glibc' ? 'gnu' : 'musl'}`), + version: linux.libc.min_version, + })); + } + if (linux?.distributions?.length) { + lines.push(t('plugins.compat.requirement.distributions', { + value: linux.distributions.map((entry) => `${entry.id} ${entry.versions.join(', ')}`).join('; '), + })); + } + return lines; +} + +function testedLabels(target: PluginTargetAssessment['target']): string[] { + return target.tested_on.map((entry) => [ + entry.distribution ?? entry.product, + entry.version ?? entry.release, + ].filter(Boolean).join(' ')).filter((label) => label.length > 0); +} + +/** Whether the detected system matches an author-declared tested environment. Informational. */ +function matchesTested(target: PluginTargetAssessment['target'], details: PluginCompatibilityDetails): boolean { + return target.tested_on.some((entry) => { + if (entry.distribution) { + return entry.distribution === details.os && (!entry.version || entry.version === details.release); + } + if (entry.product) { + return entry.product === details.product && (!entry.release || entry.release === details.release); + } + return false; + }); +} + +function summaryKey(details: PluginCompatibilityDetails): string { + if (details.ambiguous) return 'plugins.compat.summary.ambiguous'; + return `plugins.compat.summary.${details.state}`; +} + +export interface PluginCompatibilityReviewProps { + details: PluginCompatibilityDetails; +} + +/** + * Target requirements, the detected effective environment, the compatibility verdict with its + * reasons, and the author-tested coverage. The tested list is shown separately and never changes + * whether the package may be activated. + */ +export const PluginCompatibilityReview: React.FC = ({ details }) => { + const { t } = useI18n(); + const unknown = t('plugins.compat.unknownValue'); + const environment: Array<[string, string]> = [ + [t('plugins.compat.os'), details.os ?? unknown], + [t('plugins.compat.release'), details.release ?? unknown], + ...(details.product && details.product !== 'unknown' ? [[t('plugins.compat.product'), t(`plugins.compat.product.${details.product}`)] as [string, string]] : []), + ...(details.build != null ? [[t('plugins.compat.build'), String(details.build)] as [string, string]] : []), + [t('plugins.compat.architecture'), details.architecture ?? unknown], + [t('plugins.compat.abi'), details.abi ?? unknown], + [t('plugins.compat.libc'), libcLabel(details.libc, t) ?? unknown], + [t('plugins.compat.emulation'), t(`plugins.compat.emulation.${details.emulation}`)], + ]; + const selected = details.targets.filter((entry) => entry.verdict.state === 'compatible'); + const compatibleUntested = details.state === 'compatible' && !details.ambiguous && selected.length === 1 + ? !matchesTested(selected[0].target, details) + : false; + + return ( +
+
+

{t('plugins.compat.title')}

+ {t(`plugins.compat.verdict.${details.state}`)} +
+

{t(summaryKey(details))}

+ {details.state === 'compatible' && !details.ambiguous && selected.length === 1 && ( +

+ {t(compatibleUntested ? 'plugins.compat.coverage.untested' : 'plugins.compat.coverage.tested')} +

+ )} +

{t('plugins.compat.environment')}

+
+ {environment.map(([label, value]) => ( + +
{label}
+
{value}
+
+ ))} +
+

{t('plugins.compat.targets')}

+
    + {details.targets.map((entry) => { + const requirements = requirementLines(entry.target, t); + const tested = testedLabels(entry.target); + return ( +
  • +
    + {entry.target.os} · {entry.target.arch} · {entry.target.abi} + {t(`plugins.compat.verdict.${entry.verdict.state}`)} +
    +

    {t('plugins.compat.requirements')}: {requirements.length ? requirements.join(' · ') : t('plugins.compat.requirementsNone')}

    +
      + {entry.verdict.reasons.map((reason) =>
    • {t(`plugins.compat.reason.${reason}`)}
    • )} +
    + {entry.verdict.unknownFacts.length > 0 && ( +

    {t('plugins.compat.unknownFacts')}: {entry.verdict.unknownFacts.join(', ')}

    + )} +

    + {t('plugins.compat.tested')}: {tested.length ? tested.join('; ') : t('plugins.compat.testedNone')} +

    +
  • + ); + })} +
+
+ ); +}; diff --git a/ui/src/features/settings/PluginConfigurationSurface.tsx b/ui/src/features/settings/PluginConfigurationSurface.tsx new file mode 100644 index 000000000..c356b8566 --- /dev/null +++ b/ui/src/features/settings/PluginConfigurationSurface.tsx @@ -0,0 +1,53 @@ +import React, { useState } from 'react'; +import { commands } from '../../api'; +import type { PluginInfo } from '../../api'; +import type { ConfigurationChoice } from '../../api/pluginSettings'; +import { useI18n } from '../../i18n'; +import { PluginDeclarativeSettings } from './PluginDeclarativeSettings'; +import { settingsRowDescription } from './settingsClasses'; + +type RequestState = 'idle' | 'opening' | 'focusing' | 'open' | 'focused' | 'unavailable' | 'denied' | 'timedOut' | 'failed'; + +export const PluginConfigurationSurface: React.FC<{ + plugin: PluginInfo; + choice?: ConfigurationChoice; + loading?: boolean; +}> = ({ plugin, choice, loading = false }) => { + const { t } = useI18n(); + const [requestState, setRequestState] = useState('idle'); + const [windowOpen, setWindowOpen] = useState(false); + const [requesting, setRequesting] = useState(false); + const enabled = plugin.status === 'installed' && plugin.session === 'active'; + + const configure = async () => { + if (!enabled || requesting) return; + const focus = windowOpen; + setRequesting(true); + setRequestState(focus ? 'focusing' : 'opening'); + try { + const result = await commands.pluginConfigurationOpen(plugin.providerId, focus); + setRequestState(result.status); + const accepted = result.status === 'open' || result.status === 'focused'; + setWindowOpen(accepted); + } catch { + setRequestState('unavailable'); + setWindowOpen(false); + } finally { + setRequesting(false); + } + }; + + if (!enabled) return

{t('plugins.configure.disabled')}

; + if (loading) return

{t('plugins.configure.loading')}

; + if (!choice) return

{t('plugins.configure.unavailable')}

; + + if (choice === 'external') return
+ + {requestState !== 'idle' &&

{t(`plugins.configure.status.${requestState}`)}

} +
; + if (choice === 'form') return ; + if (choice === 'denied') return

{t('plugins.settings.denied')}

; + return

{t('plugins.settings.absent')}

; +}; diff --git a/ui/src/features/settings/PluginDeclarativeSettings.tsx b/ui/src/features/settings/PluginDeclarativeSettings.tsx new file mode 100644 index 000000000..1ca81ac31 --- /dev/null +++ b/ui/src/features/settings/PluginDeclarativeSettings.tsx @@ -0,0 +1,101 @@ +import React, { useEffect, useState } from 'react'; +import { commands } from '../../api'; +import type { PluginSettingsContext, PluginSettingsField, PluginSettingsForm, PluginSettingsReply, PluginSettingsValue } from '../../api/pluginSettings'; +import { useI18n } from '../../i18n'; +import { settingsCard, settingsRowDescription, settingsRowTitle } from './settingsClasses'; + +function localized(text: { fallback: string; translations: Record }, locale: string) { + return text.translations[locale] ?? text.translations[locale.split('-')[0]] ?? text.fallback; +} + +function FormField({ + field, value, locale, onChange, +}: { + field: PluginSettingsField; + value: PluginSettingsValue; + locale: string; + onChange: (value: PluginSettingsValue) => void; +}) { + const label = localized(field.label, locale); + const help = field.help ? localized(field.help, locale) : undefined; + let control: React.ReactNode; + switch (field.kind.type) { + case 'boolean': + control = onChange({ type: 'boolean', value: event.currentTarget.checked })} />; + break; + case 'text': + control = onChange({ type: 'text', value: event.currentTarget.value })} />; + break; + case 'number': + control = onChange({ type: 'number', value: Number(event.currentTarget.value) })} />; + break; + case 'choice': + control = ; + break; + } + return
+ + {help &&

{help}

} +
; +} + +export const PluginDeclarativeSettings: React.FC<{ providerId: string }> = ({ providerId }) => { + const { t, locale } = useI18n(); + const [reply, setReply] = useState(null); + const [values, setValues] = useState>({}); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(false); + + const describe = async () => { + setBusy(true); + setError(false); + try { + const result = await commands.pluginSettingsDescribe(providerId); + setReply(result); + if (result.outcome.type === 'form') setValues(result.outcome.values); + } catch { setError(true); } + finally { setBusy(false); } + }; + + useEffect(() => { void describe(); }, [providerId]); + + const submit = async (form: PluginSettingsForm, context: PluginSettingsContext) => { + setBusy(true); + setError(false); + try { + const result = await commands.pluginSettingsSubmit(context, form.schema_revision, form.configuration_revision, values); + setReply(result); + if (result.outcome.type === 'form') setValues(result.outcome.values); + if (result.outcome.type === 'revision_conflict') await describe(); + } catch { setError(true); } + finally { setBusy(false); } + }; + + const cancel = async (context: PluginSettingsContext) => { + setBusy(true); + setError(false); + try { setReply(await commands.pluginSettingsCancel(context)); } + catch { setError(true); } + finally { setBusy(false); } + }; + + const formReply = reply?.outcome.type === 'form' ? reply.outcome : undefined; + const form = formReply?.form; + return
+ {form && formReply && reply && <> +

{localized(form.title, locale)}

+
+ {form.fields.map((field) => setValues((current) => ({ ...current, [field.id]: value }))} />)} +
+
+ + +
+ } + {!form &&

{busy ? t('plugins.settings.loading') : error ? t('plugins.settings.failed') : t('plugins.settings.unavailable')}

} + {error && form &&

{t('plugins.settings.failed')}

} + {reply?.outcome.type === 'applied' &&

{t('plugins.settings.saved')}

} + {reply?.outcome.type === 'failed' &&

{t('plugins.settings.failed')}

} + {reply?.outcome.type === 'field_errors' && Object.entries(reply.outcome.errors).map(([field, message]) =>

{localized(message, locale)}

)} +
; +}; diff --git a/ui/src/features/settings/PluginDurableUsage.test.tsx b/ui/src/features/settings/PluginDurableUsage.test.tsx new file mode 100644 index 000000000..10e3b39ac --- /dev/null +++ b/ui/src/features/settings/PluginDurableUsage.test.tsx @@ -0,0 +1,83 @@ +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import { MantineProvider } from '@mantine/core'; +import { fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { commands, type PluginDurableUsage } from '../../api'; +import { appTheme } from '../../AppProviders'; +import { I18nProvider } from '../../i18n'; +import { PluginDurableUsage as PluginDurableUsageSection } from './PluginDurableUsage'; + +const usage: PluginDurableUsage = { + pluginId: 'org.example.producer', + profileId: 'a', + recordCount: 3, + logicalBytes: 4096, + maxBytes: 1024 * 1024, + maxAgeSeconds: 30 * 24 * 60 * 60, + oldestUpdatedAt: 1_700_000_000, +}; + +function renderUsage(locale = 'en') { + const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + render( + + + + + + + , + ); + return client; +} + +describe('PluginDurableUsage', () => { + beforeEach(() => { + vi.restoreAllMocks(); + }); + + it('shows logical usage and limits without disclosing a physical path', async () => { + vi.spyOn(commands, 'pluginDurableUsage').mockResolvedValue(usage); + renderUsage(); + + expect(await screen.findByText('Records: 3')).toBeInTheDocument(); + expect(screen.getByText('Retained size: 4 KB')).toBeInTheDocument(); + expect(screen.getByText('Size limit: 1 MB')).toBeInTheDocument(); + expect(screen.getByText('Age limit: 30 days')).toBeInTheDocument(); + const text = screen.getByRole('region', { name: 'Retained shared data' }).textContent ?? ''; + for (const leaked of ['/home', '\\\\', '.sqlite3', 'plugin-data', 'plugin-shared-data']) { + expect(text).not.toContain(leaked); + } + }); + + it('requires confirmation before deleting and reports the reclaimed size', async () => { + vi.spyOn(commands, 'pluginDurableUsage').mockResolvedValue(usage); + const remove = vi.spyOn(commands, 'pluginDurableDelete').mockResolvedValue({ + pluginId: usage.pluginId, + profileId: usage.profileId, + removedRecords: 3, + reclaimedBytes: 4096, + usage: { ...usage, recordCount: 0, logicalBytes: 0 }, + }); + renderUsage(); + + fireEvent.click(await screen.findByRole('button', { name: 'Delete retained data' })); + expect(remove).not.toHaveBeenCalled(); + expect(screen.getByText(/only this plugin's durable shared records/i)).toBeInTheDocument(); + + fireEvent.click(screen.getByRole('button', { name: 'Delete data' })); + await waitFor(() => expect(remove).toHaveBeenCalledWith('org.example.producer', 'a', true)); + expect(await screen.findByText('Deleted 4 KB of retained shared data.')).toBeInTheDocument(); + expect(screen.getByText('This plugin retains no durable shared records.')).toBeInTheDocument(); + }); + + it('renders the Portuguese limits and cleanup copy', async () => { + vi.spyOn(commands, 'pluginDurableUsage').mockResolvedValue(usage); + renderUsage('pt-BR'); + + expect(await screen.findByText('Registros: 3')).toBeInTheDocument(); + expect(screen.getByText('Tamanho retido: 4 KB')).toBeInTheDocument(); + expect(screen.getByText('Limite de idade: 30 dias')).toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'Excluir dados retidos' })).toBeInTheDocument(); + }); +}); diff --git a/ui/src/features/settings/PluginDurableUsage.tsx b/ui/src/features/settings/PluginDurableUsage.tsx new file mode 100644 index 000000000..6c14df668 --- /dev/null +++ b/ui/src/features/settings/PluginDurableUsage.tsx @@ -0,0 +1,182 @@ +import React, { useState } from 'react'; +import { useQuery, useQueryClient } from '@tanstack/react-query'; +import { commands } from '../../api'; +import { AppModal } from '../../components/AppModal'; +import { pluginQueryKeys } from '../../api/pluginQueryKeys'; +import { useI18n } from '../../i18n'; +import { formatBytes } from '../ports/catalog/format'; +import { + settingsButtonSecondary, + settingsRowDescription, + settingsRowTitle, +} from './settingsClasses'; + +interface PluginDurableUsageProps { + pluginId: string; + profileId: string | null; +} + +/** + * The durable public-pool usage of one producer. The host reports only logical values; this + * surface never receives or shows a physical path, and cleanup never uninstalls the plugin. + */ +export const PluginDurableUsage: React.FC = ({ + pluginId, + profileId, +}) => { + const { t, locale } = useI18n(); + const client = useQueryClient(); + const queryKey = pluginQueryKeys.durableUsage(pluginId, profileId ?? ''); + const [confirming, setConfirming] = useState(false); + const [deleting, setDeleting] = useState(false); + const [failed, setFailed] = useState(false); + const [reclaimed, setReclaimed] = useState(null); + const { data, isPending, isError } = useQuery({ + queryKey, + queryFn: async () => { + const usage = await commands.pluginDurableUsage(pluginId, profileId!); + if (usage.pluginId !== pluginId || usage.profileId !== profileId) { + throw new Error('plugin durable usage profile changed'); + } + return usage; + }, + enabled: profileId !== null, + }); + + const remove = async () => { + if (!profileId) return; + setDeleting(true); + setFailed(false); + try { + const result = await commands.pluginDurableDelete(pluginId, profileId, true); + client.setQueryData(queryKey, result.usage); + setReclaimed(result.reclaimedBytes); + setConfirming(false); + } catch { + setFailed(true); + await client.invalidateQueries({ queryKey }); + } finally { + setDeleting(false); + } + }; + + const days = data?.maxAgeSeconds + ? Math.max(1, Math.round(data.maxAgeSeconds / 86_400)) + : null; + + return ( +
+

{t('plugins.durableUsage.title')}

+

+ {t('plugins.durableUsage.description')} +

+ {profileId === null ? ( +

+ {t('plugins.signInRequired')} +

+ ) : isPending ? ( +

+ {t('plugins.durableUsage.loading')} +

+ ) : isError || !data ? ( +

+ {t('plugins.durableUsage.error')} +

+ ) : data.recordCount === 0 ? ( +

+ {t('plugins.durableUsage.empty')} +

+ ) : ( +
+

+ {t('plugins.durableUsage.records')}: {data.recordCount} +

+

+ {t('plugins.durableUsage.size')}:{' '} + {formatBytes(data.logicalBytes, locale)} +

+

+ {t('plugins.durableUsage.maxBytes')}:{' '} + {formatBytes(data.maxBytes, locale)} +

+

+ {days === null + ? t('plugins.durableUsage.noAge') + : t('plugins.durableUsage.maxAge', { days })} +

+ +
+ )} + {failed && ( +

+ {t('plugins.durableUsage.deleteFailed')} +

+ )} + {reclaimed !== null && ( +

+ {t('plugins.durableUsage.deleted', { + size: formatBytes(reclaimed, locale), + })} +

+ )} + + !deleting && setConfirming(false)} + closeOnEscape={!deleting} + closeOnClickOutside={!deleting} + > + + + + + {t('plugins.durableUsage.deleteTitle')} + + + + +

+ {t('plugins.durableUsage.deleteConfirm')} +

+
+ + +
+
+
+
+
+ ); +}; diff --git a/ui/src/features/settings/PluginFolderApprovals.test.tsx b/ui/src/features/settings/PluginFolderApprovals.test.tsx new file mode 100644 index 000000000..ef5ca56af --- /dev/null +++ b/ui/src/features/settings/PluginFolderApprovals.test.tsx @@ -0,0 +1,66 @@ +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { MantineProvider } from '@mantine/core'; +import { appTheme } from '../../AppProviders'; +import { commands, type PluginFolderApproval } from '../../api'; +import { I18nProvider } from '../../i18n'; +import { PluginFolderApprovals } from './PluginFolderApprovals'; + +const approvals: PluginFolderApproval[] = [ + { + id: 'file-1', pluginId: 'community.example', publisherFingerprint: 'ab'.repeat(32), + installationName: 'Space Game', kind: 'save', root: 'C:\\Games\\Space\\Saves', + operations: ['read'], affectedGames: ['Space Game'], revoked: false, declaredByPlugin: true, + logicalLibrary: false, libraryId: null, watching: null, + }, + { + id: 'root-1', pluginId: 'community.example', publisherFingerprint: 'ab'.repeat(32), + installationName: 'Game roots', kind: 'library', root: 'C:\\Games', + operations: ['read', 'plugin_discovery', 'core_executable_discovery'], affectedGames: [], + revoked: false, declaredByPlugin: false, logicalLibrary: true, libraryId: 'library-1', watching: true, + }, +]; + +function renderPanel(locale = 'en') { + const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + return render( + + + + + + + , + ); +} + +describe('PluginFolderApprovals', () => { + beforeEach(() => { + vi.spyOn(commands, 'pluginFolderApprovals').mockResolvedValue(approvals); + vi.spyOn(commands, 'pluginFolderChange').mockResolvedValue(undefined); + vi.spyOn(commands, 'pluginFolderRevoke').mockResolvedValue(true); + vi.spyOn(commands, 'pluginLibraryRootSetWatching').mockResolvedValue(true); + }); + afterEach(() => vi.restoreAllMocks()); + + it.each([ + ['en', 'Folder access and library roots', 'Stop Core monitoring'], + ['pt-BR', 'Acesso a pastas e raízes de biblioteca', 'Parar monitoramento pelo Core'], + ])('lists scopes and exposes separate file and Core monitoring controls in %s', async (locale, heading, stopWatching) => { + renderPanel(locale); + expect(await screen.findByRole('region', { name: heading })).toBeInTheDocument(); + expect(await screen.findByText('C:\\Games\\Space\\Saves')).toBeInTheDocument(); + expect(screen.getByText(/does not grant file bytes|não concede acesso aos arquivos/)).toBeInTheDocument(); + + fireEvent.click(screen.getByRole('button', { name: stopWatching })); + await waitFor(() => expect(commands.pluginLibraryRootSetWatching).toHaveBeenCalledWith( + 'community.example', 'ab'.repeat(32), 'root-1', false, + )); + + fireEvent.click(screen.getByRole('button', { name: locale === 'en' ? 'Change folder…' : 'Alterar pasta…' })); + await waitFor(() => expect(commands.pluginFolderChange).toHaveBeenCalledWith( + 'community.example', 'ab'.repeat(32), 'file-1', + )); + }); +}); diff --git a/ui/src/features/settings/PluginFolderApprovals.tsx b/ui/src/features/settings/PluginFolderApprovals.tsx new file mode 100644 index 000000000..d5c372c03 --- /dev/null +++ b/ui/src/features/settings/PluginFolderApprovals.tsx @@ -0,0 +1,82 @@ +import React, { useState } from 'react'; +import { useQuery, useQueryClient } from '@tanstack/react-query'; +import { commands, type PluginFolderApproval } from '../../api'; +import { useI18n } from '../../i18n'; +import { settingsButtonSecondary, settingsRowDescription, settingsRowTitle } from './settingsClasses'; + +const queryKey = (pluginId: string, publisher: string) => ['plugin-folder-approvals', pluginId, publisher] as const; + +export const PluginFolderApprovals: React.FC<{ pluginId: string; publisherFingerprint: string }> = ({ + pluginId, + publisherFingerprint, +}) => { + const { t } = useI18n(); + const client = useQueryClient(); + const [busy, setBusy] = useState(null); + const [error, setError] = useState(false); + const { data = [], isPending, isError } = useQuery({ + queryKey: queryKey(pluginId, publisherFingerprint), + queryFn: () => commands.pluginFolderApprovals(pluginId, publisherFingerprint), + }); + + const refresh = async () => client.invalidateQueries({ queryKey: queryKey(pluginId, publisherFingerprint) }); + const revoke = async (approval: PluginFolderApproval) => { + setBusy(approval.id); setError(false); + try { await commands.pluginFolderRevoke(pluginId, publisherFingerprint, approval.id); await refresh(); } + catch { setError(true); } + finally { setBusy(null); } + }; + const change = async (approval: PluginFolderApproval) => { + setBusy(approval.id); setError(false); + try { await commands.pluginFolderChange(pluginId, publisherFingerprint, approval.id); await refresh(); } + catch { setError(true); } + finally { setBusy(null); } + }; + const setWatching = async (approval: PluginFolderApproval) => { + setBusy(approval.id); setError(false); + try { + await commands.pluginLibraryRootSetWatching(pluginId, publisherFingerprint, approval.id, approval.watching !== true); + await refresh(); + } catch { setError(true); } + finally { setBusy(null); } + }; + + return ( +
+

{t('plugins.folders.title')}

+ {isPending &&

{t('plugins.folders.loading')}

} + {(isError || error) &&

{t('plugins.folders.error')}

} + {!isPending && !isError && data.length === 0 &&

{t('plugins.folders.empty')}

} +
    + {data.map((approval) => ( +
  • +
    +

    {approval.installationName} · {t(`plugins.folder.kind.${approval.kind}`)}

    + {approval.revoked && {t('plugins.folders.revoked')}} +
    +

    {approval.root}

    +

    {approval.operations.map((operation) => t(`plugins.folder.operation.${operation}`)).join(', ')}

    + {approval.declaredByPlugin &&

    {t('plugins.folder.declaredUnverified')}

    } + {approval.logicalLibrary ? ( + <> +

    {t('plugins.folders.rootDisclosure')}

    +
    + + +
    + + ) : ( + <> + {approval.affectedGames.length > 0 &&

    {t('plugins.folder.affectedGames')}: {approval.affectedGames.join(', ')}

    } +
    + {!approval.revoked && } + {!approval.revoked && } +
    + + )} +
  • + ))} +
+
+ ); +}; diff --git a/ui/src/features/settings/PluginImportPermissions.tsx b/ui/src/features/settings/PluginImportPermissions.tsx new file mode 100644 index 000000000..2ae2d5e17 --- /dev/null +++ b/ui/src/features/settings/PluginImportPermissions.tsx @@ -0,0 +1,106 @@ +import React from 'react'; +import type { PluginImportPermissionReview } from '../../api'; +import { useI18n } from '../../i18n'; +import { + settingsPill, + settingsPillWarning, + settingsRowDescription, + settingsRowTitle, +} from './settingsClasses'; +import { + importPermissionAllowed, + importPermissionLabel, + importScopeLabel, + type ImportPermissionDecisions, +} from './pluginImportReview'; + +interface PluginImportPermissionsProps { + permissions: PluginImportPermissionReview[]; + decisions: ImportPermissionDecisions; + onDecisionsChange: (decisions: ImportPermissionDecisions) => void; + disabled?: boolean; + ariaLabel: string; + emptyLabel: string; +} + +/** + * Readable permission rows shared by the package and bundle import reviews. Required + * permissions are locked with an explanation; optional ones default to allowed and show + * what stops working before the user turns them off. + */ +export const PluginImportPermissions: React.FC = ({ + permissions, + decisions, + onDecisionsChange, + disabled = false, + ariaLabel, + emptyLabel, +}) => { + const { t } = useI18n(); + + if (permissions.length === 0) { + return

{emptyLabel}

; + } + + return ( +
    + {permissions.map((permission) => { + const label = importPermissionLabel(permission.id, t); + const allowed = importPermissionAllowed(permission, decisions); + const impact = permission.impactIfDisabled || t('plugins.import.permissionImpactFallback'); + return ( +
  • +
    +
    +

    {label}

    +

    + + {importScopeLabel(permission.scope, t)} + + + {permission.required + ? t('plugins.import.requiredBadge') + : t('plugins.import.optionalBadge')} + +

    +

    {permission.reason}

    + {permission.required ? ( +

    + {t('plugins.import.requiredLocked')} +

    + ) : !allowed ? ( +

    + {impact} +

    + ) : null} +
    + {!permission.required && ( + { + const next = { ...decisions }; + if (event.currentTarget.checked) delete next[permission.id]; + else next[permission.id] = false; + onDecisionsChange(next); + }} + /> + )} +
    +
  • + ); + })} +
+ ); +}; diff --git a/ui/src/features/settings/PluginInventory.bundle.test.tsx b/ui/src/features/settings/PluginInventory.bundle.test.tsx new file mode 100644 index 000000000..d9723e1cc --- /dev/null +++ b/ui/src/features/settings/PluginInventory.bundle.test.tsx @@ -0,0 +1,844 @@ +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { fireEvent, render, screen, waitFor, within } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { MantineProvider } from '@mantine/core'; +import { appTheme } from '../../AppProviders'; +import { + commands, + createDefaultSnapshot, + SNAPSHOT_QUERY_KEY, + type PluginBundleImportReview, + type PluginGrantScope, + type PluginInfo, + type PluginPermissionSnapshot, +} from '../../api'; +import { I18nProvider } from '../../i18n'; +import { PluginInventory } from './PluginInventory'; + +const openFile = vi.fn(); +vi.mock('@tauri-apps/plugin-dialog', () => ({ open: (...args: unknown[]) => openFile(...args) })); +vi.mock('@tauri-apps/api/event', () => ({ listen: vi.fn(async () => () => {}) })); + +const publisher = `SHA256:${'ef'.repeat(32)}`; + +const official: PluginInfo = { + providerId: 'steam', + pluginId: 'org.gamenode.plugin.steam-discovery', + pluginKind: 'provider', + name: 'Steam', + version: '0.1.0', + source: 'official', + status: 'installed', + capabilities: ['library.discovery'], + session: 'active', + nativeAccess: ['files', 'network'], +}; + +const bundle: PluginInfo = { + providerId: '', + pluginId: 'org.example.dolphin.bundle', + pluginKind: 'bundle', + name: 'Dolphin GameCube and Wii', + version: '0.2.0', + source: 'community', + status: 'installed', + capabilities: [], + session: 'stopped', + nativeAccess: ['files', 'network', 'process'], + bundleId: 'org.example.dolphin.bundle', + bundleName: 'Dolphin GameCube and Wii', + bundleVersion: '0.2.0', + bundlePublisherFingerprint: publisher, + bundleComponents: [ + { + pluginId: 'org.example.dolphin', + pluginKind: 'provider', + name: 'Dolphin discovery', + version: '0.1.0', + status: 'installed', + session: 'stopped', + enabled: false, + runtimeAvailable: true, + publisherFingerprint: publisher, + nativeAccess: ['files', 'network'], + }, + { + pluginId: 'org.example.dolphin.launch', + pluginKind: 'extension', + name: 'Dolphin launch', + version: '0.2.0', + status: 'unavailable', + session: 'stopped', + enabled: false, + runtimeAvailable: false, + publisherFingerprint: publisher, + nativeAccess: ['files', 'process'], + }, + ], +}; + +function renderInventory(locale = 'en', profileId?: string) { + const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + if (profileId) { + client.setQueryData(SNAPSHOT_QUERY_KEY, { + ...createDefaultSnapshot(), + auth: { signedIn: { user: { id: profileId } } }, + }); + } + return render( + + + + + + + , + ); +} + +function permissionSnapshot( + pluginId: string, + permissionId: string, + scope: PluginPermissionSnapshot['requestedPermissions'][number]['allowed_scopes'][number], + revision = 0, +): PluginPermissionSnapshot { + return { + pluginId, + publisherFingerprint: publisher, + profileId: 'account-one', + grantRevision: revision, + requestedPermissions: [{ permission_id: permissionId, required: false, allowed_scopes: [scope] }], + effectiveGrants: [], + }; +} + +const providerScope: PluginGrantScope = { scope: 'declared', value: 'https://api.example.com' }; +const extensionScope: PluginGrantScope = { scope: 'selected-records', category: 'runtime', record_ids: [] }; + +function bundleReview(trust: PluginBundleImportReview['trust'] = 'untrusted'): PluginBundleImportReview { + const component = ( + kind: 'provider' | 'extension', + pluginId: string, + name: string, + version: string, + ): PluginBundleImportReview['components'][number] => ({ + kind, + availability: kind === 'provider' + ? { status: 'available' as const } + : { status: 'unavailable' as const, reason: 'noCompatibleTarget' as const }, + review: { + pluginId, + name, + version, + publisherKeyId: 'dolphin-dev', + publisherFingerprint: publisher, + trust, + license: 'MIT', + licenseFiles: ['licenses/LICENSE'], + licenseNotices: [], + permissionIds: kind === 'provider' ? ['storage.persist'] : ['game.launch'], + requestedPermissions: kind === 'provider' + ? [{ + id: 'storage.persist', + required: false, + scope: 'own-provider', + reason: 'Keep the local catalog.', + impactIfDisabled: 'The local catalog is rebuilt on every start.', + }] + : [{ + id: 'game.launch', + required: false, + scope: 'approved-game-session', + reason: 'Start the selected game.', + impactIfDisabled: 'Games cannot be launched from GameNode.', + }], + supportedPlatforms: ['gamecube', 'wii'], + nativeAccess: ['files'], + playtime: { identifiesGameplay: false, identifiesPauses: false, withoutPauseDetection: 'disabled' as const }, + compatibility: kind === 'provider' ? 'compatible' as const : 'incompatible' as const, + compatibilityDetails: { + state: kind === 'provider' ? 'compatible' as const : 'incompatible' as const, + ambiguous: false, os: 'linux', release: '24.04', architecture: 'x86_64', abi: 'gnu', + libc: { family: 'gnu' as const, version: '2.39' }, emulation: 'native' as const, + targets: [], + }, + }, + }); + return { + token: 'bundle-token', + bundle: { + id: 'org.example.dolphin.bundle', + name: 'Dolphin GameCube and Wii', + version: '0.2.0', + publisherKeyId: 'dolphin-dev', + publisherFingerprint: publisher, + }, + trust, + license: { + expressions: ['MIT'], + components: [ + { pluginId: 'org.example.dolphin', expression: 'MIT', files: ['LICENSE'], notices: [] }, + { pluginId: 'org.example.dolphin.launch', expression: 'MIT', files: ['LICENSE'], notices: [] }, + ], + }, + components: [ + component('provider', 'org.example.dolphin', 'Dolphin discovery', '0.1.0'), + component('extension', 'org.example.dolphin.launch', 'Dolphin launch', '0.2.0'), + ], + }; +} + +function bundleUpdateReviewFixture(rollback = false) { + const component = ( + pluginId: string, + kind: 'provider' | 'extension', + installedVersion: string, + candidateVersion: string, + ) => ({ + pluginId, + kind, + installedVersion, + candidateVersion, + addedPermissions: rollback ? [] : ['library.write'], + removedPermissions: [], + changedPermissions: ['game.launch'], + permissionChanges: [{ + id: 'game.launch', + installedScope: 'approved-game-session', + candidateScope: 'selected-game-session', + installedRequired: false, + candidateRequired: false, + }], + addedNativeAccess: [], + removedNativeAccess: [], + apiChanged: false, + installedApi: '1.6.0', + candidateApi: '1.6.0', + availability: { status: 'available' as const }, + compatibility: 'compatible' as const, + compatibilityDetails: { + state: 'compatible' as const, + ambiguous: false, os: 'linux', release: '24.04', architecture: 'x86_64', abi: 'gnu', + libc: { family: 'gnu' as const, version: '2.39' }, emulation: 'native' as const, targets: [], + }, + publisherChanged: false, + isDowngrade: rollback, + }); + return { + bundleId: 'org.example.dolphin.bundle', + name: 'Dolphin GameCube and Wii', + installedVersion: rollback ? '0.3.0' : '0.2.0', + candidateVersion: rollback ? '0.2.0' : '0.3.0', + bundleSha256: 'ab'.repeat(32), + publisherFingerprint: publisher, + components: [ + component( + 'org.example.dolphin', + 'provider', + rollback ? '0.2.0' : '0.1.0', + rollback ? '0.1.0' : '0.2.0', + ), + component( + 'org.example.dolphin.launch', + 'extension', + rollback ? '0.3.0' : '0.2.0', + rollback ? '0.2.0' : '0.3.0', + ), + ], + addedPermissions: rollback ? [] : ['library.write'], + removedPermissions: [], + changedPermissions: ['game.launch'], + requiresManualApproval: true, + isDowngrade: rollback, + isRollback: rollback, + }; +} + +describe('bundle inventory', () => { + beforeEach(() => { + vi.restoreAllMocks(); + openFile.mockReset(); + delete (window as Window & { __TAURI_INTERNALS__?: unknown }).__TAURI_INTERNALS__; + }); + + it('renders one row per bundle with every component status and never merges official plugins', async () => { + vi.spyOn(commands, 'pluginInventory').mockResolvedValue([official, bundle]); + renderInventory('en', 'account-one'); + + const list = await screen.findByRole('group', { name: 'Installed plugins' }); + const rows = within(list).getAllByRole('button'); + expect(rows).toHaveLength(2); + const bundleRow = within(list).getByRole('button', { name: /Dolphin GameCube and Wii/ }); + expect(bundleRow).toHaveTextContent('Bundle version: 0.2.0'); + expect(bundleRow).toHaveTextContent('Dolphin discovery: Installed'); + expect(bundleRow).toHaveTextContent('Dolphin launch: Unavailable'); + const officialRow = within(list).getByRole('button', { name: /Steam/ }); + expect(officialRow).not.toHaveTextContent('Bundle version'); + + // The bundle is one row even though it has two components; the details keep them separate. + expect(within(list).getAllByRole('button', { name: /Dolphin GameCube and Wii/ })).toHaveLength(1); + fireEvent.click(bundleRow); + const details = await screen.findByRole('article', { name: 'Bundle details' }); + expect(details).toHaveTextContent(publisher); + expect(details).toHaveTextContent('Dolphin discovery'); + expect(details).toHaveTextContent('Dolphin launch'); + expect(details).toHaveTextContent('Runtime unavailable'); + const componentItems = within(details).getByRole('list', { name: 'Bundle components' }).querySelectorAll('li'); + expect(componentItems).toHaveLength(2); + expect(within(componentItems[0] as HTMLElement).getByRole('button', { name: 'Enable' })).toBeEnabled(); + // The unavailable extension cannot be enabled, and it says why. + const extensionItem = within(componentItems[1] as HTMLElement); + expect(extensionItem.getByRole('button', { name: 'Enable' })).toBeDisabled(); + }); + + it('selects a bundle row from the keyboard', async () => { + vi.spyOn(commands, 'pluginInventory').mockResolvedValue([official, bundle]); + renderInventory('en', 'account-one'); + + const row = await screen.findByRole('button', { name: /Dolphin GameCube and Wii/ }); + row.focus(); + expect(row).toHaveFocus(); + await userEvent.setup().keyboard('{Enter}'); + expect(await screen.findByRole('article', { name: 'Bundle details' })).toBeInTheDocument(); + }); + + it('keeps activation per component in the bundle details', async () => { + let enabled = false; + vi.spyOn(commands, 'pluginInventory').mockImplementation(async () => [{ + ...bundle, + bundleComponents: bundle.bundleComponents?.map((component) => + component.pluginKind === 'provider' ? { ...component, enabled } : component), + }]); + const enable = vi.spyOn(commands, 'pluginEnable').mockImplementation(async () => { enabled = true; }); + const disable = vi.spyOn(commands, 'pluginDisable').mockImplementation(async () => { enabled = false; }); + renderInventory('en', 'account-one'); + + fireEvent.click(await screen.findByRole('button', { name: /Dolphin GameCube and Wii/ })); + const details = await screen.findByRole('article', { name: 'Bundle details' }); + const componentItems = within(details).getByRole('list', { name: 'Bundle components' }).querySelectorAll('li'); + fireEvent.click(within(componentItems[0] as HTMLElement).getByRole('button', { name: 'Enable' })); + await waitFor(() => expect(enable).toHaveBeenCalledWith('org.example.dolphin')); + const enabledItems = within(details).getByRole('list', { name: 'Bundle components' }).querySelectorAll('li'); + await waitFor(() => expect(within(enabledItems[0] as HTMLElement).getByRole('button', { name: 'Disable' })).toBeInTheDocument()); + fireEvent.click(within(enabledItems[0] as HTMLElement).getByRole('button', { name: 'Disable' })); + await waitFor(() => expect(disable).toHaveBeenCalledWith('org.example.dolphin')); + }); + + it.each([ + ['en', 'Bundle details', 'Uninstall bundle', 'Sign in to manage community plugins.'], + ['pt-BR', 'Detalhes do pacote', 'Desinstalar pacote', 'Entre na sua conta para gerenciar plugins da comunidade.'], + ])('keeps the bundle read-only while signed out in %s', async (locale, detailsLabel, uninstallLabel, signIn) => { + vi.spyOn(commands, 'pluginInventory').mockResolvedValue([bundle]); + renderInventory(locale); + + fireEvent.click(await screen.findByRole('button', { name: /Dolphin GameCube and Wii/ })); + const details = await screen.findByRole('article', { name: detailsLabel }); + expect(details).toHaveTextContent(signIn); + expect(within(details).queryByRole('button', { name: uninstallLabel })).not.toBeInTheDocument(); + expect(within(details).queryByRole('button', { name: /Ativar|Enable/ })).not.toBeInTheDocument(); + }); + + it('uninstalls the bundle once with one retention choice and refreshes the inventory', async () => { + const inventory = vi.spyOn(commands, 'pluginInventory').mockResolvedValue([bundle]); + const uninstall = vi.spyOn(commands, 'pluginBundleUninstall').mockResolvedValue({ + bundleId: 'org.example.dolphin.bundle', + removed: [ + { pluginId: 'org.example.dolphin', version: '0.1.0', stopped: true }, + { pluginId: 'org.example.dolphin.launch', version: '0.2.0', stopped: false }, + ], + failures: [], + dataRetention: 'deleted', + }); + renderInventory('en', 'account-one'); + + fireEvent.click(await screen.findByRole('button', { name: /Dolphin GameCube and Wii/ })); + fireEvent.click(within(await screen.findByRole('article', { name: 'Bundle details' })) + .getByRole('button', { name: 'Uninstall bundle' })); + const dialog = await screen.findByRole('dialog'); + fireEvent.click(within(dialog).getByRole('radio', { + name: 'Delete private data for the signed-in account', + })); + fireEvent.click(within(dialog).getByRole('button', { name: 'Uninstall bundle' })); + + await waitFor(() => expect(uninstall).toHaveBeenCalledWith('org.example.dolphin.bundle', true)); + expect(await screen.findByText(/Bundle uninstalled\. Private data was deleted\./)).toBeInTheDocument(); + await waitFor(() => expect(inventory.mock.calls.length).toBeGreaterThan(1)); + }); + + it('names every remaining component when the uninstall is only partial', async () => { + vi.spyOn(commands, 'pluginInventory').mockResolvedValue([bundle]); + vi.spyOn(commands, 'pluginBundleUninstall').mockResolvedValue({ + bundleId: 'org.example.dolphin.bundle', + removed: [{ pluginId: 'org.example.dolphin', version: '0.1.0', stopped: true }], + failures: [{ + pluginId: 'org.example.dolphin.launch', + version: '0.2.0', + error: 'remove org.example.dolphin.launch 0.2.0: permission denied', + }], + dataRetention: 'kept', + }); + renderInventory('en', 'account-one'); + + fireEvent.click(await screen.findByRole('button', { name: /Dolphin GameCube and Wii/ })); + const details = await screen.findByRole('article', { name: 'Bundle details' }); + fireEvent.click(within(details).getByRole('button', { name: 'Uninstall bundle' })); + fireEvent.click(within(await screen.findByRole('dialog')) + .getByRole('button', { name: 'Uninstall bundle' })); + + expect(await screen.findByText(/only partly uninstalled/i)).toBeInTheDocument(); + expect(screen.getByText(/org\.example\.dolphin\.launch 0\.2\.0: remove .*permission denied/)) + .toBeInTheDocument(); + expect(screen.queryByText('Could not uninstall this bundle. The last saved host state is still in effect.')) + .not.toBeInTheDocument(); + }); + + it('submits grouped permission decisions once and scopes a component error', async () => { + vi.spyOn(commands, 'pluginInventory').mockResolvedValue([bundle]); + vi.spyOn(commands, 'pluginPermissionSnapshot') + .mockImplementation(async (pluginId) => pluginId === 'org.example.dolphin' + ? permissionSnapshot(pluginId, 'storage.persist', providerScope) + : permissionSnapshot(pluginId, 'game.launch', extensionScope)); + const replace = vi.spyOn(commands, 'pluginBundlePermissionsReplace').mockResolvedValue({ + components: [ + { pluginId: 'org.example.dolphin' }, + { pluginId: 'org.example.dolphin.launch', error: 'grants changed while saving' }, + ], + }); + renderInventory('en', 'account-one'); + + fireEvent.click(await screen.findByRole('button', { name: /Dolphin GameCube and Wii/ })); + const details = await screen.findByRole('article', { name: 'Bundle details' }); + fireEvent.click(await within(details).findByRole('checkbox', { name: /api\.example\.com/ })); + fireEvent.click(within(details).getByRole('checkbox', { name: /selected-records/ })); + fireEvent.click(within(details).getByRole('button', { name: 'Save bundle permissions' })); + + await waitFor(() => expect(replace).toHaveBeenCalledTimes(1)); + const submissions = replace.mock.calls[0][0]; + expect(submissions).toHaveLength(2); + expect(submissions.map((submission) => submission.pluginId)).toEqual([ + 'org.example.dolphin', + 'org.example.dolphin.launch', + ]); + expect(submissions.every((submission) => submission.expectedRevision === 0)).toBe(true); + expect(submissions[0].decisions).toEqual([ + { permission_id: 'storage.persist', scope: providerScope, granted: true }, + ]); + // The denied/failed component is named beside its own section, not as a bundle-wide failure. + expect(await screen.findByRole('alert')).toHaveTextContent( + 'Dolphin launch: grants changed while saving', + ); + }); + + it('denies one component without touching its sibling decision', async () => { + vi.spyOn(commands, 'pluginInventory').mockResolvedValue([bundle]); + vi.spyOn(commands, 'pluginPermissionSnapshot') + .mockImplementation(async (pluginId) => pluginId === 'org.example.dolphin' + ? permissionSnapshot(pluginId, 'storage.persist', providerScope) + : permissionSnapshot(pluginId, 'game.launch', extensionScope)); + const replace = vi.spyOn(commands, 'pluginBundlePermissionsReplace').mockResolvedValue({ + components: [{ pluginId: 'org.example.dolphin' }, { pluginId: 'org.example.dolphin.launch' }], + }); + renderInventory('en', 'account-one'); + + fireEvent.click(await screen.findByRole('button', { name: /Dolphin GameCube and Wii/ })); + const details = await screen.findByRole('article', { name: 'Bundle details' }); + // Only the provider is granted; the extension stays denied on its own scope. + fireEvent.click(await within(details).findByRole('checkbox', { name: /api\.example\.com/ })); + fireEvent.click(within(details).getByRole('button', { name: 'Save bundle permissions' })); + + await waitFor(() => expect(replace).toHaveBeenCalledTimes(1)); + const submissions = replace.mock.calls[0][0]; + expect(submissions[0].decisions).toEqual([ + { permission_id: 'storage.persist', scope: providerScope, granted: true }, + ]); + expect(submissions[1].decisions).toEqual([ + { permission_id: 'game.launch', scope: extensionScope, granted: false }, + ]); + expect(screen.queryByRole('alert')).not.toBeInTheDocument(); + }); + + it('reviews a bundle with localized labels in pt-BR', async () => { + vi.spyOn(commands, 'pluginInventory').mockResolvedValue([official]); + vi.spyOn(commands, 'pluginBundleImportReview').mockResolvedValue(bundleReview()); + renderInventory('pt-BR', 'account-one'); + + const path = await screen.findByRole('textbox', { name: 'Caminho do bundle assinado' }); + fireEvent.change(path, { target: { value: '/pacotes/dolphin.gnbundle' } }); + await userEvent.setup().type(path, '{Enter}'); + + const article = await screen.findByRole('article', { name: 'Revisar pacote de plugins' }); + expect(article).toHaveTextContent('Identificador do pacote: org.example.dolphin.bundle'); + expect(article).toHaveTextContent('Permissões solicitadas'); + expect(article).toHaveTextContent('Plataformas: GameCube, Wii'); + expect(article).toHaveTextContent('Persistir dados do plugin'); + expect(article).toHaveTextContent('Aceitar, instalar e ativar'); + expect(article).toHaveTextContent('Confiar neste publicador'); + }); + + it('opens the native file picker and fills the signed package path', async () => { + vi.spyOn(commands, 'pluginInventory').mockResolvedValue([official]); + openFile.mockResolvedValue('/tmp/dolphin-emu-0.1.0-linux-x64.gnbundle'); + (window as Window & { __TAURI_INTERNALS__?: unknown }).__TAURI_INTERNALS__ = {}; + + renderInventory('en', 'account-one'); + fireEvent.click(await screen.findByRole('button', { name: 'Choose file…' })); + + await waitFor(() => expect(openFile).toHaveBeenCalledWith({ + multiple: false, + directory: false, + title: 'Choose a signed plugin bundle', + filters: [ + { name: 'Signed plugin bundles', extensions: ['gnbundle'] }, + { name: 'Individual plugin packages', extensions: ['gnplugin'] }, + { name: 'Signed plugin bundles and individual packages', extensions: ['gnbundle', 'gnplugin'] }, + ], + })); + const input = screen.getByRole('textbox', { name: 'Path to signed bundle' }); + await waitFor(() => expect(input).toHaveValue('/tmp/dolphin-emu-0.1.0-linux-x64.gnbundle')); + }); + + it('reviews a bundle with per-component permissions and compatibility behind one fingerprint', async () => { + vi.spyOn(commands, 'pluginInventory').mockResolvedValue([official]); + const review = vi.spyOn(commands, 'pluginBundleImportReview').mockResolvedValue(bundleReview()); + const confirm = vi.spyOn(commands, 'pluginBundleImportConfirmPublisher') + .mockResolvedValue(bundleReview('trusted')); + renderInventory('en', 'account-one'); + + const path = await screen.findByRole('textbox', { name: 'Path to signed bundle' }); + fireEvent.change(path, { target: { value: '/packages/dolphin.gnbundle' } }); + await userEvent.setup().type(path, '{Enter}'); + + const article = await screen.findByRole('article', { name: 'Review plugin bundle' }); + expect(review).toHaveBeenCalledWith('/packages/dolphin.gnbundle'); + expect(article).toHaveTextContent('Dolphin GameCube and Wii 0.2.0'); + expect(article).toHaveTextContent(publisher); + expect(article).toHaveTextContent('Persist plugin data'); + expect(article).toHaveTextContent('Own provider'); + expect(article).toHaveTextContent('Optional'); + expect(article).toHaveTextContent('Keep the local catalog.'); + expect(article).toHaveTextContent('Launch games'); + expect(article).toHaveTextContent('Approved game session'); + expect(article).toHaveTextContent('Platforms: GameCube, Wii'); + expect(article).toHaveTextContent('Unavailable on this system'); + expect(article).toHaveTextContent('No package target matches this system'); + expect(article).toHaveTextContent('Incompatible'); + expect(within(article).getByRole('button', { name: 'Accept, install and enable' })).toBeDisabled(); + + fireEvent.click(within(article).getByRole('button', { name: 'Trust this publisher' })); + await waitFor(() => expect(confirm).toHaveBeenCalledWith('bundle-token', publisher)); + expect(await screen.findByText(/Bundle publisher confirmed/)).toBeInTheDocument(); + }); + + it('installs an approved bundle from the review and refreshes the inventory', async () => { + const inventory = vi.spyOn(commands, 'pluginInventory').mockResolvedValue([official]); + vi.spyOn(commands, 'pluginBundleImportReview').mockResolvedValue(bundleReview()); + vi.spyOn(commands, 'pluginBundleImportConfirmPublisher').mockResolvedValue(bundleReview('trusted')); + const install = vi.spyOn(commands, 'pluginBundleImportInstall').mockResolvedValue({ + bundleId: 'org.example.dolphin.bundle', + components: [ + { + pluginId: 'org.example.dolphin', kind: 'provider', version: '0.1.0', active: true, + activated: true, + }, + { + pluginId: 'org.example.dolphin.launch', kind: 'extension', version: '0.2.0', active: false, + activated: false, + }, + ], + }); + renderInventory('en', 'account-one'); + + const path = await screen.findByRole('textbox', { name: 'Path to signed bundle' }); + fireEvent.change(path, { target: { value: '/packages/dolphin.gnbundle' } }); + await userEvent.setup().type(path, '{Enter}'); + const article = await screen.findByRole('article', { name: 'Review plugin bundle' }); + fireEvent.click(within(article).getByRole('button', { name: 'Trust this publisher' })); + + const consent = await within(article).findByRole('checkbox'); + fireEvent.click(consent); + fireEvent.click(within(article).getByRole('button', { name: 'Accept, install and enable' })); + + await waitFor(() => expect(install).toHaveBeenCalledWith('bundle-token', true, [ + { pluginId: 'org.example.dolphin', deniedPermissionIds: [] }, + { pluginId: 'org.example.dolphin.launch', deniedPermissionIds: [] }, + ])); + expect(screen.queryByRole('article', { name: 'Review plugin bundle' })).not.toBeInTheDocument(); + await waitFor(() => expect(inventory.mock.calls.length).toBeGreaterThan(1)); + }); + + it('collects denied optional permissions per bundle component', async () => { + vi.spyOn(commands, 'pluginInventory').mockResolvedValue([official]); + vi.spyOn(commands, 'pluginBundleImportReview').mockResolvedValue(bundleReview('trusted')); + const install = vi.spyOn(commands, 'pluginBundleImportInstall').mockResolvedValue({ + bundleId: 'org.example.dolphin.bundle', + components: [], + }); + renderInventory('en', 'account-one'); + + const path = await screen.findByRole('textbox', { name: 'Path to signed bundle' }); + fireEvent.change(path, { target: { value: '/packages/dolphin.gnbundle' } }); + await userEvent.setup().type(path, '{Enter}'); + const article = await screen.findByRole('article', { name: 'Review plugin bundle' }); + + const persist = within(article).getByRole('switch', { name: 'Allow Persist plugin data' }); + expect(persist).toBeChecked(); + fireEvent.click(persist); + expect(await within(article).findByText('The local catalog is rebuilt on every start.')).toBeInTheDocument(); + + fireEvent.click(within(article).getByRole('checkbox', { name: /reviewed the declared native access/i })); + fireEvent.click(within(article).getByRole('button', { name: 'Accept, install and enable' })); + + await waitFor(() => expect(install).toHaveBeenCalledWith('bundle-token', true, [ + { pluginId: 'org.example.dolphin', deniedPermissionIds: ['storage.persist'] }, + { pluginId: 'org.example.dolphin.launch', deniedPermissionIds: [] }, + ])); + }); + + it('reviews and applies one bundle update with per-component old and new versions', async () => { + vi.spyOn(commands, 'pluginInventory').mockResolvedValue([bundle]); + vi.spyOn(commands, 'pluginBundleUpdateAvailable').mockResolvedValue([{ + bundleId: 'org.example.dolphin.bundle', + name: 'Dolphin GameCube and Wii', + installedVersion: '0.2.0', + versions: ['0.3.0'], + }]); + vi.spyOn(commands, 'pluginBundleRollbackAvailable').mockResolvedValue([]); + const check = vi.spyOn(commands, 'pluginBundleUpdateCheck').mockResolvedValue([{ + bundleId: 'org.example.dolphin.bundle', + name: 'Dolphin GameCube and Wii', + installedVersion: '0.2.0', + versions: ['0.3.0'], + }]); + const review = vi.spyOn(commands, 'pluginBundleUpdateReview') + .mockResolvedValue(bundleUpdateReviewFixture()); + const approve = vi.spyOn(commands, 'pluginBundleUpdateApprove').mockResolvedValue({ + bundleId: 'org.example.dolphin.bundle', + previousVersion: '0.2.0', + version: '0.3.0', + components: [ + { pluginId: 'org.example.dolphin', kind: 'provider', previousVersion: '0.1.0', version: '0.2.0', active: true }, + { pluginId: 'org.example.dolphin.launch', kind: 'extension', previousVersion: '0.2.0', version: '0.3.0', active: true }, + ], + }); + renderInventory('en', 'account-one'); + + fireEvent.click(await screen.findByRole('button', { name: /Dolphin GameCube and Wii/ })); + const details = await screen.findByRole('article', { name: 'Bundle details' }); + const updates = within(details).getByRole('region', { name: 'Bundle updates and rollback' }); + fireEvent.click(within(updates).getByRole('button', { name: 'Check for bundle updates' })); + await waitFor(() => expect(check).toHaveBeenCalledTimes(1)); + + fireEvent.click(await within(updates).findByRole('button', { name: 'Review bundle 0.3.0' })); + await waitFor(() => expect(review).toHaveBeenCalledWith('org.example.dolphin.bundle', '0.3.0')); + const reviewPanel = await within(updates).findByRole('article', { name: 'Bundle update review' }); + expect(reviewPanel).toHaveTextContent('Dolphin GameCube and Wii: 0.2.0 → 0.3.0'); + expect(reviewPanel).toHaveTextContent('0.1.0 → 0.2.0'); + expect(reviewPanel).toHaveTextContent('0.2.0 → 0.3.0'); + expect(reviewPanel).toHaveTextContent('game.launch: approved-game-session → selected-game-session'); + expect(reviewPanel).toHaveTextContent('Signed bundle hash'); + + fireEvent.click(within(reviewPanel).getByRole('button', { name: 'Update every component' })); + await waitFor(() => expect(approve).toHaveBeenCalledWith('org.example.dolphin.bundle', '0.3.0')); + expect(await within(updates).findByText('Bundle updated to 0.3.0.')).toBeInTheDocument(); + }); + + it('keeps unrelated bundle controls usable during a slow update and restores the saved state on failure', async () => { + vi.spyOn(commands, 'pluginInventory').mockResolvedValue([bundle]); + vi.spyOn(commands, 'pluginBundleUpdateAvailable').mockResolvedValue([{ + bundleId: 'org.example.dolphin.bundle', + name: 'Dolphin GameCube and Wii', + installedVersion: '0.2.0', + versions: ['0.3.0'], + }]); + vi.spyOn(commands, 'pluginBundleRollbackAvailable').mockResolvedValue([]); + vi.spyOn(commands, 'pluginBundleUpdateReview').mockResolvedValue(bundleUpdateReviewFixture()); + let rejectApprove!: (error: Error) => void; + const pendingApprove = new Promise((_, reject) => { + rejectApprove = reject; + }); + const approve = vi.spyOn(commands, 'pluginBundleUpdateApprove') + .mockReturnValue(pendingApprove); + renderInventory('en', 'account-one'); + + fireEvent.click(await screen.findByRole('button', { name: /Dolphin GameCube and Wii/ })); + const details = await screen.findByRole('article', { name: 'Bundle details' }); + const updates = within(details).getByRole('region', { name: 'Bundle updates and rollback' }); + fireEvent.click(await within(updates).findByRole('button', { name: 'Review bundle 0.3.0' })); + const reviewPanel = await within(updates).findByRole('article', { name: 'Bundle update review' }); + fireEvent.click(within(reviewPanel).getByRole('button', { name: 'Update every component' })); + await waitFor(() => expect(approve).toHaveBeenCalledTimes(1)); + + // The pending update only disables its own controls: per-component activation stays usable. + const componentItems = within(details) + .getAllByRole('list', { name: 'Bundle components' })[0] + .querySelectorAll('li'); + expect(within(componentItems[0] as HTMLElement).getByRole('button', { name: 'Enable' })).toBeEnabled(); + expect(within(reviewPanel).getByRole('button', { name: 'Update every component' })).toBeDisabled(); + + rejectApprove(new Error('persistence failed')); + expect(await within(updates).findByText( + 'The bundle change could not be saved. The last saved host state is still in effect.', + )).toBeInTheDocument(); + expect(details).toHaveTextContent('Bundle version: 0.2.0'); + expect(within(reviewPanel).getByRole('button', { name: 'Update every component' })).toBeEnabled(); + }); + + it('localizes a failed bundle update review in pt-BR', async () => { + vi.spyOn(commands, 'pluginInventory').mockResolvedValue([bundle]); + vi.spyOn(commands, 'pluginBundleUpdateAvailable').mockResolvedValue([{ + bundleId: 'org.example.dolphin.bundle', + name: 'Dolphin GameCube and Wii', + installedVersion: '0.2.0', + versions: ['0.3.0'], + }]); + vi.spyOn(commands, 'pluginBundleRollbackAvailable').mockResolvedValue([]); + vi.spyOn(commands, 'pluginBundleUpdateReview').mockRejectedValue(new Error('hash mismatch')); + renderInventory('pt-BR', 'account-one'); + + fireEvent.click(await screen.findByRole('button', { name: /Dolphin GameCube and Wii/ })); + const details = await screen.findByRole('article', { name: 'Detalhes do pacote' }); + const updates = within(details).getByRole('region', { name: 'Atualizações e reversão do pacote' }); + fireEvent.click(await within(updates).findByRole('button', { name: 'Revisar pacote 0.3.0' })); + + expect(await within(updates).findByText( + 'Não foi possível revisar esta versão do pacote. Nada foi instalado.', + )).toBeInTheDocument(); + }); + + it('reviews and confirms one bundle rollback', async () => { + vi.spyOn(commands, 'pluginInventory').mockResolvedValue([bundle]); + vi.spyOn(commands, 'pluginBundleUpdateAvailable').mockResolvedValue([]); + vi.spyOn(commands, 'pluginBundleRollbackAvailable').mockResolvedValue([{ + bundleId: 'org.example.dolphin.bundle', + name: 'Dolphin GameCube and Wii', + activeVersion: '0.3.0', + versions: ['0.2.0'], + }]); + vi.spyOn(commands, 'pluginBundleRollbackReview') + .mockResolvedValue(bundleUpdateReviewFixture(true)); + const approve = vi.spyOn(commands, 'pluginBundleRollbackApprove').mockResolvedValue({ + bundleId: 'org.example.dolphin.bundle', + previousVersion: '0.3.0', + version: '0.2.0', + components: [], + }); + renderInventory('en', 'account-one'); + + fireEvent.click(await screen.findByRole('button', { name: /Dolphin GameCube and Wii/ })); + const details = await screen.findByRole('article', { name: 'Bundle details' }); + const updates = within(details).getByRole('region', { name: 'Bundle updates and rollback' }); + fireEvent.click(await within(updates).findByRole('button', { name: 'Review rollback to 0.2.0' })); + const reviewPanel = await within(updates).findByRole('article', { name: 'Bundle rollback review' }); + const confirm = within(reviewPanel).getByRole('checkbox'); + const action = within(reviewPanel).getByRole('button', { name: 'Roll back every component' }); + expect(action).toBeDisabled(); + fireEvent.click(confirm); + fireEvent.click(action); + + await waitFor(() => expect(approve).toHaveBeenCalledWith( + 'org.example.dolphin.bundle', + '0.2.0', + true, + )); + expect(await within(updates).findByText('Bundle rolled back to 0.2.0.')).toBeInTheDocument(); + }); + + it('keeps the bundle review signed out and disables the publisher decision', async () => { + vi.spyOn(commands, 'pluginInventory').mockResolvedValue([official]); + const review = vi.spyOn(commands, 'pluginBundleImportReview').mockResolvedValue(bundleReview()); + renderInventory('en'); + + const button = await screen.findByRole('button', { name: 'Review package' }); + expect(button).toBeDisabled(); + expect(screen.getByText('Sign in to manage community plugins.')).toBeInTheDocument(); + expect(review).not.toHaveBeenCalled(); + }); + it('reports a compatible component that stayed installed but was not activated', async () => { + vi.spyOn(commands, 'pluginInventory').mockResolvedValue([official]); + vi.spyOn(commands, 'pluginBundleImportReview').mockResolvedValue(bundleReview('trusted')); + vi.spyOn(commands, 'pluginBundleImportInstall').mockResolvedValue({ + bundleId: 'org.example.dolphin.bundle', + components: [ + { + pluginId: 'org.example.dolphin', kind: 'provider', version: '0.1.0', active: true, + activated: false, activationError: 'activation failed: plugin did not establish its command session', + }, + ], + }); + renderInventory('en', 'account-one'); + + const path = await screen.findByRole('textbox', { name: 'Path to signed bundle' }); + fireEvent.change(path, { target: { value: '/packages/dolphin.gnbundle' } }); + await userEvent.setup().type(path, '{Enter}'); + const article = await screen.findByRole('article', { name: 'Review plugin bundle' }); + fireEvent.click(within(article).getByRole('checkbox', { name: /reviewed the declared native access/i })); + fireEvent.click(within(article).getByRole('button', { name: 'Accept, install and enable' })); + + const alert = await screen.findByRole('alert'); + expect(alert).toHaveTextContent('Installed, but not activated'); + expect(alert).toHaveTextContent('org.example.dolphin'); + expect(alert).toHaveTextContent('plugin did not establish its command session'); + }); + + it('removes playtime rows immediately after uninstalling the bundle', async () => { + vi.spyOn(commands, 'pluginInventory').mockResolvedValue([bundle]); + vi.spyOn(commands, 'pluginBundleUninstall').mockResolvedValue({ + bundleId: 'org.example.dolphin.bundle', + removed: [ + { pluginId: 'org.example.dolphin', version: '0.1.0', stopped: true }, + { pluginId: 'org.example.dolphin.launch', version: '0.2.0', stopped: false }, + ], + failures: [], + dataRetention: 'kept', + }); + vi.spyOn(commands, 'pluginPlaytimeInventory') + .mockResolvedValueOnce([{ + pluginId: 'org.example.dolphin', + name: 'Dolphin discovery', + version: '0.1.0', + playtime: { + identifiesGameplay: true, + identifiesPauses: true, + withoutPauseDetection: 'disabled', + }, + accountingEnabled: true, + }]) + .mockResolvedValue([]); + renderInventory('en', 'account-one'); + + expect(await screen.findByRole('article', { name: 'Dolphin discovery' })).toBeInTheDocument(); + fireEvent.click(await screen.findByRole('button', { name: /Dolphin GameCube and Wii/ })); + fireEvent.click(within(await screen.findByRole('article', { name: 'Bundle details' })) + .getByRole('button', { name: 'Uninstall bundle' })); + fireEvent.click(within(await screen.findByRole('dialog')) + .getByRole('button', { name: 'Uninstall bundle' })); + + await waitFor(() => expect(screen.queryByRole('article', { name: 'Dolphin discovery' })).not.toBeInTheDocument()); + expect(screen.getByText('No active trusted third-party plugins declare playtime support.')).toBeInTheDocument(); + }); + + it('renders folder and program approvals for each bundle component with the component ids', async () => { + vi.spyOn(commands, 'pluginInventory').mockResolvedValue([bundle]); + const folders = vi.spyOn(commands, 'pluginFolderApprovals').mockResolvedValue([]); + const runtimes = vi.spyOn(commands, 'pluginRuntimeApprovals').mockResolvedValue([]); + renderInventory('en', 'account-one'); + + fireEvent.click(await screen.findByRole('button', { name: /Dolphin GameCube and Wii/ })); + const discovery = await screen.findByRole('region', { name: 'Approvals for Dolphin discovery' }); + const launch = await screen.findByRole('region', { name: 'Approvals for Dolphin launch' }); + expect(within(discovery).getByRole('region', { name: 'Folder access and library roots' })).toBeInTheDocument(); + expect(within(discovery).getByRole('region', { name: 'Approved runtime programs' })).toBeInTheDocument(); + expect(within(launch).getByRole('region', { name: 'Folder access and library roots' })).toBeInTheDocument(); + expect(within(launch).getByRole('region', { name: 'Approved runtime programs' })).toBeInTheDocument(); + + await waitFor(() => expect(folders).toHaveBeenCalledWith('org.example.dolphin', publisher)); + expect(folders).toHaveBeenCalledWith('org.example.dolphin.launch', publisher); + expect(runtimes).toHaveBeenCalledWith('org.example.dolphin', publisher); + expect(runtimes).toHaveBeenCalledWith('org.example.dolphin.launch', publisher); + // A bundle has no namespace of its own, so no bundle-level approvals are requested. + expect(folders).not.toHaveBeenCalledWith('org.example.dolphin.bundle', publisher); + expect(runtimes).not.toHaveBeenCalledWith('org.example.dolphin.bundle', publisher); + }); + +}); diff --git a/ui/src/features/settings/PluginInventory.test.tsx b/ui/src/features/settings/PluginInventory.test.tsx index 059c3198c..b92de28ab 100644 --- a/ui/src/features/settings/PluginInventory.test.tsx +++ b/ui/src/features/settings/PluginInventory.test.tsx @@ -1,341 +1,1084 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { fireEvent, render, screen, waitFor, within } from '@testing-library/react'; +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; import { MantineProvider } from '@mantine/core'; -import { QueryClientProvider } from '@tanstack/react-query'; -import { appTheme, createAppQueryClient } from '../../AppProviders'; +import { appTheme } from '../../AppProviders'; import { - SNAPSHOT_QUERY_KEY, commands, createDefaultSnapshot, + SNAPSHOT_QUERY_KEY, + type AvailablePluginUpdate, + type PluginConfigurationState, type PluginInfo, - type StoreAccountView, + type PluginPermissionSnapshot, + type PluginSharedDataSnapshot, } from '../../api'; +import { cleanup } from '@testing-library/react'; +import { selectPluginConfiguration } from '../../api/pluginSettings'; import { I18nProvider } from '../../i18n'; -import { - openSettingsModal, - resetUiStore, - uiStore, -} from '../../store/uiStore'; -import { ToastContainer } from './ToastContainer'; -import { PluginsPanel } from './panels/PluginsPanel'; - -const steam: PluginInfo = { +import { PluginInventory } from './PluginInventory'; +import { pluginQueryKeys } from '../../api/pluginQueryKeys'; + +const { listenMock } = vi.hoisted(() => ({ listenMock: vi.fn() })); +vi.mock('@tauri-apps/api/event', () => ({ listen: listenMock })); + +const plugin: PluginInfo = { providerId: 'steam', pluginId: 'org.gamenode.plugin.steam-discovery', + pluginKind: 'provider', name: 'Steam', - version: '1.4.2', source: 'official', status: 'installed', capabilities: ['library.discovery', 'auth.webview', 'secrets.read'], session: 'active', - nativeAccess: ['network', 'files', 'process', 'registry'], + nativeAccess: ['files', 'network'], }; -const epic: PluginInfo = { - providerId: 'epic', - pluginId: 'org.gamenode.plugin.epic-discovery', - name: 'Epic Games Store', - version: '2.0.1', - source: 'official', - status: 'installed', - capabilities: ['library.discovery', 'account.state.read'], - session: 'active', - nativeAccess: ['network', 'files'], -}; +function renderInventory(locale = 'en', profileId?: string, seed?: (client: QueryClient) => void) { + const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + if (profileId) { + client.setQueryData(SNAPSHOT_QUERY_KEY, { + ...createDefaultSnapshot(), + auth: { signedIn: { user: { id: profileId } } }, + }); + } + seed?.(client); + const view = render( + + + + + + + , + ); + return { ...view, client }; +} -const community: PluginInfo = { - providerId: 'community', - pluginId: 'dev.prateleira.local', - name: 'Prateleira Local', - version: '0.3.1', - source: 'community', - status: 'installed', - capabilities: ['provider.context.read'], - session: 'stopped', - nativeAccess: ['files', 'dbus'], -}; +describe('PluginInventory', () => { + beforeEach(() => { + vi.restoreAllMocks(); + listenMock.mockReset(); + delete (window as Window & { __TAURI_INTERNALS__?: unknown }).__TAURI_INTERNALS__; + }); -function storeAccount( - provider: string, - state: StoreAccountView['state'], -): StoreAccountView { - return { - provider, - state, - accountId: null, - accountName: null, - ownedCount: 0, - sharedCount: 0, - sharedLabel: null, - installedCount: 0, - lastCheckedAt: null, - lastSyncedAt: null, - storage: null, - persistFailed: false, - catalogError: null, - sharedError: null, - canSignIn: true, - canCancelSignIn: false, - canFocusSignIn: false, - canSignOut: true, - canCheck: true, - canRemoveCredential: true, - }; -} + it('discloses the signed playtime warning in Portuguese and persists the per-plugin setting', async () => { + const declared = { + pluginId: 'org.example.emulator', + name: 'Emulador', + version: '1.0.0', + playtime: { identifiesGameplay: true, identifiesPauses: false, withoutPauseDetection: 'application_open' as const }, + accountingEnabled: true, + }; + const inventory = vi.spyOn(commands, 'pluginPlaytimeInventory') + .mockResolvedValueOnce([declared]) + .mockResolvedValueOnce([{ ...declared, accountingEnabled: false }]); + const save = vi.spyOn(commands, 'pluginPlaytimeSetAccounting').mockResolvedValue(undefined); -function renderPlugins( - _plugins: PluginInfo[], - options: { - locale?: string; - storeAccounts?: StoreAccountView[]; - } = {}, -) { - resetUiStore(); - openSettingsModal('plugins'); - const queryClient = createAppQueryClient(); - queryClient.setQueryData(SNAPSHOT_QUERY_KEY, { - ...createDefaultSnapshot(), - storeAccounts: options.storeAccounts ?? [], - }); - return { - queryClient, - ...render( - - - - - - - - , - ), - }; -} + renderInventory('pt-BR'); -describe('PluginsPanel', () => { - beforeEach(() => { + const card = await screen.findByRole('article', { name: 'Emulador' }); + expect(within(card).getByText('Identifica o conteúdo do jogo: Sim')).toBeInTheDocument(); + expect(within(card).getByRole('note')).toHaveTextContent( + 'Este plugin não consegue distinguir pausas. O tempo com o aplicativo aberto pode ser contabilizado como tempo de jogo.', + ); + expect(screen.getByText(/Desativar a contabilização preserva o histórico/)).toBeInTheDocument(); + expect(screen.getByText(/não altera permissões de descoberta ou lançamento/)).toBeInTheDocument(); + + const accounting = within(card).getByRole('checkbox', { name: 'Permitir que este plugin contabilize tempo de jogo' }); + expect(accounting).toBeChecked(); + fireEvent.click(accounting); + await waitFor(() => expect(save).toHaveBeenCalledWith('org.example.emulator', false)); + await waitFor(() => expect(accounting).not.toBeChecked()); + expect(inventory).toHaveBeenCalledTimes(2); + }); + + it('loads a fresh data review when the publisher changes and binds the save to that publisher', async () => { + const oldFingerprint = `SHA256:${'a'.repeat(64)}`; + const newFingerprint = `SHA256:${'b'.repeat(64)}`; + const managed: PluginInfo = { + ...plugin, source: 'community', publisherFingerprint: oldFingerprint, + }; + const review = { + pluginId: managed.pluginId, profileId: 'a', policyRevision: 0, + publisherFingerprint: oldFingerprint, + commonCategories: ['gamePaths' as const], selectedRecordIds: [], catalog: [], sourcePolicies: [], + }; + vi.spyOn(commands, 'pluginInventory').mockResolvedValue([managed]); + vi.spyOn(commands, 'pluginSharedDataSnapshot') + .mockResolvedValueOnce(review) + .mockResolvedValue({ ...review, publisherFingerprint: newFingerprint, commonCategories: [] }); + const save = vi.spyOn(commands, 'pluginSharedDataReplace') + .mockResolvedValue({ ...review, publisherFingerprint: newFingerprint }); + + const { client } = renderInventory('en', 'a'); + fireEvent.click(await screen.findByRole('button', { name: 'Review data access' })); + expect(await screen.findByRole('switch', { name: 'Game paths' })).toBeChecked(); + act(() => { + client.setQueryData(pluginQueryKeys.inventory, [{ ...managed, publisherFingerprint: newFingerprint }]); + }); + await waitFor(() => expect(screen.getByRole('switch', { name: 'Game paths' })).not.toBeChecked()); + fireEvent.click(screen.getByRole('switch', { name: 'Game paths' })); + fireEvent.click(screen.getByRole('button', { name: 'Save data permissions' })); + await waitFor(() => expect(save).toHaveBeenCalledWith(managed.pluginId, { + profileId: 'a', expectedPublisherFingerprint: newFingerprint, expectedRevision: 0, + commonCategories: ['gamePaths'], selectedRecordIds: [], sourcePolicies: [], + })); + }); + + it('keeps a completed save in the reviewed publisher cache after inventory changes', async () => { + const oldFingerprint = `SHA256:${'a'.repeat(64)}`; + const newFingerprint = `SHA256:${'b'.repeat(64)}`; + const managed: PluginInfo = { + ...plugin, source: 'community', publisherFingerprint: oldFingerprint, + }; + const review: PluginSharedDataSnapshot = { + pluginId: managed.pluginId, profileId: 'a', policyRevision: 0, + publisherFingerprint: oldFingerprint, + commonCategories: [], selectedRecordIds: [], catalog: [], sourcePolicies: [], + }; + const newReview = { ...review, publisherFingerprint: newFingerprint }; + vi.spyOn(commands, 'pluginInventory').mockResolvedValue([managed]); + vi.spyOn(commands, 'pluginSharedDataSnapshot') + .mockResolvedValueOnce(review) + .mockResolvedValue(newReview); + let finishSave!: (snapshot: PluginSharedDataSnapshot) => void; + const pendingSave = new Promise((resolve) => { finishSave = resolve; }); + const save = vi.spyOn(commands, 'pluginSharedDataReplace').mockReturnValue(pendingSave); + const { client } = renderInventory('en', 'a'); + + fireEvent.click(await screen.findByRole('button', { name: 'Review data access' })); + fireEvent.click(await screen.findByRole('switch', { name: 'Game paths' })); + fireEvent.click(screen.getByRole('button', { name: 'Save data permissions' })); + expect(save).toHaveBeenCalledOnce(); + + const oldKey = pluginQueryKeys.sharedData(managed.pluginId, 'a', oldFingerprint); + const newKey = pluginQueryKeys.sharedData(managed.pluginId, 'a', newFingerprint); + act(() => { + client.setQueryData(pluginQueryKeys.inventory, [{ ...managed, publisherFingerprint: newFingerprint }]); + }); + await waitFor(() => expect(client.getQueryData(newKey)).toEqual(newReview)); + + const saved: PluginSharedDataSnapshot = { ...review, policyRevision: 1, commonCategories: ['gamePaths'] }; + await act(async () => { finishSave(saved); }); + expect(client.getQueryData(oldKey)).toEqual(saved); + expect(client.getQueryData(newKey)).toEqual(newReview); + expect(screen.getByRole('switch', { name: 'Game paths' })).not.toBeChecked(); + }); + + it.each([ + ['external-only', { externalDeclared: true, externalAuthorized: true, declarativeDeclared: false, declarativeAuthorized: false }, 'external'], + ['form-only', { externalDeclared: false, externalAuthorized: false, declarativeDeclared: true, declarativeAuthorized: true }, 'form'], + ['both', { externalDeclared: true, externalAuthorized: true, declarativeDeclared: true, declarativeAuthorized: true }, 'external'], + ['denied', { externalDeclared: true, externalAuthorized: false, declarativeDeclared: true, declarativeAuthorized: false }, 'denied'], + ['absent', { externalDeclared: false, externalAuthorized: false, declarativeDeclared: false, declarativeAuthorized: false }, 'absent'], + ] as const)('selects authorized configuration mode for %s', (_name, modes, expected) => { + expect(selectPluginConfiguration(modes)).toBe(expected); + }); + + it('prefers the authorized external window when a form is also available', async () => { + vi.spyOn(commands, 'pluginInventory').mockResolvedValue([plugin]); + vi.spyOn(commands, 'pluginConfigurationModes').mockResolvedValue({ + externalDeclared: true, externalAuthorized: true, + declarativeDeclared: true, declarativeAuthorized: true, + }); + const describe = vi.spyOn(commands, 'pluginSettingsDescribe'); + renderInventory(); + expect(await screen.findByRole('button', { name: 'Configure' })).toBeInTheDocument(); + expect(describe).not.toHaveBeenCalled(); + }); + + it('routes Configure to open, then focus, while plugin settings navigation stays usable', async () => { + const secondPlugin: PluginInfo = { ...plugin, providerId: 'second-provider', pluginId: 'org.example.second', name: 'Second plugin' }; + vi.spyOn(commands, 'pluginInventory').mockResolvedValue([plugin, secondPlugin]); + vi.spyOn(commands, 'pluginConfigurationModes').mockResolvedValue({ + externalDeclared: true, externalAuthorized: true, + declarativeDeclared: true, declarativeAuthorized: true, + }); + const configure = vi.spyOn(commands, 'pluginConfigurationOpen') + .mockResolvedValueOnce({ status: 'open', windowId: 'window-1', message: null }) + .mockResolvedValueOnce({ status: 'focused', windowId: 'window-1', message: null }); + renderInventory(); + + fireEvent.click(await screen.findByRole('button', { name: 'Configure' })); + await waitFor(() => expect(configure).toHaveBeenCalledWith(plugin.providerId, false)); + expect(await screen.findByText('Configuration window opened.')).toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: 'Configure' })); + await waitFor(() => expect(configure).toHaveBeenLastCalledWith(plugin.providerId, true)); + expect(await screen.findByText('Configuration window focused.')).toBeInTheDocument(); + + fireEvent.click(within(await screen.findByRole('group', { name: 'Installed plugins' })).getByRole('button', { name: /Second plugin/ })); + expect(screen.getByRole('article', { name: 'Plugin details' })).toHaveTextContent('org.example.second'); + }); + + it('shows timeout feedback from the external configuration lifecycle', async () => { + vi.spyOn(commands, 'pluginInventory').mockResolvedValue([plugin]); + vi.spyOn(commands, 'pluginConfigurationModes').mockResolvedValue({ + externalDeclared: true, externalAuthorized: true, + declarativeDeclared: false, declarativeAuthorized: false, + }); + vi.spyOn(commands, 'pluginConfigurationOpen').mockResolvedValue({ status: 'timedOut', windowId: null, message: 'timeout' }); + renderInventory(); + fireEvent.click(await screen.findByRole('button', { name: 'Configure' })); + expect(await screen.findByText('The configuration request timed out. Try again.')).toBeInTheDocument(); + }); + + it('keeps plugin navigation usable while a durable usage read is slow', async () => { + const fingerprint = `SHA256:${'c'.repeat(64)}`; + const first: PluginInfo = { ...plugin, publisherFingerprint: fingerprint }; + const second: PluginInfo = { + ...plugin, + providerId: 'second-provider', + pluginId: 'org.example.second', + name: 'Second plugin', + publisherFingerprint: fingerprint, + }; + vi.spyOn(commands, 'pluginInventory').mockResolvedValue([first, second]); + vi.spyOn(commands, 'pluginPermissionSnapshot').mockImplementation(async (pluginId: string) => ({ + pluginId, + publisherFingerprint: fingerprint, + profileId: 'a', + grantRevision: 0, + requestedPermissions: [], + effectiveGrants: [], + })); + vi.spyOn(commands, 'pluginSharedDataSnapshot').mockImplementation(async (pluginId: string) => ({ + pluginId, + publisherFingerprint: fingerprint, + profileId: 'a', + policyRevision: 0, + commonCategories: [], + selectedRecordIds: [], + catalog: [], + sourcePolicies: [], + })); + vi.spyOn(commands, 'pluginConfigurationState').mockImplementation(async (pluginId: string) => ({ + pluginId, available: false, revision: null, + })); + vi.spyOn(commands, 'pluginConfigurationModes').mockResolvedValue({ + externalDeclared: false, externalAuthorized: false, + declarativeDeclared: false, declarativeAuthorized: false, + }); + vi.spyOn(commands, 'pluginDurableUsage').mockReturnValue(new Promise(() => undefined)); + + renderInventory('en', 'a'); + expect(await screen.findByText('Reading retained shared data…')).toBeInTheDocument(); + + fireEvent.click(within(await screen.findByRole('group', { name: 'Installed plugins' })).getByRole('button', { name: /Second plugin/ })); + expect(screen.getByRole('article', { name: 'Plugin details' })).toHaveTextContent('org.example.second'); + expect(screen.getByText('Reading retained shared data…')).toBeInTheDocument(); + }); + + it('reports disabled and unavailable modes without issuing Configure requests', async () => { + const disabledConfigure = vi.spyOn(commands, 'pluginConfigurationOpen'); + const disabledModes = vi.spyOn(commands, 'pluginConfigurationModes'); + vi.spyOn(commands, 'pluginInventory').mockResolvedValue([{ ...plugin, status: 'missing', session: 'stopped' }]); + renderInventory(); + expect(await screen.findByText(/unavailable while this plugin is disabled or stopped/i)).toBeInTheDocument(); + expect(disabledModes).not.toHaveBeenCalled(); + expect(disabledConfigure).not.toHaveBeenCalled(); + + cleanup(); vi.restoreAllMocks(); - resetUiStore(); + const unavailableConfigure = vi.spyOn(commands, 'pluginConfigurationOpen'); + vi.spyOn(commands, 'pluginInventory').mockResolvedValue([plugin]); + vi.spyOn(commands, 'pluginConfigurationModes').mockRejectedValue(new Error('provider unavailable')); + renderInventory(); + expect(await screen.findByText(/configuration is unavailable for this plugin right now/i)).toBeInTheDocument(); + expect(unavailableConfigure).not.toHaveBeenCalled(); }); - afterEach(() => { - delete (navigator as unknown as { clipboard?: unknown }).clipboard; + it('loads and renders the authorized declarative schema in form-only mode', async () => { + vi.spyOn(commands, 'pluginInventory').mockResolvedValue([plugin]); + vi.spyOn(commands, 'pluginConfigurationModes').mockResolvedValue({ + externalDeclared: false, externalAuthorized: false, + declarativeDeclared: true, declarativeAuthorized: true, + }); + vi.spyOn(commands, 'pluginSettingsDescribe').mockResolvedValue({ + context: { plugin_id: plugin.pluginId, provider_id: plugin.providerId, session_id: 's1', profile_epoch: 1, form_handle: 'f1' }, + outcome: { type: 'form', form: { + schema_version: 1, form_id: 'prefs', schema_revision: 'schema-1', configuration_revision: 'config-1', + title: { fallback: 'Plugin preferences', translations: {} }, + fields: [{ id: 'label', label: { fallback: 'Catalog label', translations: {} }, kind: { type: 'text', min_length: 1, max_length: 32 }, default: { type: 'text', value: 'Games' } }], + }, values: { label: { type: 'text', value: 'Games' } } }, + }); + renderInventory(); + expect(await screen.findByRole('textbox', { name: 'Catalog label' })).toHaveValue('Games'); + expect(commands.pluginSettingsDescribe).toHaveBeenCalledWith(plugin.providerId); + }); + + it.each([ + [{ externalDeclared: true, externalAuthorized: false, declarativeDeclared: true, declarativeAuthorized: false }, /not authorized/i], + [{ externalDeclared: false, externalAuthorized: false, declarativeDeclared: false, declarativeAuthorized: false }, /does not provide an authorized configuration/i], + ])('does not request settings for denied or absent configuration', async (modes, message) => { + vi.spyOn(commands, 'pluginInventory').mockResolvedValue([plugin]); + vi.spyOn(commands, 'pluginConfigurationModes').mockResolvedValue(modes); + const describe = vi.spyOn(commands, 'pluginSettingsDescribe'); + renderInventory(); + expect(await screen.findByText(message)).toBeInTheDocument(); + expect(describe).not.toHaveBeenCalled(); }); - it('filters by trusted origin with live counts', async () => { + it.each([ + ['en', 'Linux Package Manager'], + ['pt-BR', 'Gerenciador de pacotes Linux'], + ])('localizes the Portuguese manifest in %s and retains unknown names', async (locale, label) => { vi.spyOn(commands, 'pluginInventory').mockResolvedValue([ - steam, - epic, - community, + { ...plugin, providerId: 'packagekit', name: 'Gerenciador de pacotes Linux' }, + { ...plugin, providerId: 'community', pluginId: 'community.plugin', name: 'Community Games' }, ]); - renderPlugins([steam, epic, community]); + renderInventory(locale); + expect((await screen.findAllByText(label)).length).toBeGreaterThan(0); + expect(screen.getByText('Community Games')).toBeInTheDocument(); + }); + + it('shows trusted origin, runtime status, actual grants and native access separately', async () => { + vi.spyOn(commands, 'pluginInventory').mockResolvedValue([plugin]); + renderInventory(); + + expect((await screen.findAllByText('Official')).length).toBeGreaterThan(0); + expect((await screen.findAllByText('Installed')).length).toBeGreaterThan(0); + expect(screen.getByText('library.discovery')).toBeInTheDocument(); + expect(screen.getByText('auth.webview')).toBeInTheDocument(); + expect(screen.getByText('secrets.read')).toBeInTheDocument(); + expect(screen.getByText('Files')).toBeInTheDocument(); + expect(screen.getByText('Network')).toBeInTheDocument(); + expect(screen.getByText(/not sandboxed/i)).toBeInTheDocument(); + expect(screen.getByText(/Process session: Active/)).toBeInTheDocument(); + expect(JSON.stringify(plugin)).not.toMatch(/token|cookie|password|credentialValue/i); + expect(screen.queryByRole('button', { name: 'Enable' })).not.toBeInTheDocument(); + expect(screen.queryByRole('button', { name: 'Remove' })).not.toBeInTheDocument(); + }); + + it('keeps community inventory read-only while signed out', async () => { + const managed: PluginInfo = { + ...plugin, source: 'community', pluginId: 'org.example.community', + publisherFingerprint: `SHA256:${'c'.repeat(64)}`, runtimeAvailable: true, + }; + vi.spyOn(commands, 'pluginInventory').mockResolvedValue([managed]); + vi.spyOn(commands, 'pluginUpdatePreferences').mockResolvedValue({ periodicChecks: false }); + vi.spyOn(commands, 'pluginUpdateAvailable').mockResolvedValue([]); + renderInventory(); + expect(await screen.findByText('Sign in to manage community plugins.')).toBeInTheDocument(); + expect(screen.queryByRole('button', { name: 'Enable' })).not.toBeInTheDocument(); + expect(screen.queryByRole('button', { name: 'Remove' })).not.toBeInTheDocument(); + }); + + it.each([ + ['en', 'This extension is installed but its runtime could not be registered. Review the package compatibility or reinstall it.'], + ['pt-BR', 'Esta extensão está instalada, mas o runtime dela não pôde ser registrado. Verifique a compatibilidade do pacote ou reinstale-o.'], + ])('explains unavailable extension runtime in %s and keeps removal available', async (locale, explanation) => { + const extension: PluginInfo = { + ...plugin, + providerId: 'org.example.extension', + pluginId: 'org.example.extension', + pluginKind: 'extension', + source: 'community', + session: 'stopped', + enabled: false, + runtimeAvailable: false, + publisherFingerprint: `SHA256:${'e'.repeat(64)}`, + }; + vi.spyOn(commands, 'pluginInventory').mockResolvedValue([extension]); + vi.spyOn(commands, 'pluginUpdatePreferences').mockResolvedValue({ periodicChecks: false }); + vi.spyOn(commands, 'pluginUpdateAvailable').mockResolvedValue([]); + renderInventory(locale, 'user-1'); + + expect(await screen.findByText(explanation)).toBeInTheDocument(); + expect(screen.queryByRole('button', { name: 'Enable' })).not.toBeInTheDocument(); + expect(screen.getByRole('button', { name: locale === 'pt-BR' ? 'Remover' : 'Remove' })).toBeInTheDocument(); + }); + + it('lets the user select a plugin and inspect its identity and permissions', async () => { + const secondPlugin: PluginInfo = { + ...plugin, + providerId: 'packagekit', + pluginId: 'org.gamenode.plugin.packagekit-discovery', + name: 'Gerenciador de pacotes Linux', + source: 'official', + capabilities: ['provider.context.read', 'library.discovery'], + nativeAccess: ['files', 'process', 'dbus'], + }; + vi.spyOn(commands, 'pluginInventory').mockResolvedValue([plugin, secondPlugin]); + renderInventory(); + + const list = await screen.findByRole('group', { name: 'Installed plugins' }); + const packagePluginOption = within(list).getByRole('button', { name: /Linux Package Manager/ }); + fireEvent.click(packagePluginOption); + + expect(packagePluginOption).toHaveAttribute('aria-pressed', 'true'); + expect(screen.getByRole('article', { name: 'Plugin details' })).toHaveTextContent('org.gamenode.plugin.packagekit-discovery'); + expect(screen.getByRole('article', { name: 'Plugin details' })).toHaveTextContent('library.discovery'); + expect(screen.getByRole('article', { name: 'Plugin details' })).toHaveTextContent('provider.context.read'); + expect(screen.getByRole('article', { name: 'Plugin details' })).toHaveTextContent('Local process execution'); + expect(screen.getByRole('article', { name: 'Plugin details' })).toHaveTextContent('System D-Bus'); + expect(screen.getByRole('article', { name: 'Plugin details' })).toHaveTextContent('Official'); + expect(screen.getByRole('article', { name: 'Plugin details' })).toHaveTextContent('Process session: Active'); + expect(packagePluginOption).toHaveTextContent('Installed'); + expect(screen.getByRole('article', { name: 'Plugin details' })).not.toHaveTextContent('auth.webview'); + }); + + it('shows missing executable state and Portuguese labels', async () => { + vi.spyOn(commands, 'pluginInventory').mockResolvedValue([{ ...plugin, status: 'missing', session: 'stopped' }]); + renderInventory('pt-BR'); - const filter = await screen.findByRole('radiogroup', { - name: 'Filter by origin', + expect((await screen.findAllByText('Oficial')).length).toBeGreaterThan(0); + expect((await screen.findAllByText('Executável ausente')).length).toBeGreaterThan(0); + expect(screen.getByText('Permissões de plugin concedidas')).toBeInTheDocument(); + expect(screen.getByText(/Sessão do processo: Parada/)).toBeInTheDocument(); + }); + + it('renders native package manager access labels in Portuguese', async () => { + vi.spyOn(commands, 'pluginInventory').mockResolvedValue([{ + ...plugin, + providerId: 'packagekit', + pluginId: 'org.gamenode.plugin.packagekit-discovery', + name: 'Gerenciador de pacotes Linux', + capabilities: ['provider.context.read', 'library.discovery'], + nativeAccess: ['files', 'process', 'dbus'], + }]); + renderInventory('pt-BR'); + + expect(await screen.findByText('Execução de processos locais')).toBeInTheDocument(); + expect(screen.getByText('D-Bus do sistema')).toBeInTheDocument(); + }); + + it.each([false, true])('reviews explicit updates and reports the active version (activation fails: %s)', async (fails) => { + vi.spyOn(commands, 'pluginInventory').mockResolvedValue([{ ...plugin, version: '1.0.0' }]); + const setPeriodic = vi.spyOn(commands, 'pluginUpdateSetPeriodicChecks').mockResolvedValue({ periodicChecks: true }); + vi.spyOn(commands, 'pluginUpdatePreferences').mockResolvedValue({ periodicChecks: false }); + vi.spyOn(commands, 'pluginUpdateCheck').mockResolvedValue([{ + pluginId: plugin.pluginId, name: plugin.name, installedVersion: '1.0.0', versions: ['2.0.0'], + }]); + vi.spyOn(commands, 'pluginUpdateReview').mockResolvedValue({ + pluginId: plugin.pluginId, installedVersion: '1.0.0', candidateVersion: '2.0.0', + addedPermissions: ['network.fetch'], removedPermissions: [], changedPermissions: ['files.read'], + permissionChanges: [{ id: 'files.read', installedScope: 'selected-game', candidateScope: 'all-games', installedRequired: false, candidateRequired: true }], + addedNativeAccess: ['process'], removedNativeAccess: [], apiChanged: true, + installedApi: '1.0.0 – 1.4.0', candidateApi: '1.0.0 – 2.0.0', + licenseChanged: true, installedLicense: 'MIT', candidateLicense: 'GPL-3.0-only', + installedLicenseFiles: ['LICENSE'], candidateLicenseFiles: ['LICENSE', 'NOTICE'], + installedLicenseNotices: [], candidateLicenseNotices: ['Third-party notice'], + installedPlaytime: { identifiesGameplay: false, identifiesPauses: false, withoutPauseDetection: 'disabled' }, + candidatePlaytime: { identifiesGameplay: true, identifiesPauses: false, withoutPauseDetection: 'application_open' }, + playtimeChanged: true, + publisherChanged: false, installedPublisherKeyId: 'publisher-1', candidatePublisherKeyId: 'publisher-1', + publisherFingerprint: '', changedDataSchemas: [], preservesPriorData: true, isDowngrade: false, + requiresManualApproval: true, }); - expect(within(filter).getByRole('radio', { name: 'All · 3' })).toBeChecked(); - expect( - within(filter).getByRole('radio', { name: 'Official · 2' }), - ).toBeInTheDocument(); - expect( - within(filter).getByRole('radio', { name: 'Community · 1' }), - ).toBeInTheDocument(); - - fireEvent.click(within(filter).getByRole('radio', { name: 'Community · 1' })); - expect(screen.getByRole('article', { name: 'Prateleira Local' })).toBeInTheDocument(); - expect(screen.queryByRole('article', { name: 'Steam' })).not.toBeInTheDocument(); - - fireEvent.click(within(filter).getByRole('radio', { name: 'Official · 2' })); - expect(screen.getByRole('article', { name: 'Steam' })).toBeInTheDocument(); - expect(screen.getByRole('article', { name: 'Epic Games Store' })).toBeInTheDocument(); - expect( - screen.queryByRole('article', { name: 'Prateleira Local' }), - ).not.toBeInTheDocument(); - }); - - it('shows versions, origin, session state, native access and the community note', async () => { - vi.spyOn(commands, 'pluginInventory').mockResolvedValue([ - steam, - epic, - community, - ]); - renderPlugins([steam, epic, community]); - - expect(await screen.findByText('1.4.2')).toBeInTheDocument(); - expect(screen.getByText('2.0.1')).toBeInTheDocument(); - expect(screen.getByText('0.3.1')).toBeInTheDocument(); - expect(screen.getAllByText('Official').length).toBeGreaterThanOrEqual(2); - expect(screen.getByText('Community')).toBeInTheDocument(); - expect(screen.getAllByText('Session active').length).toBe(2); - expect(screen.getByText('Stopped')).toBeInTheDocument(); - expect(screen.getAllByText('Network')).toHaveLength(2); - expect(screen.getAllByText('Files')).toHaveLength(3); - expect(screen.getByText('Processes')).toBeInTheDocument(); - expect(screen.getByText('Registry')).toBeInTheDocument(); - expect(screen.getByText('D-Bus')).toBeInTheDocument(); - expect( - screen.getByText( - "Community plugins aren't reviewed by GameNode. Only grant permissions that make sense.", - ), - ).toBeInTheDocument(); - expect(screen.queryByText(/sandbox/i)).not.toBeInTheDocument(); - }); - - it('renders an unknown native-access value as its raw neutral pill', async () => { - vi.spyOn(commands, 'pluginInventory').mockResolvedValue([ - { ...steam, nativeAccess: ['files', 'customAccess'] }, - ]); - renderPlugins([steam]); + let finish!: () => void; + const approve = vi.spyOn(commands, 'pluginUpdateApprove').mockReturnValue(new Promise((resolve, reject) => { + finish = () => fails ? reject(new Error('candidate did not become ready')) : resolve('2.0.0'); + })); + renderInventory(); - expect(await screen.findByText('Files')).toBeInTheDocument(); - expect(screen.getByText('customAccess')).toBeInTheDocument(); + const periodicCheckbox = await screen.findByRole('checkbox', { name: /Check periodically/ }); + await waitFor(() => expect(periodicCheckbox).toBeEnabled()); + fireEvent.click(periodicCheckbox); + await waitFor(() => expect(setPeriodic).toHaveBeenCalledWith(true)); + fireEvent.click(screen.getByRole('button', { name: 'Check for updates now' })); + fireEvent.click(await screen.findByRole('button', { name: 'Review version 2.0.0' })); + expect(await screen.findByRole('article', { name: 'Review plugin update' })).toHaveTextContent('selected-game → all-games'); + expect(screen.getByText(/Signed playtime policy change/)).toBeInTheDocument(); + expect(screen.getByText(/New permissions and wider scopes stay denied/)).toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: 'Approve update' })); + await waitFor(() => expect(approve).toHaveBeenCalledWith(plugin.pluginId, '2.0.0')); + expect(screen.getByRole('button', { name: 'Approve update' })).toBeDisabled(); + expect(periodicCheckbox).toBeEnabled(); + finish(); + if (fails) { + expect(await screen.findByText('Active version: 1.0.0')).toBeInTheDocument(); + expect(screen.getByText('candidate did not become ready')).toBeInTheDocument(); + } else { + expect(await screen.findByText('Update complete. Active version: 2.0.0')).toBeInTheDocument(); + } + await waitFor(() => expect(screen.queryByRole('button', { name: 'Approve update' })).not.toBeInTheDocument()); }); - it('shows a missing executable state without offering a session control', async () => { - vi.spyOn(commands, 'pluginInventory').mockResolvedValue([ - { ...steam, status: 'missing', session: 'stopped' }, - ]); - renderPlugins([steam]); + it.each([ + { rollback: false, version: '2.0.0', reviewButton: 'Review version 2.0.0', approval: 'Approve update', locale: 'en', chooseLabel: 'Choose a game for the readiness check', targetLabel: 'Target game' }, + { rollback: true, version: '1.0.0', reviewButton: 'Revisar rollback para 1.0.0', approval: 'Confirmar rollback', locale: 'pt-BR', chooseLabel: 'Escolher um jogo para a verificação', targetLabel: 'Jogo alvo' }, + ])('selects an explicit target and can cancel extension approval (rollback=$rollback)', async ({ rollback, version, reviewButton, approval, locale, chooseLabel, targetLabel }) => { + const pluginId = 'org.example.extension'; + const extension = { ...plugin, pluginId, providerId: '', pluginKind: 'extension' as const, session: 'stopped' as const, enabled: true }; + const target = { installationId: 'installation-42', revision: '7', profileEpoch: '3' }; + vi.spyOn(commands, 'pluginInventory').mockResolvedValue([extension]); + vi.spyOn(commands, 'pluginUpdateAvailable').mockResolvedValue(rollback ? [] : [{ + pluginId, name: 'Test extension', installedVersion: '1.0.0', versions: [version], + }]); + vi.spyOn(commands, 'pluginRollbackAvailable').mockResolvedValue(rollback ? [{ + pluginId, name: 'Test extension', activeVersion: '2.0.0', versions: [version], + }] : []); + const readReview = rollback ? commands.pluginRollbackReview : commands.pluginUpdateReview; + const review = await readReview(pluginId, version); + vi.spyOn(commands, rollback ? 'pluginRollbackReview' : 'pluginUpdateReview').mockResolvedValue({ + ...review, extensionTargets: [{ name: 'Example Game', providerId: 'steam', selection: target }], + }); + const approveUpdate = vi.spyOn(commands, 'pluginUpdateApprove').mockResolvedValue(version); + const approveRollback = vi.spyOn(commands, 'pluginRollbackApprove').mockResolvedValue(version); + const decline = vi.spyOn(commands, 'pluginUpdateDecline').mockResolvedValue(undefined); + renderInventory(locale, 'signed-in'); + + async function openTargetPicker() { + fireEvent.click(await screen.findByRole('button', { name: reviewButton })); + const choose = await screen.findByRole('button', { name: chooseLabel }); + if (rollback) { + expect(choose).toBeDisabled(); + fireEvent.click(screen.getByRole('checkbox', { name: /Entendo que isso ativará/ })); + } + fireEvent.click(choose); + return within(await screen.findByRole('dialog', { name: chooseLabel })); + } + + const firstPicker = await openTargetPicker(); + expect(firstPicker.getByRole('button', { name: approval })).toBeDisabled(); + fireEvent.change(firstPicker.getByRole('combobox', { name: targetLabel }), { target: { value: target.installationId } }); + await userEvent.setup().keyboard('{Escape}'); + await waitFor(() => expect(decline).toHaveBeenCalledWith(pluginId)); + await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument()); + expect(approveUpdate).not.toHaveBeenCalled(); + expect(approveRollback).not.toHaveBeenCalled(); - expect(await screen.findByText('Missing')).toBeInTheDocument(); - expect(screen.queryByRole('button', { name: 'Start' })).not.toBeInTheDocument(); - expect(screen.queryByRole('button', { name: 'Stop' })).not.toBeInTheDocument(); + const secondPicker = await openTargetPicker(); + expect(secondPicker.getByRole('button', { name: approval })).toBeDisabled(); + fireEvent.change(secondPicker.getByRole('combobox', { name: targetLabel }), { target: { value: target.installationId } }); + fireEvent.click(secondPicker.getByRole('button', { name: approval })); + if (rollback) { + await waitFor(() => expect(approveRollback).toHaveBeenCalledWith(pluginId, version, true, target)); + } else { + await waitFor(() => expect(approveUpdate).toHaveBeenCalledWith(pluginId, version, target)); + } }); - it('copies the plugin id and confirms with a toast', async () => { - const writeText = vi.fn().mockResolvedValue(undefined); - Object.defineProperty(navigator, 'clipboard', { - configurable: true, - value: { writeText }, + it('keeps the saved opt-in authoritative when persistence fails', async () => { + vi.spyOn(commands, 'pluginInventory').mockResolvedValue([plugin]); + vi.spyOn(commands, 'pluginUpdateAvailable').mockResolvedValue([]); + vi.spyOn(commands, 'pluginUpdatePreferences').mockResolvedValue({ periodicChecks: true }); + vi.spyOn(commands, 'pluginUpdateSetPeriodicChecks').mockRejectedValue(new Error('disk full')); + renderInventory(); + + const periodicCheckbox = await screen.findByRole('checkbox', { name: /Check periodically/ }); + await waitFor(() => expect(periodicCheckbox).toBeChecked()); + fireEvent.click(periodicCheckbox); + + await waitFor(() => { + expect(periodicCheckbox).toBeChecked(); + expect(screen.getByText(/Could not check or review this update/)).toBeInTheDocument(); }); - vi.spyOn(commands, 'pluginInventory').mockResolvedValue([steam]); - renderPlugins([steam]); + }); + + it('reviews a staged package, requires exact publisher trust, and installs it enabled', async () => { + vi.spyOn(commands, 'pluginInventory').mockResolvedValue([]); + vi.spyOn(commands, 'pluginUpdatePreferences').mockResolvedValue({ periodicChecks: false }); + vi.spyOn(commands, 'pluginUpdateAvailable').mockResolvedValue([]); + const staged = { + token: 'review-token', pluginId: 'org.example.community', name: 'Community', version: '1.0.0', + publisherKeyId: 'key-1', publisherFingerprint: 'SHA256:abc', trust: 'untrusted' as const, + license: 'MIT', licenseFiles: ['LICENSE'], licenseNotices: [], permissionIds: ['library.read'], + requestedPermissions: [{ + id: 'library.read', required: false, scope: 'selected-game', + reason: 'Read selected game data', + impactIfDisabled: 'Selected game details are not shown.', + }], + supportedPlatforms: ['gamecube', 'wii'], + nativeAccess: [], + playtime: { identifiesGameplay: true, identifiesPauses: false, withoutPauseDetection: 'application_open' as const }, + compatibility: 'compatible' as const, + }; + const importReview = vi.spyOn(commands, 'pluginImportReview').mockResolvedValue(staged); + const confirm = vi.spyOn(commands, 'pluginImportConfirmPublisher').mockResolvedValue({ ...staged, trust: 'trusted' }); + const viewLicense = vi.spyOn(commands, 'pluginImportLicenseText').mockResolvedValue('MIT license text available offline'); + const install = vi.spyOn(commands, 'pluginImportInstall').mockResolvedValue({ pluginId: staged.pluginId, activated: true }); + renderInventory('en', 'account-import'); - const copyButton = await screen.findByRole('button', { - name: /Copy identifier: org\.gamenode\.plugin\.steam-discovery/, + fireEvent.change(await screen.findByRole('textbox', { name: 'Path to signed bundle' }), { target: { value: '/packages/community.zip' } }); + await userEvent.setup().type(screen.getByRole('textbox', { name: 'Path to signed bundle' }), '{Enter}'); + expect(await screen.findByRole('article', { name: 'Review plugin package' })).toHaveTextContent('SHA256:abc'); + const packageReview = screen.getByRole('article', { name: 'Review plugin package' }); + expect(packageReview).toHaveTextContent('Platforms: GameCube, Wii'); + expect(packageReview).toHaveTextContent('Read library'); + expect(packageReview).toHaveTextContent('Selected game'); + expect(packageReview).toHaveTextContent('Optional'); + expect(packageReview).toHaveTextContent('Read selected game data'); + + // Optional permissions default on; turning one off explains what stops working. + const toggle = within(packageReview).getByRole('switch', { name: 'Allow Read library' }); + expect(toggle).toBeChecked(); + fireEvent.click(toggle); + expect(toggle).not.toBeChecked(); + expect(within(packageReview).getByText('Selected game details are not shown.')).toBeInTheDocument(); + + fireEvent.click(within(packageReview).getByText('Technical details')); + expect(packageReview).toHaveTextContent('Playtime behavior declared by this signed package'); + expect(packageReview).toHaveTextContent('Application-open time'); + expect(within(packageReview).getByText(/This plugin cannot distinguish pauses/)).toBeInTheDocument(); + fireEvent.click(screen.getByText('LICENSE')); + fireEvent.click(screen.getByRole('button', { name: 'View this license or notice offline' })); + expect(await screen.findByText('MIT license text available offline')).toBeInTheDocument(); + expect(viewLicense).toHaveBeenCalledWith('review-token', 'LICENSE'); + + const accept = within(packageReview).getByRole('button', { name: 'Accept, install and enable' }); + expect(accept).toBeDisabled(); + expect(accept).toHaveClass('w-full'); + fireEvent.click(within(packageReview).getByRole('button', { name: 'Trust this publisher' })); + await waitFor(() => expect(confirm).toHaveBeenCalledWith('review-token', 'SHA256:abc')); + await waitFor(() => expect(accept).toBeEnabled()); + fireEvent.click(accept); + await waitFor(() => expect(install).toHaveBeenCalledWith('review-token', false, ['library.read'])); + expect(importReview).toHaveBeenCalledWith('/packages/community.zip'); + }); + + it('locks required permissions and omits an empty platform line', async () => { + vi.spyOn(commands, 'pluginInventory').mockResolvedValue([]); + vi.spyOn(commands, 'pluginUpdatePreferences').mockResolvedValue({ periodicChecks: false }); + vi.spyOn(commands, 'pluginUpdateAvailable').mockResolvedValue([]); + const staged = { + token: 'required-review', pluginId: 'org.example.required', name: 'Required', version: '1.0.0', + publisherKeyId: 'key-required', publisherFingerprint: 'SHA256:required', trust: 'trusted' as const, + license: 'MIT', licenseFiles: [], licenseNotices: [], permissionIds: ['provider.context.read'], + requestedPermissions: [{ + id: 'provider.context.read', required: true, scope: 'own-provider', + reason: 'Read the host-issued provider context.', + }], + nativeAccess: [], + playtime: { identifiesGameplay: false, identifiesPauses: false, withoutPauseDetection: 'disabled' as const }, + compatibility: 'compatible' as const, + }; + vi.spyOn(commands, 'pluginImportReview').mockResolvedValue(staged); + const install = vi.spyOn(commands, 'pluginImportInstall').mockResolvedValue({ pluginId: staged.pluginId, activated: true }); + renderInventory('en', 'account-required'); + + fireEvent.change(await screen.findByRole('textbox', { name: 'Path to signed bundle' }), { target: { value: '/packages/required.gnplugin' } }); + await userEvent.setup().type(screen.getByRole('textbox', { name: 'Path to signed bundle' }), '{Enter}'); + const review = await screen.findByRole('article', { name: 'Review plugin package' }); + expect(review).toHaveTextContent('Provider context'); + expect(review).toHaveTextContent('Required by the package and cannot be turned off.'); + expect(within(review).queryByRole('switch')).not.toBeInTheDocument(); + expect(review).not.toHaveTextContent('Platforms'); + + const accept = within(review).getByRole('button', { name: 'Accept, install and enable' }); + expect(accept).toBeEnabled(); + fireEvent.click(accept); + await waitFor(() => expect(install).toHaveBeenCalledWith('required-review', false, [])); + }); + + it('blocks installing a package whose only target mismatches the libc family', async () => { + vi.spyOn(commands, 'pluginInventory').mockResolvedValue([]); + vi.spyOn(commands, 'pluginUpdatePreferences').mockResolvedValue({ periodicChecks: false }); + vi.spyOn(commands, 'pluginUpdateAvailable').mockResolvedValue([]); + const target = { + os: 'linux', arch: 'x86_64', abi: 'gnu', entrypoint: 'bin/plugin', + requires: { linux: { libc: { family: 'glibc' as const, min_version: '2.31' } } }, tested_on: [], + }; + vi.spyOn(commands, 'pluginImportReview').mockResolvedValue({ + token: 'musl-review', pluginId: 'org.example.musl', name: 'Musl', version: '1.0.0', + publisherKeyId: 'key-musl', publisherFingerprint: 'SHA256:musl', trust: 'trusted', + license: 'MIT', licenseFiles: [], licenseNotices: [], permissionIds: [], requestedPermissions: [], + nativeAccess: [], playtime: { identifiesGameplay: false, identifiesPauses: false, withoutPauseDetection: 'disabled' }, + compatibility: 'incompatible', compatibilityReason: 'no compatible target', + compatibilityDetails: { + state: 'incompatible', ambiguous: false, os: 'alpine', release: '3.19', architecture: 'x86_64', abi: 'musl', + libc: { family: 'musl', version: '1.2.4' }, emulation: 'native', + targets: [{ target, verdict: { state: 'incompatible', reasons: ['linuxLibcMismatch'], unknownFacts: [] } }], + }, }); - fireEvent.click(copyButton); + renderInventory('en', 'account-musl'); + fireEvent.change(await screen.findByRole('textbox', { name: 'Path to signed bundle' }), { target: { value: '/packages/musl.zip' } }); + await userEvent.setup().type(screen.getByRole('textbox', { name: 'Path to signed bundle' }), '{Enter}'); + const review = await screen.findByRole('article', { name: 'Review plugin package' }); + expect(within(review).getByRole('region', { name: 'Compatibility with this system' })).toHaveTextContent('The C library family does not match'); + expect(screen.getByRole('button', { name: 'Accept, install and enable' })).toBeDisabled(); + }); + + it('requires separate explicit consent for declared native access', async () => { + vi.spyOn(commands, 'pluginInventory').mockResolvedValue([]); + vi.spyOn(commands, 'pluginUpdatePreferences').mockResolvedValue({ periodicChecks: false }); + vi.spyOn(commands, 'pluginUpdateAvailable').mockResolvedValue([]); + const staged = { + token: 'native-review', pluginId: 'org.example.native', name: 'Native', version: '1.0.0', + publisherKeyId: 'key-native', publisherFingerprint: 'SHA256:native', trust: 'trusted' as const, + license: 'MIT', licenseFiles: [], licenseNotices: [], permissionIds: [], requestedPermissions: [], + nativeAccess: ['process'], playtime: { identifiesGameplay: false, identifiesPauses: false, withoutPauseDetection: 'disabled' as const }, + compatibility: 'compatible' as const, + }; + const install = vi.spyOn(commands, 'pluginImportInstall').mockResolvedValue({ pluginId: staged.pluginId, activated: true }); + vi.spyOn(commands, 'pluginImportReview').mockResolvedValue(staged); + renderInventory('en', 'account-import'); + + fireEvent.change(await screen.findByRole('textbox', { name: 'Path to signed bundle' }), { target: { value: '/packages/native.zip' } }); + fireEvent.click(screen.getByRole('button', { name: 'Review package' })); + const installButton = await screen.findByRole('button', { name: 'Accept, install and enable' }); + expect(installButton).toBeDisabled(); + fireEvent.click(screen.getByRole('checkbox', { name: /reviewed the declared native access/i })); + expect(installButton).toBeEnabled(); + fireEvent.click(installButton); + await waitFor(() => expect(install).toHaveBeenCalledWith('native-review', true, [])); + }); + + it('shows the old fingerprint and requires explicit re-trust when a publisher key changes', async () => { + vi.spyOn(commands, 'pluginInventory').mockResolvedValue([]); + vi.spyOn(commands, 'pluginUpdatePreferences').mockResolvedValue({ periodicChecks: false }); + vi.spyOn(commands, 'pluginUpdateAvailable').mockResolvedValue([]); + const changed = { + token: 'changed-token', pluginId: 'org.example.changed', name: 'Changed', version: '2.0.0', + publisherKeyId: 'key-2', publisherFingerprint: 'SHA256:new', pinnedFingerprint: 'SHA256:old', + trust: 'changed' as const, license: 'MIT', licenseFiles: [], licenseNotices: [], + requestedPermissions: [], playtime: { identifiesGameplay: false, identifiesPauses: false, withoutPauseDetection: 'disabled' as const }, + permissionIds: [], nativeAccess: [], compatibility: 'compatible' as const, + }; + vi.spyOn(commands, 'pluginImportReview').mockResolvedValue(changed); + const retrust = vi.spyOn(commands, 'pluginImportConfirmPublisher').mockResolvedValue({ ...changed, trust: 'trusted', pinnedFingerprint: undefined }); + renderInventory('en', 'account-import'); + fireEvent.change(await screen.findByRole('textbox', { name: 'Path to signed bundle' }), { target: { value: '/packages/changed.zip' } }); + await userEvent.setup().type(screen.getByRole('textbox', { name: 'Path to signed bundle' }), '{Enter}'); + + expect(await screen.findByText('Previously trusted fingerprint: SHA256:old')).toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: 'Re-trust this changed publisher key' })); + await waitFor(() => expect(retrust).toHaveBeenCalledWith('changed-token', 'SHA256:new')); + }); + + it('saves only selected network origins for the reviewed account, publisher and revision', async () => { + const managed: PluginInfo = { + ...plugin, pluginId: 'org.example.community', source: 'community', + publisherFingerprint: `SHA256:${'a'.repeat(64)}`, runtimeAvailable: true, enabled: false, + }; + const permissionSnapshot: PluginPermissionSnapshot = { + pluginId: managed.pluginId, publisherFingerprint: managed.publisherFingerprint!, + profileId: 'host-profile-one', grantRevision: 12, + requestedPermissions: [{ + permission_id: 'network.fetch', required: false, + allowed_scopes: [ + { scope: 'declared', value: 'https://api.example.com' }, + { scope: 'declared', value: 'https://cdn.example.com:8443' }, + ], + }], + effectiveGrants: [], + }; + vi.spyOn(commands, 'pluginInventory').mockResolvedValue([managed]); + vi.spyOn(commands, 'pluginUpdatePreferences').mockResolvedValue({ periodicChecks: false }); + vi.spyOn(commands, 'pluginUpdateAvailable').mockResolvedValue([]); + vi.spyOn(commands, 'pluginPermissionSnapshot').mockResolvedValue(permissionSnapshot); + const replace = vi.spyOn(commands, 'pluginPermissionsReplace').mockResolvedValue({ ...permissionSnapshot, grantRevision: 13 }); + renderInventory('en', 'account-one'); + + expect(await screen.findByText(/Requested scopes come from the verified package manifest/)).toBeInTheDocument(); + const apiOrigin = await screen.findByRole('checkbox', { name: /api\.example\.com.*Denied/ }); + const cdnOrigin = screen.getByRole('checkbox', { name: /cdn\.example\.com:8443.*Denied/ }); + expect(apiOrigin).not.toBeChecked(); + fireEvent.click(apiOrigin); + expect(cdnOrigin).not.toBeChecked(); + fireEvent.click(screen.getByRole('button', { name: 'Save permission choices' })); + await waitFor(() => expect(replace).toHaveBeenCalledWith( + managed.pluginId, + 'host-profile-one', + managed.publisherFingerprint, + 12, + [ + { permission_id: 'network.fetch', scope: { scope: 'declared', value: 'https://api.example.com' }, granted: true }, + { permission_id: 'network.fetch', scope: { scope: 'declared', value: 'https://cdn.example.com:8443' }, granted: false }, + ], + )); + }); + + it('keeps a completed network permission save in the reviewed publisher cache', async () => { + const oldFingerprint = `SHA256:${'a'.repeat(64)}`; + const newFingerprint = `SHA256:${'b'.repeat(64)}`; + const managed: PluginInfo = { + ...plugin, source: 'community', publisherFingerprint: oldFingerprint, runtimeAvailable: true, + }; + const scope = { scope: 'declared', value: 'https://api.example.com' } as const; + const review: PluginPermissionSnapshot = { + pluginId: managed.pluginId, profileId: 'a', publisherFingerprint: oldFingerprint, grantRevision: 0, + requestedPermissions: [{ permission_id: 'network.fetch', required: false, allowed_scopes: [scope] }], + effectiveGrants: [], + }; + const newReview = { ...review, publisherFingerprint: newFingerprint }; + const newInventory = [{ ...managed, publisherFingerprint: newFingerprint }]; + vi.spyOn(commands, 'pluginInventory').mockResolvedValueOnce([managed]).mockResolvedValue(newInventory); + vi.spyOn(commands, 'pluginPermissionSnapshot').mockResolvedValueOnce(review).mockResolvedValue(newReview); + let finishSave!: (snapshot: PluginPermissionSnapshot) => void; + const pendingSave = new Promise((resolve) => { finishSave = resolve; }); + const replace = vi.spyOn(commands, 'pluginPermissionsReplace').mockReturnValue(pendingSave); + const { client } = renderInventory('en', 'a'); + + fireEvent.click(await screen.findByRole('checkbox', { name: /api\.example\.com.*Denied/ })); + fireEvent.click(screen.getByRole('button', { name: 'Save permission choices' })); + expect(replace).toHaveBeenCalledOnce(); + const oldKey = pluginQueryKeys.permissions(managed.pluginId, 'a', oldFingerprint); + const newKey = pluginQueryKeys.permissions(managed.pluginId, 'a', newFingerprint); + act(() => { client.setQueryData(pluginQueryKeys.inventory, newInventory); }); + await waitFor(() => expect(client.getQueryData(newKey)).toEqual(newReview)); + + const saved: PluginPermissionSnapshot = { + ...review, grantRevision: 1, + effectiveGrants: [{ permission_id: 'network.fetch', required: false, scope, state: 'granted' }], + }; + await act(async () => { finishSave(saved); }); + expect(client.getQueryData(oldKey)).toEqual(saved); + expect(client.getQueryData(newKey)).toEqual(newReview); + expect(screen.getByRole('checkbox', { name: /api\.example\.com.*Denied/ })).not.toBeChecked(); + }); + + it('uses the shared removal modal with Escape and invokes stop-before-remove lifecycle command', async () => { + const managed: PluginInfo = { + ...plugin, source: 'community', pluginId: 'org.example.community', + publisherFingerprint: `SHA256:${'d'.repeat(64)}`, runtimeAvailable: true, enabled: false, + }; + vi.spyOn(commands, 'pluginInventory').mockResolvedValue([managed]); + vi.spyOn(commands, 'pluginUpdatePreferences').mockResolvedValue({ periodicChecks: false }); + vi.spyOn(commands, 'pluginUpdateAvailable').mockResolvedValue([]); + vi.spyOn(commands, 'pluginPermissionSnapshot').mockResolvedValue({ + pluginId: managed.pluginId, publisherFingerprint: managed.publisherFingerprint!, + profileId: 'account-one', grantRevision: 1, requestedPermissions: [], effectiveGrants: [], + }); + const remove = vi.spyOn(commands, 'pluginRemove').mockResolvedValue(undefined); + renderInventory('en', 'account-one'); + + const trigger = await screen.findByRole('button', { name: 'Remove' }); + fireEvent.click(trigger); + expect(await screen.findByRole('dialog')).toBeInTheDocument(); + await userEvent.setup().keyboard('{Escape}'); + await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument()); + fireEvent.click(trigger); + expect(within(await screen.findByRole('dialog')) + .getByRole('radio', { name: 'Keep private data for the signed-in account (recommended)' }) + ).toBeChecked(); + fireEvent.click(within(await screen.findByRole('dialog')).getByRole('button', { name: 'Remove' })); + await waitFor(() => expect(remove).toHaveBeenCalledWith(managed.pluginId, false)); + }); + + it('applies the single-plugin Keep/Delete choice to the private data', async () => { + const managed: PluginInfo = { + ...plugin, source: 'community', pluginId: 'org.example.community', + publisherFingerprint: `SHA256:${'d'.repeat(64)}`, runtimeAvailable: true, enabled: false, + }; + vi.spyOn(commands, 'pluginInventory').mockResolvedValue([managed]); + vi.spyOn(commands, 'pluginUpdatePreferences').mockResolvedValue({ periodicChecks: false }); + vi.spyOn(commands, 'pluginUpdateAvailable').mockResolvedValue([]); + vi.spyOn(commands, 'pluginPermissionSnapshot').mockResolvedValue({ + pluginId: managed.pluginId, publisherFingerprint: managed.publisherFingerprint!, + profileId: 'account-one', grantRevision: 1, requestedPermissions: [], effectiveGrants: [], + }); + const remove = vi.spyOn(commands, 'pluginRemove').mockResolvedValue(undefined); + renderInventory('en', 'account-one'); + + fireEvent.click(await screen.findByRole('button', { name: 'Remove' })); + const dialog = await screen.findByRole('dialog'); + fireEvent.click(within(dialog).getByRole('radio', { + name: 'Delete private data for the signed-in account', + })); + fireEvent.click(within(dialog).getByRole('button', { name: 'Remove' })); await waitFor(() => - expect(writeText).toHaveBeenCalledWith( - 'org.gamenode.plugin.steam-discovery', - ), - ); - expect(await screen.findByText('Identifier copied')).toBeInTheDocument(); - }); - - it('expands in-card details, marks the card selected and keeps grants apart from native access', async () => { - vi.spyOn(commands, 'pluginInventory').mockResolvedValue([steam, community]); - renderPlugins([steam, community]); - - const card = await screen.findByRole('article', { name: 'Steam' }); - const details = within(card).getByRole('button', { name: 'Details' }); - expect(details).toHaveAttribute('aria-expanded', 'false'); - - fireEvent.click(details); - - expect(details).toHaveAttribute('aria-expanded', 'true'); - expect(card).toHaveAttribute('data-selected', 'true'); - expect(card.className).toContain('border-brand'); - expect( - within(card).getByRole('heading', { name: 'API permissions' }), - ).toBeInTheDocument(); - expect( - within(card).getByRole('heading', { name: 'Native system access' }), - ).toBeInTheDocument(); - expect(within(card).getByText('library.discovery')).toBeInTheDocument(); - expect(within(card).getByText('auth.webview')).toBeInTheDocument(); - expect(within(card).getByText('secrets.read')).toBeInTheDocument(); - - fireEvent.click(within(card).getByRole('button', { name: 'Hide details' })); - expect(details).toHaveAttribute('aria-expanded', 'false'); - expect(card).not.toHaveAttribute('data-selected'); - expect( - within(card).queryByRole('heading', { name: 'API permissions' }), - ).not.toBeInTheDocument(); - }); - - it('stops and starts a plugin process and refreshes its session state', async () => { - const inventory = vi - .spyOn(commands, 'pluginInventory') - .mockResolvedValueOnce([epic]) - .mockResolvedValueOnce([{ ...epic, session: 'stopped' }]) - .mockResolvedValueOnce([epic]); - const stop = vi.spyOn(commands, 'pluginStop').mockResolvedValue(undefined); - const start = vi.spyOn(commands, 'pluginStart').mockResolvedValue(undefined); - renderPlugins([epic]); - - fireEvent.click(await screen.findByRole('button', { name: 'Stop' })); - await waitFor(() => expect(stop).toHaveBeenCalledWith('epic')); - expect(await screen.findByRole('button', { name: 'Start' })).toBeInTheDocument(); - expect(screen.getByText('Stopped')).toBeInTheDocument(); - await waitFor(() => expect(inventory).toHaveBeenCalledTimes(2)); - - fireEvent.click(screen.getByRole('button', { name: 'Start' })); - await waitFor(() => expect(start).toHaveBeenCalledWith('epic')); - expect(await screen.findByRole('button', { name: 'Stop' })).toBeInTheDocument(); - expect(screen.getByText('Session active')).toBeInTheDocument(); - }); - - it('keeps the active session and shows an error when stopping fails', async () => { - vi.spyOn(commands, 'pluginInventory').mockResolvedValue([epic]); - vi.spyOn(commands, 'pluginStop').mockRejectedValue( - new Error('plugin shutdown failed'), - ); - renderPlugins([epic]); + expect(remove).toHaveBeenCalledWith('org.example.community', true)); + }); + + it('caches host permission revisions and configuration metadata without plugin preferences', async () => { + const managed: PluginInfo = { + ...plugin, + pluginId: 'org.example.community', + source: 'community', + publisherFingerprint: `SHA256:${'a'.repeat(64)}`, + }; + const permissions: PluginPermissionSnapshot = { + pluginId: managed.pluginId, + publisherFingerprint: managed.publisherFingerprint!, + profileId: 'account-one', + grantRevision: 7, + requestedPermissions: [], + effectiveGrants: [], + }; + const configuration: PluginConfigurationState = { + pluginId: managed.pluginId, + available: true, + revision: '1.2.0:external=true:declarative=false', + }; + vi.spyOn(commands, 'pluginInventory').mockResolvedValue([managed]); + vi.spyOn(commands, 'pluginUpdatePreferences').mockResolvedValue({ periodicChecks: false }); + vi.spyOn(commands, 'pluginUpdateAvailable').mockResolvedValue([]); + vi.spyOn(commands, 'pluginPermissionSnapshot').mockResolvedValue(permissions); + vi.spyOn(commands, 'pluginConfigurationState').mockResolvedValue(configuration); - fireEvent.click(await screen.findByRole('button', { name: 'Stop' })); + const { client } = renderInventory('en', 'account-one'); + await waitFor(() => { + expect(commands.pluginPermissionSnapshot).toHaveBeenCalledWith(managed.pluginId, 'account-one'); + expect(commands.pluginConfigurationState).toHaveBeenCalledWith(managed.pluginId); + }); + expect(client.getQueryData(pluginQueryKeys.permissions(managed.pluginId, 'account-one', managed.publisherFingerprint))) + .toEqual(permissions); + expect(client.getQueryData(pluginQueryKeys.configuration(managed.pluginId))) + .toEqual(configuration); + }); + + it('retains the last host permission and configuration snapshots after read errors', async () => { + const managed: PluginInfo = { + ...plugin, + pluginId: 'org.example.community', + source: 'community', + publisherFingerprint: `SHA256:${'b'.repeat(64)}`, + }; + const savedPermissions: PluginPermissionSnapshot = { + pluginId: managed.pluginId, + publisherFingerprint: managed.publisherFingerprint!, + profileId: 'account-two', + grantRevision: 11, + requestedPermissions: [], + effectiveGrants: [], + }; + const savedConfiguration: PluginConfigurationState = { + pluginId: managed.pluginId, + available: true, + revision: '2.0.0:external=false:declarative=true', + }; + vi.spyOn(commands, 'pluginInventory').mockResolvedValue([managed]); + vi.spyOn(commands, 'pluginUpdatePreferences').mockResolvedValue({ periodicChecks: false }); + vi.spyOn(commands, 'pluginUpdateAvailable').mockResolvedValue([]); + vi.spyOn(commands, 'pluginPermissionSnapshot').mockRejectedValue(new Error('offline')); + vi.spyOn(commands, 'pluginConfigurationState').mockRejectedValue(new Error('offline')); - expect( - await screen.findByTestId('settings-plugins-error'), - ).toHaveTextContent('Could not stop or start the plugin. Try again.'); - expect(screen.getByText('Session active')).toBeInTheDocument(); - expect(screen.getByRole('button', { name: 'Stop' })).toBeEnabled(); + const { client } = renderInventory('en', 'account-two', (queryClient) => { + queryClient.setQueryData( + pluginQueryKeys.permissions(managed.pluginId, 'account-two', managed.publisherFingerprint), + savedPermissions, + ); + queryClient.setQueryData(pluginQueryKeys.configuration(managed.pluginId), savedConfiguration); + }); + await waitFor(() => { + expect(commands.pluginPermissionSnapshot).toHaveBeenCalledWith(managed.pluginId, 'account-two'); + expect(commands.pluginConfigurationState).toHaveBeenCalledWith(managed.pluginId); + }); + expect(client.getQueryData(pluginQueryKeys.permissions(managed.pluginId, 'account-two', managed.publisherFingerprint))) + .toEqual(savedPermissions); + expect(client.getQueryData(pluginQueryKeys.configuration(managed.pluginId))) + .toEqual(savedConfiguration); }); - it('links an expired store session to the Stores topic', async () => { - vi.spyOn(commands, 'pluginInventory').mockResolvedValue([epic]); - renderPlugins([epic], { - storeAccounts: [storeAccount('epic', 'expired')], + it('does not let a stale check response overwrite a newer host update event', async () => { + let publishUpdate: ((event: { payload: AvailablePluginUpdate[] }) => void) | undefined; + listenMock.mockImplementation(async (event: string, callback: (event: { payload: AvailablePluginUpdate[] }) => void) => { + if (event === 'plugin:update-available') publishUpdate = callback; + return () => { publishUpdate = undefined; }; }); + Object.defineProperty(window, '__TAURI_INTERNALS__', { value: {}, configurable: true }); - const card = await screen.findByRole('article', { name: 'Epic Games Store' }); - expect(card.className).toContain('border-warning'); - const strip = within(card).getByRole('button', { - name: "This store's session expired. Sign in again in Stores.", + vi.spyOn(commands, 'pluginInventory').mockResolvedValue([plugin]); + vi.spyOn(commands, 'pluginUpdatePreferences').mockResolvedValue({ periodicChecks: false }); + vi.spyOn(commands, 'pluginUpdateAvailable').mockResolvedValue([]); + let finishCheck!: (updates: AvailablePluginUpdate[]) => void; + vi.spyOn(commands, 'pluginUpdateCheck').mockImplementation(() => new Promise((resolve) => { + finishCheck = resolve; + })); + renderInventory(); + + const checkButton = await screen.findByRole('button', { name: 'Check for updates now' }); + await waitFor(() => expect(publishUpdate).toBeDefined()); + fireEvent.click(checkButton); + await waitFor(() => expect(commands.pluginUpdateCheck).toHaveBeenCalled()); + + const newest: AvailablePluginUpdate[] = [{ + pluginId: plugin.pluginId, name: plugin.name, installedVersion: '1.0.0', versions: ['3.0.0'], + }]; + act(() => publishUpdate?.({ payload: newest })); + expect(await screen.findByRole('button', { name: 'Review version 3.0.0' })).toBeInTheDocument(); + + await act(async () => { + finishCheck([{ ...newest[0], versions: ['2.0.0'] }]); }); - fireEvent.click(strip); + expect(screen.getByRole('button', { name: 'Review version 3.0.0' })).toBeInTheDocument(); + expect(screen.queryByRole('button', { name: 'Review version 2.0.0' })).not.toBeInTheDocument(); + }); - expect(uiStore.state.settingsTopic).toBe('stores'); + it('requires separate rollback and exact publisher fingerprint confirmations', async () => { + const fingerprint = `SHA256:${'a'.repeat(64)}`; + vi.spyOn(commands, 'pluginInventory').mockResolvedValue([plugin]); + vi.spyOn(commands, 'pluginRollbackAvailable').mockResolvedValue([{ + pluginId: 'org.example.update', name: 'Example update', activeVersion: '2.0.0', versions: ['1.0.0'], + }]); + vi.spyOn(commands, 'pluginRollbackReview').mockResolvedValue({ + pluginId: 'org.example.update', installedVersion: '2.0.0', candidateVersion: '1.0.0', + addedPermissions: [], removedPermissions: ['files.read'], changedPermissions: [], permissionChanges: [], + addedNativeAccess: [], removedNativeAccess: [], apiChanged: false, installedApi: '1.0.0 – 1.0.0', + candidateApi: '1.0.0 – 1.0.0', licenseChanged: false, installedLicense: 'MIT', candidateLicense: 'MIT', + installedLicenseFiles: [], candidateLicenseFiles: [], installedLicenseNotices: [], candidateLicenseNotices: [], + installedPlaytime: { identifiesGameplay: false, identifiesPauses: false, withoutPauseDetection: 'disabled' }, + candidatePlaytime: { identifiesGameplay: false, identifiesPauses: false, withoutPauseDetection: 'disabled' }, + playtimeChanged: false, + publisherChanged: true, installedPublisherKeyId: 'new-key', candidatePublisherKeyId: 'old-key', + publisherFingerprint: fingerprint, changedDataSchemas: [], preservesPriorData: true, isDowngrade: true, + requiresManualApproval: true, + }); + const retrust = vi.spyOn(commands, 'pluginUpdateRetrustPublisher').mockResolvedValue(undefined); + const approveRollback = vi.spyOn(commands, 'pluginRollbackApprove').mockResolvedValue('1.0.0'); + renderInventory(); + + fireEvent.click(await screen.findByRole('button', { name: 'Review rollback to 1.0.0' })); + await screen.findByRole('article', { name: 'Review plugin rollback' }); + const approve = screen.getByRole('button', { name: 'Confirm rollback' }); + expect(approve).toBeDisabled(); + fireEvent.click(screen.getByRole('checkbox', { name: /I understand this will activate/ })); + expect(approve).toBeDisabled(); + fireEvent.change(screen.getByRole('textbox', { name: /Type the new publisher fingerprint/ }), { + target: { value: fingerprint }, + }); + fireEvent.click(screen.getByRole('button', { name: 'Confirm publisher re-trust' })); + await waitFor(() => expect(retrust).toHaveBeenCalledWith('org.example.update', '1.0.0', fingerprint)); + await waitFor(() => expect(approve).toBeEnabled()); + fireEvent.click(approve); + await waitFor(() => expect(approveRollback).toHaveBeenCalledWith('org.example.update', '1.0.0', true)); }); + it('installs, enables immediately, and reports an activation failure without hiding the package', async () => { + const inventory = vi.spyOn(commands, 'pluginInventory').mockResolvedValue([]); + vi.spyOn(commands, 'pluginUpdatePreferences').mockResolvedValue({ periodicChecks: false }); + vi.spyOn(commands, 'pluginUpdateAvailable').mockResolvedValue([]); + vi.spyOn(commands, 'pluginPlaytimeInventory').mockResolvedValue([]); + const staged = { + token: 'activation-review', pluginId: 'org.example.launch', name: 'Launch', version: '1.0.0', + publisherKeyId: 'key-launch', publisherFingerprint: 'SHA256:launch', trust: 'trusted' as const, + license: 'MIT', licenseFiles: [], licenseNotices: [], permissionIds: [], + requestedPermissions: [], nativeAccess: [], + playtime: { identifiesGameplay: false, identifiesPauses: false, withoutPauseDetection: 'disabled' as const }, + compatibility: 'compatible' as const, + }; + vi.spyOn(commands, 'pluginImportReview').mockResolvedValue(staged); + const install = vi.spyOn(commands, 'pluginImportInstall').mockResolvedValue({ + pluginId: staged.pluginId, + activated: false, + activationError: 'activation failed: packaged provider executable could not start', + }); + renderInventory('en', 'account-import'); - it('reports a failed inventory load without losing the community note', async () => { - vi.spyOn(commands, 'pluginInventory').mockRejectedValue('offline'); - renderPlugins([]); + fireEvent.change(await screen.findByRole('textbox', { name: 'Path to signed bundle' }), { target: { value: '/packages/launch.zip' } }); + await userEvent.setup().type(screen.getByRole('textbox', { name: 'Path to signed bundle' }), '{Enter}'); + fireEvent.click(await screen.findByRole('button', { name: 'Accept, install and enable' })); - expect(await screen.findByRole('alert')).toHaveTextContent( - 'Plugin information could not be loaded.', - ); - expect( - screen.getByText( - "Community plugins aren't reviewed by GameNode. Only grant permissions that make sense.", - ), - ).toBeInTheDocument(); + await waitFor(() => expect(install).toHaveBeenCalledWith('activation-review', false, [])); + const alert = await screen.findByRole('alert'); + expect(alert).toHaveTextContent('Installed, but not activated'); + expect(alert).toHaveTextContent('org.example.launch'); + expect(alert).toHaveTextContent('packaged provider executable could not start'); + await waitFor(() => expect(inventory.mock.calls.length).toBeGreaterThan(1)); }); - it('localizes the filter, stopped session and permissions in pt-BR', async () => { - vi.spyOn(commands, 'pluginInventory').mockResolvedValue([ - { ...community, providerId: 'packagekit', name: 'Gerenciador de pacotes Linux' }, - ]); - renderPlugins([community], { locale: 'pt-BR' }); + it('renders folder and program approvals for a standalone plugin with its own identity', async () => { + const fingerprint = 'ab'.repeat(32); + const managed: PluginInfo = { + ...plugin, + pluginId: 'community.example.emulator', + pluginKind: 'extension', + source: 'community', + publisherFingerprint: fingerprint, + runtimeAvailable: true, + }; + vi.spyOn(commands, 'pluginInventory').mockResolvedValue([managed]); + const folders = vi.spyOn(commands, 'pluginFolderApprovals').mockResolvedValue([]); + const runtimes = vi.spyOn(commands, 'pluginRuntimeApprovals').mockResolvedValue([]); + renderInventory('en', 'account-one'); - expect( - await screen.findByRole('radiogroup', { name: 'Filtrar por origem' }), - ).toBeInTheDocument(); - expect(screen.getByRole('radio', { name: 'Todos · 1' })).toBeInTheDocument(); - expect(screen.getByText('Parada')).toBeInTheDocument(); - expect(screen.getByText('Permissões')).toBeInTheDocument(); - expect(screen.getByText('Arquivos')).toBeInTheDocument(); - expect(screen.getByText('D-Bus')).toBeInTheDocument(); + expect(await screen.findByRole('region', { name: 'Folder access and library roots' })).toBeInTheDocument(); + expect(await screen.findByRole('region', { name: 'Approved runtime programs' })).toBeInTheDocument(); + await waitFor(() => expect(folders).toHaveBeenCalledWith(managed.pluginId, fingerprint)); + expect(runtimes).toHaveBeenCalledWith(managed.pluginId, fingerprint); }); + }); diff --git a/ui/src/features/settings/PluginInventory.tsx b/ui/src/features/settings/PluginInventory.tsx index f9ccdef1d..b3324dd32 100644 --- a/ui/src/features/settings/PluginInventory.tsx +++ b/ui/src/features/settings/PluginInventory.tsx @@ -1,9 +1,1304 @@ -/** - * Compatibility wrapper: the redesigned Plugins topic lives in - * `panels/PluginsPanel.tsx`. Keep this export for callers that still import the - * inventory by its old name. - */ -export { - PluginsPanel as PluginInventory, - PLUGIN_INVENTORY_QUERY_KEY, -} from './panels/PluginsPanel'; +import { providerLabel } from '../../i18n/providerLabel'; +import React, { useEffect, useMemo, useRef, useState } from 'react'; +import { useQuery, useQueryClient } from '@tanstack/react-query'; +import { listen, type UnlistenFn } from '@tauri-apps/api/event'; +import { open } from '@tauri-apps/plugin-dialog'; +import { useAuth } from '../../api/useSnapshot'; +import { commands, isTauriRuntime, type AvailablePluginUpdate, type BundleUninstallOutcome, type ExtensionReadinessSelection, type PluginBundleImportReview, type PluginImportReview, type PluginInfo, type PluginPermissionSnapshot, type PluginPlaytimeInfo, type PluginSharedDataSnapshot, type PluginUpdateReview } from '../../api'; +import { AppModal } from '../../components/AppModal'; +import { pluginQueryKeys } from '../../api/pluginQueryKeys'; +import { useI18n } from '../../i18n'; +import { RememberedConfirmations } from './RememberedConfirmations'; +import { PluginBundleDetails } from './PluginBundleDetails'; +import { PluginFolderApprovals } from './PluginFolderApprovals'; +import { PluginRuntimeApprovals } from './PluginRuntimeApprovals'; +import { PluginSharedResources } from './PluginSharedResources'; +import { PluginDurableUsage } from './PluginDurableUsage'; +import { PluginCompatibilityReview } from './PluginCompatibilityReview'; +import { PluginImportPermissions } from './PluginImportPermissions'; +import { + deniedPermissionIds, + importPlatformLabel, + type ImportPermissionDecisions, +} from './pluginImportReview'; +import { selectPluginConfiguration } from '../../api/pluginSettings'; +import { PluginConfigurationSurface } from './PluginConfigurationSurface'; +import { + PluginActivationPermissions, + type PluginActivationPermissionsValue, +} from './PluginActivationPermissions'; +import { + settingsCard, + settingsPill, + settingsPillSuccess, + settingsPillWarning, + settingsRowDescription, + settingsRowTitle, +} from './settingsClasses'; + +function statusLabel(status: PluginInfo['status'], t: (key: string) => string): string { + return t(`plugins.status.${status}`); +} + +function scopeChoiceKey(snapshot: PluginPermissionSnapshot, permissionId: string, scope: unknown): string { + return JSON.stringify([snapshot.pluginId, snapshot.publisherFingerprint, snapshot.profileId, snapshot.grantRevision, permissionId, scope]); +} + +interface PluginInventoryProps { + renderCards?: (options: { + selectedPluginId: string | null; + selectPlugin: (pluginId: string | null) => void; + details: React.ReactNode; + }) => React.ReactNode; +} + +export const PluginInventory: React.FC = ({ renderCards }) => { + const { t } = useI18n(); + const queryClient = useQueryClient(); + const [selectedPluginId, setSelectedPluginId] = useState(null); + const [review, setReview] = useState(null); + const [importReview, setImportReview] = useState(null); + const [bundleReview, setBundleReview] = useState(null); + const [bundleUninstallOutcome, setBundleUninstallOutcome] = useState(null); + const [bundleUninstallError, setBundleUninstallError] = useState(false); + const [nativeCodeConsent, setNativeCodeConsent] = useState(false); + const [bundleNativeConsent, setBundleNativeConsent] = useState(false); + const [licenseText, setLicenseText] = useState>({}); + const [archivePath, setArchivePath] = useState(''); + const [pickerError, setPickerError] = useState(false); + const [importPermissionDecisions, setImportPermissionDecisions] = + useState({}); + const [bundlePermissionDecisions, setBundlePermissionDecisions] = + useState>({}); + const [scopeChoices, setScopeChoices] = useState>({}); + const [confirmRemove, setConfirmRemove] = useState(false); + const [deletePluginData, setDeletePluginData] = useState(false); + const [confirmRemoveBundle, setConfirmRemoveBundle] = useState(false); + const [deleteBundleData, setDeleteBundleData] = useState(false); + const [busy, setBusy] = useState(false); + const [updateError, setUpdateError] = useState(false); + const [updateOperation, setUpdateOperation] = useState<'check' | 'review' | 'trust' | 'approve' | 'decline' | null>(null); + const [activationResult, setActivationResult] = useState< + { version: string; rollback: boolean; failed: false } | + { version: string | undefined; reason: string; failed: true } | null + >(null); + const [managementError, setManagementError] = useState(false); + const [activationFailures, setActivationFailures] = useState< + Array<{ pluginId: string; error: string }> + >([]); + const [savingPreferences, setSavingPreferences] = useState(false); + const [playtimeError, setPlaytimeError] = useState(false); + const updateEventRevision = useRef(0); + const auth = useAuth().auth; + const profileId = typeof auth === 'object' && auth !== null && 'signedIn' in auth + ? auth.signedIn.user.id + : null; + const [choosingReadinessTarget, setChoosingReadinessTarget] = useState(false); + const [readinessTargetId, setReadinessTargetId] = useState(''); + const [reviewIsRollback, setReviewIsRollback] = useState(false); + const [rollbackConfirmed, setRollbackConfirmed] = useState(false); + const [retrustFingerprint, setRetrustFingerprint] = useState(''); + const [publisherRetrusted, setPublisherRetrusted] = useState(false); + const [reviewingPluginId, setReviewingPluginId] = useState(null); + const { data: updatePreferences } = useQuery({ + queryKey: pluginQueryKeys.updatePreferences, + queryFn: commands.pluginUpdatePreferences, + }); + const { data: updates = [] } = useQuery({ + queryKey: pluginQueryKeys.availableUpdates, + queryFn: async () => { + const eventRevisionAtStart = updateEventRevision.current; + const available = await commands.pluginUpdateAvailable(); + return eventRevisionAtStart === updateEventRevision.current + ? available + : queryClient.getQueryData(pluginQueryKeys.availableUpdates) ?? available; + }, + }); + const { data = [], isPending, isError } = useQuery({ + queryKey: pluginQueryKeys.inventory, + queryFn: commands.pluginInventory, + staleTime: 30_000, + }); + const { + data: playtimePlugins = [], + isPending: playtimePending, + isError: playtimeInventoryError, + refetch: refetchPlaytimePlugins, + } = useQuery({ + queryKey: ['plugin-playtime-accounting'], + queryFn: commands.pluginPlaytimeInventory, + staleTime: 30_000, + }); + const selectedPlugin = data.find((plugin) => plugin.pluginId === selectedPluginId) ?? (renderCards ? undefined : data[0]); + const isBundle = selectedPlugin?.pluginKind === 'bundle'; + const { data: rollbackPackages = [], refetch: refetchRollbacks } = useQuery({ + queryKey: ['plugin-rollback-available'], + queryFn: commands.pluginRollbackAvailable, + }); + const managedPluginId = selectedPlugin?.publisherFingerprint ? selectedPlugin.pluginId : null; + const publisherFingerprint = selectedPlugin?.publisherFingerprint; + const { data: permissionSnapshot } = useQuery({ + queryKey: pluginQueryKeys.permissions(managedPluginId ?? '', profileId ?? '', publisherFingerprint), + queryFn: async () => { + if (!managedPluginId || !profileId) throw new Error('plugin permission profile is unavailable'); + const snapshot = await commands.pluginPermissionSnapshot(managedPluginId, profileId); + if (snapshot.publisherFingerprint !== publisherFingerprint) throw new Error('plugin permission publisher changed'); + return snapshot; + }, + enabled: managedPluginId !== null && profileId !== null, + }); + useQuery({ + queryKey: pluginQueryKeys.configuration(managedPluginId ?? ''), + queryFn: () => commands.pluginConfigurationState(managedPluginId!), + enabled: managedPluginId !== null, + }); + const { data: sharedDataSnapshot, isError: sharedDataError } = useQuery({ + queryKey: pluginQueryKeys.sharedData(managedPluginId ?? '', profileId ?? '', publisherFingerprint), + queryFn: async () => { + if (!managedPluginId || !profileId) throw new Error('plugin data-sharing profile is unavailable'); + const snapshot = await commands.pluginSharedDataSnapshot(managedPluginId, profileId); + if (snapshot.profileId !== profileId) throw new Error('plugin data-sharing profile changed'); + if (snapshot.publisherFingerprint !== publisherFingerprint) throw new Error('plugin data-sharing publisher changed'); + return snapshot; + }, + enabled: managedPluginId !== null && profileId !== null && selectedPlugin?.pluginKind === 'provider', + }); + const periodicChecks = updatePreferences?.periodicChecks ?? false; + const managed = Boolean(selectedPlugin?.publisherFingerprint) && !isBundle; + const canManageRuntime = managed && selectedPlugin?.runtimeAvailable === true && profileId !== null; + const canManageAccount = managed && profileId !== null; + const configurationQuery = useQuery({ + queryKey: ['plugin-configuration-modes', selectedPlugin?.providerId], + queryFn: () => commands.pluginConfigurationModes(selectedPlugin!.providerId), + enabled: Boolean(selectedPlugin && !isBundle && selectedPlugin.status === 'installed' && selectedPlugin.session === 'active'), + staleTime: 5_000, + }); + const configurationModes = configurationQuery.data; + const configurationChoice = configurationModes ? selectPluginConfiguration(configurationModes) : undefined; + const sharedDataInitialValue = useMemo(() => sharedDataSnapshot ? ({ + commonDataRead: sharedDataSnapshot.commonCategories, + selectedRecordIds: sharedDataSnapshot.selectedRecordIds, + sourcePolicies: sharedDataSnapshot.sourcePolicies, + }) : undefined, [sharedDataSnapshot]); + + + useEffect(() => { + if (!isTauriRuntime()) return undefined; + let active = true; + let unlisten: UnlistenFn | undefined; + void listen('plugin:update-available', (event) => { + const eventRevision = ++updateEventRevision.current; + void queryClient.cancelQueries({ queryKey: pluginQueryKeys.availableUpdates }).then(() => { + if (eventRevision === updateEventRevision.current) { + queryClient.setQueryData(pluginQueryKeys.availableUpdates, event.payload); + } + }); + }).then((dispose) => { + if (active) unlisten = dispose; + else dispose(); + }); + return () => { + active = false; + unlisten?.(); + }; + }, [queryClient]); + + const refreshPluginHostState = async (pluginId?: string) => { + const refreshes = [ + queryClient.invalidateQueries({ queryKey: pluginQueryKeys.inventory }), + queryClient.invalidateQueries({ queryKey: pluginQueryKeys.availableUpdates }), + queryClient.invalidateQueries({ queryKey: ['plugin-playtime-accounting'] }), + ]; + if (pluginId) { + if (profileId) { + refreshes.push(queryClient.invalidateQueries({ queryKey: pluginQueryKeys.permissions(pluginId, profileId) })); + refreshes.push(queryClient.invalidateQueries({ queryKey: pluginQueryKeys.sharedData(pluginId, profileId) })); + refreshes.push(queryClient.invalidateQueries({ queryKey: pluginQueryKeys.durableUsage(pluginId, profileId) })); + } + refreshes.push(queryClient.invalidateQueries({ queryKey: pluginQueryKeys.configuration(pluginId) })); + } + await Promise.all(refreshes); + }; + + const checkUpdates = async () => { + setUpdateOperation('check'); + setActivationResult(null); + setUpdateError(false); + const eventRevisionAtStart = updateEventRevision.current; + try { + const available = await commands.pluginUpdateCheck(); + if (eventRevisionAtStart === updateEventRevision.current) { + queryClient.setQueryData(pluginQueryKeys.availableUpdates, available); + } + } + catch { setUpdateError(true); } + finally { setUpdateOperation(null); } + }; + + const reviewUpdate = async (pluginId: string, version: string) => { + setUpdateOperation('review'); + setActivationResult(null); + setUpdateError(false); + setReview(null); + setReviewIsRollback(false); + setRollbackConfirmed(false); + setPublisherRetrusted(false); + setRetrustFingerprint(''); + try { setReview(await commands.pluginUpdateReview(pluginId, version)); } + catch { setUpdateError(true); } + finally { setUpdateOperation(null); } + }; + + const reviewRollback = async (pluginId: string, version: string) => { + setUpdateOperation('review'); + setActivationResult(null); + setUpdateError(false); + setReview(null); + setReviewIsRollback(true); + setRollbackConfirmed(false); + setPublisherRetrusted(false); + setRetrustFingerprint(''); + try { setReview(await commands.pluginRollbackReview(pluginId, version)); } + catch { setUpdateError(true); } + finally { setUpdateOperation(null); } + }; + + const retrustPublisher = async () => { + if (!review || retrustFingerprint !== review.publisherFingerprint) return; + setUpdateOperation('trust'); + setActivationResult(null); + setUpdateError(false); + try { + await commands.pluginUpdateRetrustPublisher(review.pluginId, review.candidateVersion, retrustFingerprint); + setPublisherRetrusted(true); + } catch { setUpdateError(true); } + finally { setUpdateOperation(null); } + }; + + const readinessTarget = review?.extensionTargets?.find( + ({ selection }) => selection.installationId === readinessTargetId, + )?.selection; + const approveLabel = t(reviewIsRollback ? 'plugins.updates.rollbackApprove' : 'plugins.updates.approve'); + + const approveUpdate = async (target?: ExtensionReadinessSelection) => { + if (!review || (review.extensionTargets && !target)) return; + setUpdateOperation('approve'); + setActivationResult(null); + setUpdateError(false); + try { + let version: string; + if (reviewIsRollback) { + const args = [review.pluginId, review.candidateVersion, rollbackConfirmed] as const; + version = await (target ? commands.pluginRollbackApprove(...args, target) : commands.pluginRollbackApprove(...args)); + } else { + const args = [review.pluginId, review.candidateVersion] as const; + version = await (target ? commands.pluginUpdateApprove(...args, target) : commands.pluginUpdateApprove(...args)); + } + setActivationResult({ version, rollback: reviewIsRollback, failed: false }); + } catch (error) { + const reason = error instanceof Error ? error.message : typeof error === 'string' ? error : ''; + const active = await queryClient.fetchQuery({ + queryKey: pluginQueryKeys.inventory, + queryFn: commands.pluginInventory, + staleTime: 0, + }).catch(() => undefined); + setActivationResult({ failed: true, reason, version: active?.find((plugin) => plugin.pluginId === review.pluginId)?.version }); + } finally { + setChoosingReadinessTarget(false); + setReview(null); + setReviewIsRollback(false); + setRollbackConfirmed(false); + setPublisherRetrusted(false); + await Promise.all([refetchRollbacks(), refreshPluginHostState(review.pluginId)]); + setUpdateOperation(null); + } + }; + + const declineUpdate = async () => { + if (!review) return; + setChoosingReadinessTarget(false); + setUpdateOperation('decline'); + setActivationResult(null); + setUpdateError(false); + try { + await commands.pluginUpdateDecline(review.pluginId); + setReview(null); + } catch { + setUpdateError(true); + await queryClient.invalidateQueries({ queryKey: pluginQueryKeys.availableUpdates }); + } finally { setUpdateOperation(null); } + }; + + const reviewImport = async () => { + setBusy(true); + setManagementError(false); + setActivationFailures([]); + setImportReview(null); + setBundleReview(null); + setNativeCodeConsent(false); + setBundleNativeConsent(false); + setLicenseText({}); + setImportPermissionDecisions({}); + setBundlePermissionDecisions({}); + try { + const path = archivePath.trim(); + if (path.toLowerCase().endsWith('.gnbundle')) { + setBundleReview(await commands.pluginBundleImportReview(path)); + } else { + setImportReview(await commands.pluginImportReview(path)); + } + } + catch { setManagementError(true); } + finally { setBusy(false); } + }; + + const pickArchive = async () => { + if (busy) return; + setPickerError(false); + if (!isTauriRuntime()) return; + try { + const selected = await open({ + multiple: false, + directory: false, + title: t('plugins.import.chooseFileTitle'), + filters: [ + { + name: t('plugins.import.fileFilterBundle'), + extensions: ['gnbundle'], + }, + { + name: t('plugins.import.fileFilterPackage'), + extensions: ['gnplugin'], + }, + { + name: t('plugins.import.fileFilterAll'), + extensions: ['gnbundle', 'gnplugin'], + }, + ], + }); + if (typeof selected === 'string') setArchivePath(selected); + } catch { + setPickerError(true); + } + }; + + const confirmBundlePublisher = async () => { + if (!bundleReview) return; + setBusy(true); + setManagementError(false); + try { + setBundleReview(await commands.pluginBundleImportConfirmPublisher( + bundleReview.token, + bundleReview.bundle.publisherFingerprint, + )); + } catch { setManagementError(true); } + finally { setBusy(false); } + }; + + const installBundle = async () => { + if (!bundleReview) return; + setBusy(true); + setManagementError(false); + setActivationFailures([]); + try { + const componentDeniedPermissions = bundleReview.components.map((component) => ({ + pluginId: component.review.pluginId, + deniedPermissionIds: deniedPermissionIds( + component.review.requestedPermissions, + bundlePermissionDecisions[component.review.pluginId] ?? {}, + ), + })); + const outcome = await commands.pluginBundleImportInstall( + bundleReview.token, + bundleNativeConsent, + componentDeniedPermissions, + ); + setActivationFailures( + outcome.components + .filter((component) => component.active && !component.activated) + .map((component) => ({ + pluginId: component.pluginId, + error: component.activationError ?? '', + })), + ); + setBundleReview(null); + setBundleNativeConsent(false); + setBundlePermissionDecisions({}); + setArchivePath(''); + setSelectedPluginId(outcome.bundleId); + await refreshPluginHostState(); + } catch { setManagementError(true); } + finally { setBusy(false); } + }; + + const uninstallBundle = async () => { + if (!selectedPlugin?.bundleId) return; + setBusy(true); + setManagementError(false); + setBundleUninstallError(false); + setBundleUninstallOutcome(null); + try { + const outcome = await commands.pluginBundleUninstall(selectedPlugin.bundleId, deleteBundleData); + setBundleUninstallOutcome(outcome); + setConfirmRemoveBundle(false); + setDeleteBundleData(false); + if (outcome.failures.length === 0) setSelectedPluginId(null); + await refreshPluginHostState(); + } catch { + setBundleUninstallError(true); + setConfirmRemoveBundle(false); + await refreshPluginHostState(); + } finally { setBusy(false); } + }; + + const installImport = async () => { + if (!importReview) return; + setBusy(true); + setManagementError(false); + setActivationFailures([]); + try { + const outcome = await commands.pluginImportInstall( + importReview.token, + nativeCodeConsent, + deniedPermissionIds(importReview.requestedPermissions, importPermissionDecisions), + ); + setActivationFailures( + outcome.activated + ? [] + : [{ pluginId: outcome.pluginId, error: outcome.activationError ?? '' }], + ); + setImportReview(null); + setNativeCodeConsent(false); + setLicenseText({}); + setImportPermissionDecisions({}); + setArchivePath(''); + setSelectedPluginId(outcome.pluginId); + await refreshPluginHostState(outcome.pluginId); + } catch { setManagementError(true); } + finally { setBusy(false); } + }; + + const savePermissions = async (snapshot: PluginPermissionSnapshot) => { + if (!profileId || snapshot.pluginId !== managedPluginId || snapshot.publisherFingerprint !== publisherFingerprint) return; + const queryKey = pluginQueryKeys.permissions(snapshot.pluginId, profileId, snapshot.publisherFingerprint); + const decisions = snapshot.requestedPermissions.flatMap((request) => request.allowed_scopes.map((scope) => { + const key = scopeChoiceKey(snapshot, request.permission_id, scope); + const persisted = snapshot.effectiveGrants.some((grant) => grant.permission_id === request.permission_id && JSON.stringify(grant.scope) === JSON.stringify(scope) && grant.state === 'granted'); + return { permission_id: request.permission_id, scope, granted: scopeChoices[key] ?? persisted }; + })); + setBusy(true); + setManagementError(false); + try { + const saved = await commands.pluginPermissionsReplace(snapshot.pluginId, snapshot.profileId, snapshot.publisherFingerprint, snapshot.grantRevision, decisions); + setScopeChoices({}); + queryClient.setQueryData(queryKey, saved); + await queryClient.invalidateQueries({ queryKey: pluginQueryKeys.inventory }); + } catch { + setManagementError(true); + setScopeChoices({}); + await queryClient.invalidateQueries({ queryKey }); + } finally { setBusy(false); } + }; + + const saveSharedDataPermissions = async ( + snapshot: PluginSharedDataSnapshot, + value: PluginActivationPermissionsValue, + ) => { + if (!profileId || snapshot.profileId !== profileId || snapshot.pluginId !== managedPluginId || snapshot.publisherFingerprint !== publisherFingerprint) return; + const queryKey = pluginQueryKeys.sharedData(snapshot.pluginId, profileId, snapshot.publisherFingerprint); + setBusy(true); + setManagementError(false); + try { + const saved = await commands.pluginSharedDataReplace(snapshot.pluginId, { + profileId, + expectedPublisherFingerprint: snapshot.publisherFingerprint, + expectedRevision: snapshot.policyRevision, + commonCategories: value.commonDataRead, + selectedRecordIds: value.selectedRecordIds, + sourcePolicies: value.sourcePolicies, + }); + queryClient.setQueryData(queryKey, saved); + } catch { + setManagementError(true); + await queryClient.invalidateQueries({ queryKey }); + } finally { setBusy(false); } + }; + + const setPluginEnabled = async (pluginId: string, enabled: boolean) => { + setBusy(true); + setManagementError(false); + try { + if (enabled) await commands.pluginEnable(pluginId); + else await commands.pluginDisable(pluginId); + await refreshPluginHostState(pluginId); + } catch { + setManagementError(true); + await refreshPluginHostState(pluginId); + } finally { setBusy(false); } + }; + + const removePlugin = async () => { + if (!selectedPlugin) return; + setBusy(true); + setManagementError(false); + try { + await commands.pluginRemove(selectedPlugin.pluginId, deletePluginData); + setConfirmRemove(false); + setDeletePluginData(false); + setSelectedPluginId(null); + await refreshPluginHostState(selectedPlugin.pluginId); + } catch { + setManagementError(true); + await refreshPluginHostState(selectedPlugin.pluginId); + } finally { setBusy(false); } + }; + + const setPlaytimeAccounting = async (plugin: PluginPlaytimeInfo, enabled: boolean) => { + setPlaytimeError(false); + try { + await commands.pluginPlaytimeSetAccounting(plugin.pluginId, enabled); + await refetchPlaytimePlugins(); + } catch { + setPlaytimeError(true); + } + }; + + const stateClass = (status: PluginInfo['status']) => status === 'installed' + ? settingsPillSuccess + : status === 'missing' || status === 'failed' || status === 'incompatible' + ? settingsPillWarning + : settingsPill; + + const selectPlugin = (pluginId: string | null) => { + setScopeChoices({}); + setManagementError(false); + setSelectedPluginId(pluginId); + }; + + const details = selectedPlugin && (isBundle ? ( + <> + { + setBundleUninstallOutcome(null); + setBundleUninstallError(false); + setDeleteBundleData(false); + setConfirmRemoveBundle(true); + }} + uninstallOutcome={bundleUninstallOutcome} + uninstallError={bundleUninstallError} + /> + {(selectedPlugin.bundleComponents ?? []).map((component) => { + // A bundle itself has no approvals: each component owns its own namespace, and the + // bundle publisher authenticates every one of them. + const componentPublisher = selectedPlugin.bundlePublisherFingerprint + ?? selectedPlugin.publisherFingerprint + ?? component.publisherFingerprint; + if (!componentPublisher) return null; + return ( +
+

{component.name}

+

{t('plugins.bundle.approvalsDescription')}

+ + +
+ ); + })} + + ) : ( +
+ {!renderCards && <> +
+

{providerLabel(selectedPlugin.providerId, selectedPlugin.name, t)}

+ {selectedPlugin.source === 'official' ? t('plugins.official') : t('plugins.community')} + {statusLabel(selectedPlugin.status, t)} +
+

{t('plugins.identifier')}: {selectedPlugin.pluginId}

+

{t('plugins.session')}: {selectedPlugin.session === 'active' ? t('plugins.sessionActive') : t('plugins.sessionStopped')}

+ {managed && selectedPlugin.version &&

{t('plugins.import.version')}: {selectedPlugin.version}

} + } + {managed && selectedPlugin.compatibilityDetails && } + {managed && selectedPlugin.pluginKind === 'extension' && selectedPlugin.status !== 'incompatible' && selectedPlugin.runtimeAvailable !== true &&

{t('plugins.import.extensionRuntimeUnavailable')}

} + {managed && profileId === null &&

{t('plugins.signInRequired')}

} + {(canManageRuntime || canManageAccount) &&
+ {canManageRuntime && (selectedPlugin.enabled ? : )} + {canManageAccount && } +
} + {managed && profileId && permissionSnapshot && permissionSnapshot.pluginId === selectedPlugin.pluginId &&
+

{t('plugins.permissionScopes')}

+

{t('plugins.publisherFingerprint')}: {permissionSnapshot.publisherFingerprint}

+

{t('plugins.requestedGrantedEffectiveDescription')}

+ {permissionSnapshot.requestedPermissions.map((request) =>
+ {request.permission_id}{request.required ? ` · ${t('plugins.required')}` : ''} · {t('plugins.permissionRequested')} + {request.allowed_scopes.map((scope) => { + const key = scopeChoiceKey(permissionSnapshot, request.permission_id, scope); + const effective = permissionSnapshot.effectiveGrants.find((grant) => grant.permission_id === request.permission_id && JSON.stringify(grant.scope) === JSON.stringify(scope)); + const active = effective?.state === 'granted'; + return ; + })} +
)} + +
} + + {managed && selectedPlugin.pluginKind === 'provider' &&
+ + {reviewingPluginId === selectedPlugin.pluginId && ( +
+

+ {t('plugins.activation.reviewFor', { plugin: providerLabel(selectedPlugin.providerId, selectedPlugin.name, t) })} +

+ {sharedDataError &&

{t('plugins.management.failed')}

} + {sharedDataSnapshot && sharedDataInitialValue && sharedDataSnapshot.pluginId === selectedPlugin.pluginId ? ( + void saveSharedDataPermissions(sharedDataSnapshot, value)} + /> + ) :

{profileId ? t('plugins.activation.loading') : t('plugins.signInRequired')}

} +
+ )} +
} + + {!renderCards && <> +
+

{selectedPlugin.source === 'official' ? t('plugins.grants') : t('plugins.import.permissions')}

+
    + {selectedPlugin.capabilities.map((grant) => ( +
  • {grant}
  • + ))} +
+
+
+

{t('plugins.nativeAccess')}

+
    + {selectedPlugin.nativeAccess.map((access) => ( +
  • {t(`plugins.native.${access}`)}
  • + ))} +
+

{t('plugins.nativeAccessNote')}

+
+ } +
+ +
+ {selectedPlugin.publisherFingerprint && ( + <> + {selectedPlugin.pluginKind === 'provider' && ( + + )} + + + + + + )} +
+ )); + + return ( +
+ {!renderCards &&

{t('plugins.inventoryDescription')}

} +
+
{ event.preventDefault(); void reviewImport(); }}> +
+ +

{t('plugins.import.description')}

+
+ setArchivePath(event.currentTarget.value)} placeholder={t('plugins.import.path')} aria-label={t('plugins.import.path')} /> + +
+ {pickerError &&

{t('plugins.import.pickFailed')}

} +
+ {profileId === null &&

{t('plugins.signInRequired')}

} + +
+ {importReview &&
+
+
+

{importReview.name} {importReview.version}

+ + {t(`plugins.import.${importReview.compatibility}`)} + +
+

{t('plugins.import.fingerprint')}: {importReview.publisherFingerprint}

+ {importReview.pinnedFingerprint &&

{t('plugins.import.previousFingerprint')}: {importReview.pinnedFingerprint}

} +

{t('plugins.import.license')}: {importReview.license}

+ {(importReview.supportedPlatforms?.length ?? 0) > 0 && ( +

+ {t('plugins.import.platforms')}: {(importReview.supportedPlatforms ?? []).map((platform) => importPlatformLabel(platform, t)).join(', ')} +

+ )} +
+
+

{t('plugins.import.permissions')}

+ +
+
+

{t('plugins.nativeAccess')}: {importReview.nativeAccess.join(', ') || '—'}

+ {importReview.nativeAccess.length > 0 && } +
+ {importReview.trust !== 'trusted' ? :

{t('plugins.import.publisherTrusted')}

} +
+ {t('plugins.import.technicalDetails')} +
+

{t('plugins.identifier')}: {importReview.pluginId}

+

{t('plugins.import.compatibility')}: {t(`plugins.import.${importReview.compatibility}`)} {importReview.compatibilityReason ?? ''}

+ {importReview.compatibilityDetails && } +
+

{t('plugins.import.playtimeDisclosure')}

+

{t('plugins.playtime.gameplayDetection')}: {importReview.playtime.identifiesGameplay ? t('plugins.playtime.yes') : t('plugins.playtime.no')}

+

{t('plugins.playtime.pauseDetection')}: {importReview.playtime.identifiesPauses ? t('plugins.playtime.yes') : t('plugins.playtime.no')}

+

{t('plugins.playtime.modeLabel')}: {t(`plugins.playtime.mode.${importReview.playtime.withoutPauseDetection}`)}

+ {importReview.playtime.identifiesGameplay && !importReview.playtime.identifiesPauses && importReview.playtime.withoutPauseDetection === 'application_open' && ( +

{t('plugins.playtime.applicationOpenWarning')}

+ )} +
+ {[...new Set([...importReview.licenseFiles, ...importReview.licenseNotices])].map((file) => ( +
+ {file} + {licenseText[file] === undefined ? :
{licenseText[file]}
} +
+ ))} +
+
+ +
} + {bundleReview &&
+
+

+ {bundleReview.bundle.name} {bundleReview.bundle.version} +

+

+ {t('plugins.import.fingerprint')}: {bundleReview.bundle.publisherFingerprint} +

+ {bundleReview.pinnedFingerprint && ( +

+ {t('plugins.import.previousFingerprint')}: {bundleReview.pinnedFingerprint} +

+ )} +

+ {t('plugins.import.license')}: {bundleReview.license.expressions.join(', ') || '—'} +

+
+

{t('plugins.bundle.reviewDescription')}

+
    + {bundleReview.components.map((component) => { + const license = bundleReview.license.components.find( + (entry) => entry.pluginId === component.review.pluginId, + ); + return ( +
  • +
    +

    {component.review.name}

    + {t(`plugins.bundle.kind.${component.kind}`)} + {component.review.version} + + {t(`plugins.bundle.availability.${component.availability.status}`)} + + + {t(`plugins.import.${component.review.compatibility}`)} + +
    + {(component.review.supportedPlatforms?.length ?? 0) > 0 && ( +

    + {t('plugins.import.platforms')}: {(component.review.supportedPlatforms ?? []).map((platform) => importPlatformLabel(platform, t)).join(', ')} +

    + )} + {component.availability.status === 'unavailable' && ( +

    + {t(`plugins.bundle.unavailable.${component.availability.reason}`)} +

    + )} +
    +

    + {t('plugins.bundle.permissionsFor', { name: component.review.name })} +

    + setBundlePermissionDecisions((current) => ({ + ...current, + [component.review.pluginId]: decisions, + }))} + disabled={busy || profileId === null} + ariaLabel={t('plugins.bundle.permissionsFor', { name: component.review.name })} + emptyLabel={t('plugins.bundle.noPermissions')} + /> +
    +
    + {t('plugins.import.technicalDetails')} +
    +

    {t('plugins.identifier')}: {component.review.pluginId}

    +

    {t('plugins.import.license')}: {component.review.license}

    +

    + {t('plugins.import.compatibility')}: {t(`plugins.import.${component.review.compatibility}`)} + {component.review.compatibilityReason ? ` ${component.review.compatibilityReason}` : ''} +

    + {component.review.compatibilityDetails && ( + + )} +

    + {t('plugins.nativeAccess')}: {component.review.nativeAccess.join(', ') || '—'} +

    + {license && (license.files.length > 0 || license.notices.length > 0) && ( +

    + {t('plugins.import.licenseFilesLabel')}: {[...license.files, ...license.notices].join(', ')} +

    + )} +
    +
    +
  • + ); + })} +
+
+ {t('plugins.import.technicalDetails')} +
+

{t('plugins.bundle.identifier')}: {bundleReview.bundle.id}

+ {bundleReview.license.components.map((component) => ( +

+ {component.pluginId}: {component.expression} + {component.files.length > 0 ? ` · ${component.files.join(', ')}` : ''} + {component.notices.length > 0 ? ` · ${component.notices.join(', ')}` : ''} +

+ ))} +
+
+ {bundleReview.trust !== 'trusted' ? ( + + ) : ( +

+ {t('plugins.bundle.publisherConfirmed')} +

+ )} +
+ {bundleReview.components.some((component) => component.review.nativeAccess.length > 0) && ( + + )} + +
+
} +
+ {activationFailures.length > 0 && ( +
+

{t('plugins.import.activationPartial')}

+
    + {activationFailures.map((failure) => ( +
  • + {failure.pluginId} + {failure.error ? `: ${failure.error}` : ''} +
  • + ))} +
+
+ )} +
+

{t('plugins.updates.description')}

+ + + {updates.map((update) => ( +
+

{update.name}: {update.installedVersion}

+
+ {update.versions.map((version) => ( + + ))} +
+
+ ))} + {rollbackPackages.map((pkg) => ( +
+

{t('plugins.updates.rollbackTitle')}: {pkg.name} ({pkg.activeVersion})

+

{t('plugins.updates.rollbackDescription')}

+
+ {pkg.versions.map((version) => ( + + ))} +
+
+ ))} + {updateOperation && updateOperation !== 'check' && ( +

{t('plugins.updates.working')}

+ )} + {updateError &&

{t('plugins.updates.failed')}

} + {activationResult && (activationResult.failed ? ( +
+

{t('plugins.updates.activationFailed')}

+

{activationResult.version + ? t('plugins.updates.activeVersion', { version: activationResult.version }) + : t('plugins.updates.activeVersionUnavailable')}

+ {activationResult.reason &&

{activationResult.reason}

} +
+ ) : ( +

{t(activationResult.rollback ? 'plugins.updates.rollbackComplete' : 'plugins.updates.updateComplete', { version: activationResult.version })}

+ ))} + {review && ( +
+

{reviewIsRollback ? t('plugins.updates.rollbackReviewTitle') : t('plugins.updates.reviewTitle')}: {review.installedVersion} → {review.candidateVersion}

+ {review.compatibilityDetails && } + {reviewIsRollback && ( + + )} +

{t('plugins.grants')}: +{review.addedPermissions.join(', ') || '—'}; {t('plugins.updates.changed')}: {review.changedPermissions.join(', ') || '—'}; −{review.removedPermissions.join(', ') || '—'}

+ {review.permissionChanges.map((change) =>

{change.id}: {change.installedScope} → {change.candidateScope}

)} +

{t('plugins.nativeAccess')}: +{review.addedNativeAccess.join(', ') || '—'}; −{review.removedNativeAccess.join(', ') || '—'}

+

{t('plugins.updates.api')}: {review.installedApi} → {review.candidateApi}

+

{t('plugins.updates.license')}: {review.installedLicense} → {review.candidateLicense}

+

{t('plugins.updates.licenseFiles')}: {review.installedLicenseFiles.join(', ') || '—'} → {review.candidateLicenseFiles.join(', ') || '—'}

+

{t('plugins.updates.licenseNotices')}: {review.installedLicenseNotices.join('; ') || '—'} → {review.candidateLicenseNotices.join('; ') || '—'}

+

{t('plugins.updates.publisher')}: {review.installedPublisherKeyId} → {review.candidatePublisherKeyId}

+ {review.publisherChanged && ( +
+

{t('plugins.updates.publisherChanged')}: {review.installedPublisherKeyId} → {review.candidatePublisherKeyId}

+

{t('plugins.updates.publisherFingerprint')}: {review.publisherFingerprint}

+ {!publisherRetrusted ? ( +
+ setRetrustFingerprint(event.currentTarget.value)} /> + +
+ ) :

{t('plugins.updates.publisherRetrusted')}

} +
+ )} + {review.playtimeChanged &&

{t('plugins.playtime.updatePolicy')}: {t(`plugins.playtime.mode.${review.installedPlaytime.withoutPauseDetection}`)} → {t(`plugins.playtime.mode.${review.candidatePlaytime.withoutPauseDetection}`)}

} +

{t('plugins.updates.dataPreserved')}

+ {review.changedDataSchemas.length > 0 &&

{t('plugins.updates.dataSchemaChanged')}: {review.changedDataSchemas.join(', ')}. {t('plugins.updates.versionedDataKeysRequired')}

} +

{t('plugins.updates.newPermissionsDenied')}

+
+ + +
+
+ )} +
+ {managementError &&

{t('plugins.management.failed')}

} + {renderCards ? renderCards({ selectedPluginId, selectPlugin, details }) : isPending ? ( +
+

{t('plugins.loading')}

+
+ ) : isError ? ( +
+

{t('plugins.loadFailed')}

+
+ ) : data.length === 0 ? ( +
+

{t('plugins.empty')}

+
+ ) : ( +
+
+ {data.map((plugin) => ( + + ))} +
+ {details} +
+ )} + void declineUpdate()} closeOnEscape={updateOperation === null} closeOnClickOutside={updateOperation === null}> + + + + {t('plugins.updates.chooseTarget')} + + + +

{t('plugins.updates.targetDescription')}

+ {review?.extensionTargets?.length ? ( + + ) :

{t('plugins.updates.noTargets')}

} +
+ + +
+
+
+
+ + setConfirmRemove(false)}> + + + + {t('plugins.remove')} + + + +

{t('plugins.removeConfirm')}

+
+ {t('plugins.bundle.retention.title')} + + +
+
+ + +
+
+
+
+ setConfirmRemoveBundle(false)}> + + + + {t('plugins.bundle.uninstall')} + + + +

{t('plugins.bundle.uninstallConfirm')}

+
+ {t('plugins.bundle.retention.title')} + + +
+
+ + +
+
+
+
+
+

{t('plugins.playtime.description')}

+ {playtimePending ? ( +

{t('plugins.loading')}

+ ) : playtimeInventoryError ? ( +

{t('plugins.playtime.loadFailed')}

+ ) : playtimePlugins.length === 0 ? ( +

{t('plugins.playtime.empty')}

+ ) : ( +
+ {playtimePlugins.map((plugin) => ( +
+

{plugin.name}

+

{plugin.pluginId} · {plugin.version}

+

{t('plugins.playtime.gameplayDetection')}: {plugin.playtime.identifiesGameplay ? t('plugins.playtime.yes') : t('plugins.playtime.no')}

+

{t('plugins.playtime.pauseDetection')}: {plugin.playtime.identifiesPauses ? t('plugins.playtime.yes') : t('plugins.playtime.no')}

+

{t('plugins.playtime.modeLabel')}: {t(`plugins.playtime.mode.${plugin.playtime.withoutPauseDetection}`)}

+ {plugin.playtime.identifiesGameplay && !plugin.playtime.identifiesPauses && plugin.playtime.withoutPauseDetection === 'application_open' && ( +

{t('plugins.playtime.applicationOpenWarning')}

+ )} + +
+ ))} +
+ )} + {playtimeError &&

{t('plugins.playtime.saveFailed')}

} +
+
+ ); +}; diff --git a/ui/src/features/settings/PluginRuntimeApprovals.test.tsx b/ui/src/features/settings/PluginRuntimeApprovals.test.tsx new file mode 100644 index 000000000..9ae630f87 --- /dev/null +++ b/ui/src/features/settings/PluginRuntimeApprovals.test.tsx @@ -0,0 +1,89 @@ +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { MantineProvider } from '@mantine/core'; +import { appTheme } from '../../AppProviders'; +import { commands, type PluginRuntimeApproval } from '../../api'; +import { I18nProvider } from '../../i18n'; +import { PluginRuntimeApprovals } from './PluginRuntimeApprovals'; + +const publisher = 'ab'.repeat(32); +const approvals: PluginRuntimeApproval[] = [ + { + runtimeId: 'runtime-1', + path: 'C:\\Emulators\\Dolphin\\Dolphin.exe', + approvedAt: 1_760_000_000, + }, + { + runtimeId: 'runtime-2', + path: '/usr/bin/dolphin-emu', + approvedAt: 1_760_100_000, + }, +]; + +function renderPanel(locale = 'en') { + const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + return render( + + + + + + + , + ); +} + +describe('PluginRuntimeApprovals', () => { + beforeEach(() => { + vi.spyOn(commands, 'pluginRuntimeApprovals').mockResolvedValue(approvals); + vi.spyOn(commands, 'pluginRuntimeRevoke').mockResolvedValue(true); + }); + afterEach(() => vi.restoreAllMocks()); + + it.each([ + ['en', 'Approved runtime programs', /Remove approval for/, /Approved .*2025/], + ['pt-BR', 'Programas de runtime aprovados', /Remover aprovação de/, /Aprovado em .*2025/], + ])('lists approved programs with a Remove action in %s', async (locale, heading, remove, date) => { + renderPanel(locale); + + expect(await screen.findByRole('region', { name: heading })).toBeInTheDocument(); + expect(await screen.findByText('C:\\Emulators\\Dolphin\\Dolphin.exe')).toBeInTheDocument(); + expect(screen.getByText('/usr/bin/dolphin-emu')).toBeInTheDocument(); + expect(screen.getAllByText(date).length).toBeGreaterThan(0); + expect(screen.getByText(/ask for a new program|pedir um novo programa/)).toBeInTheDocument(); + + fireEvent.click(screen.getAllByRole('button', { name: remove })[0]); + await waitFor(() => expect(commands.pluginRuntimeRevoke).toHaveBeenCalledWith( + 'community.example', publisher, 'runtime-1', + )); + }); + + it('shows the empty state without a Remove action', async () => { + vi.spyOn(commands, 'pluginRuntimeApprovals').mockResolvedValue([]); + renderPanel('en'); + + expect(await screen.findByText('This plugin has no approved runtime programs.')).toBeInTheDocument(); + expect(screen.queryByRole('button', { name: /Remove approval for/ })).not.toBeInTheDocument(); + }); + + it('reports a failed revocation without hiding the saved approval', async () => { + vi.spyOn(commands, 'pluginRuntimeRevoke').mockRejectedValue(new Error('storage failed')); + renderPanel('en'); + + fireEvent.click((await screen.findAllByRole('button', { name: /Remove approval for/ }))[0]); + expect(await screen.findByRole('alert')).toHaveTextContent( + 'Could not update this program approval.', + ); + expect(screen.getByText('/usr/bin/dolphin-emu')).toBeInTheDocument(); + }); + + it('reports a failed list request', async () => { + vi.spyOn(commands, 'pluginRuntimeApprovals').mockRejectedValue(new Error('storage failed')); + renderPanel('en'); + + expect(await screen.findByRole('alert')).toHaveTextContent( + 'Could not update this program approval.', + ); + }); +}); diff --git a/ui/src/features/settings/PluginRuntimeApprovals.tsx b/ui/src/features/settings/PluginRuntimeApprovals.tsx new file mode 100644 index 000000000..c2d21faf7 --- /dev/null +++ b/ui/src/features/settings/PluginRuntimeApprovals.tsx @@ -0,0 +1,67 @@ +import React, { useState } from 'react'; +import { useQuery, useQueryClient } from '@tanstack/react-query'; +import { commands, type PluginRuntimeApproval } from '../../api'; +import { useI18n } from '../../i18n'; +import { settingsButtonSecondary, settingsRowDescription, settingsRowTitle } from './settingsClasses'; + +const queryKey = (pluginId: string, publisher: string) => ['plugin-runtime-approvals', pluginId, publisher] as const; + +export const PluginRuntimeApprovals: React.FC<{ pluginId: string; publisherFingerprint: string }> = ({ + pluginId, + publisherFingerprint, +}) => { + const { t, locale } = useI18n(); + const client = useQueryClient(); + const [busy, setBusy] = useState(null); + const [error, setError] = useState(false); + const { data = [], isPending, isError } = useQuery({ + queryKey: queryKey(pluginId, publisherFingerprint), + queryFn: () => commands.pluginRuntimeApprovals(pluginId, publisherFingerprint), + }); + + const refresh = async () => client.invalidateQueries({ queryKey: queryKey(pluginId, publisherFingerprint) }); + const revoke = async (approval: PluginRuntimeApproval) => { + setBusy(approval.runtimeId); setError(false); + try { + await commands.pluginRuntimeRevoke(pluginId, publisherFingerprint, approval.runtimeId); + await refresh(); + } catch { setError(true); } + finally { setBusy(null); } + }; + + return ( +
+

{t('plugins.runtimeApprovals.title')}

+

{t('plugins.runtimeApprovals.disclosure')}

+ {isPending &&

{t('plugins.runtimeApprovals.loading')}

} + {(isError || error) &&

{t('plugins.runtimeApprovals.error')}

} + {!isPending && !isError && data.length === 0 &&

{t('plugins.runtimeApprovals.empty')}

} +
    + {data.map((approval) => ( +
  • +

    {approval.path}

    +

    + {t('plugins.runtimeApprovals.approvedAt', { + date: new Intl.DateTimeFormat(locale, { dateStyle: 'medium' }) + .format(new Date(approval.approvedAt * 1000)), + })} +

    +
    + +
    +
  • + ))} +
+
+ ); +}; diff --git a/ui/src/features/settings/PluginSharedResources.test.tsx b/ui/src/features/settings/PluginSharedResources.test.tsx new file mode 100644 index 000000000..d75c518e0 --- /dev/null +++ b/ui/src/features/settings/PluginSharedResources.test.tsx @@ -0,0 +1,93 @@ +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { MantineProvider } from '@mantine/core'; +import { appTheme } from '../../AppProviders'; +import { commands, type PluginSharedResourceReview } from '../../api'; +import { I18nProvider } from '../../i18n'; +import { PluginSharedResources } from './PluginSharedResources'; + +const publisher = 'ab'.repeat(32); + +const reviews: PluginSharedResourceReview[] = [ + { + pluginId: 'community.example', publisherFingerprint: publisher, profileId: 'profile-a', + profileName: 'Dolphin card', gameId: '3', installationId: 'id-fixture:3', runtimeId: 'org.dolphin', + resourceId: 'memory-card', displayName: 'Memory card', + affectedGames: [ + { installationId: 'id-fixture:3', gameId: '3', name: 'Card A' }, + { installationId: 'id-fixture:4', gameId: '4', name: 'Card B' }, + ], + consent: 'pending', unavailable: false, + }, + { + pluginId: 'community.example', publisherFingerprint: publisher, profileId: 'profile-b', + profileName: 'Shared memory', gameId: '5', installationId: 'id-fixture:5', runtimeId: 'org.dolphin', + resourceId: 'shared-mem', displayName: 'Shared memory', affectedGames: [ + { installationId: 'id-fixture:5', gameId: '5', name: 'Card C' }, + ], + consent: 'current', unavailable: false, + }, + { + pluginId: 'community.example', publisherFingerprint: publisher, profileId: 'profile-c', + profileName: 'Lost card', gameId: '6', installationId: 'id-fixture:6', runtimeId: 'org.dolphin', + resourceId: 'lost', displayName: 'Lost card', affectedGames: [], + consent: 'stale', unavailable: true, + }, +]; + +function renderPanel(locale = 'en') { + const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + return render( + + + + + + + , + ); +} + +describe('PluginSharedResources', () => { + beforeEach(() => { + vi.spyOn(commands, 'pluginSharedResourceReviews').mockResolvedValue(reviews); + vi.spyOn(commands, 'pluginSharedResourceAccept').mockResolvedValue(undefined); + vi.spyOn(commands, 'pluginSharedResourceRevoke').mockResolvedValue(true); + }); + afterEach(() => vi.restoreAllMocks()); + + it.each([ + ['en', 'Shared emulator resources', 'Approve use', 'Revoke', 'Card A, Card B'], + ['pt-BR', 'Recursos de emulador compartilhados', 'Aprovar uso', 'Revogar', 'Card A, Card B'], + ])('shows the exact affected scope and separate review controls in %s', async (locale, heading, accept, revoke, games) => { + renderPanel(locale); + expect(await screen.findByRole('region', { name: heading })).toBeInTheDocument(); + expect(await screen.findByText(new RegExp(games))).toBeInTheDocument(); + expect(screen.getByText(new RegExp(locale === 'en' ? 'adding a game|new review' : 'adicionar um jogo|nova revisão', 'i'))).toBeInTheDocument(); + expect(screen.getByRole('note')).toHaveTextContent( + locale === 'en' ? 'cannot be resolved' : 'não pode ser resolvida', + ); + const approveButtons = screen.getAllByRole('button', { name: accept }); + expect(approveButtons[0]).toBeEnabled(); + const revokeButtons = screen.getAllByRole('button', { name: revoke }); + expect(revokeButtons[1]).toBeEnabled(); + + fireEvent.click(approveButtons[0]); + await waitFor(() => expect(commands.pluginSharedResourceAccept).toHaveBeenCalledWith( + 'community.example', publisher, 'profile-a', 'memory-card', + )); + + fireEvent.click(revokeButtons[1]); + await waitFor(() => expect(commands.pluginSharedResourceRevoke).toHaveBeenCalledWith( + 'community.example', publisher, 'profile-b', 'shared-mem', + )); + }); + + it('disables approval when the affected scope cannot be resolved', async () => { + renderPanel(); + await screen.findByRole('note'); + const approveButtons = screen.getAllByRole('button', { name: 'Approve use' }); + expect(approveButtons[approveButtons.length - 1]).toBeDisabled(); + }); +}); diff --git a/ui/src/features/settings/PluginSharedResources.tsx b/ui/src/features/settings/PluginSharedResources.tsx new file mode 100644 index 000000000..f824f2a28 --- /dev/null +++ b/ui/src/features/settings/PluginSharedResources.tsx @@ -0,0 +1,94 @@ +import React, { useState } from 'react'; +import { useQuery, useQueryClient } from '@tanstack/react-query'; +import { commands, type PluginSharedResourceReview } from '../../api'; +import { useI18n } from '../../i18n'; +import { settingsButtonSecondary, settingsRowDescription, settingsRowTitle } from './settingsClasses'; + +const queryKey = (pluginId: string, publisher: string) => + ['plugin-shared-resources', pluginId, publisher] as const; + +const reviewKey = (review: PluginSharedResourceReview) => `${review.profileId}:${review.resourceId}`; + +/** + * Reviews the shared emulator resources a plugin declared. The host resolves the backing folder + * and every affected game; this surface only accepts or forgets the exact resolved scope. + */ +export const PluginSharedResources: React.FC<{ pluginId: string; publisherFingerprint: string }> = ({ + pluginId, + publisherFingerprint, +}) => { + const { t } = useI18n(); + const client = useQueryClient(); + const [busy, setBusy] = useState(null); + const [error, setError] = useState(false); + const { data = [], isPending, isError } = useQuery({ + queryKey: queryKey(pluginId, publisherFingerprint), + queryFn: () => commands.pluginSharedResourceReviews(pluginId, publisherFingerprint), + }); + + const refresh = async () => client.invalidateQueries({ queryKey: queryKey(pluginId, publisherFingerprint) }); + const accept = async (review: PluginSharedResourceReview) => { + setBusy(reviewKey(review)); setError(false); + try { + await commands.pluginSharedResourceAccept( + pluginId, publisherFingerprint, review.profileId, review.resourceId, + ); + await refresh(); + } catch { setError(true); } + finally { setBusy(null); } + }; + const revoke = async (review: PluginSharedResourceReview) => { + setBusy(reviewKey(review)); setError(false); + try { + await commands.pluginSharedResourceRevoke( + pluginId, publisherFingerprint, review.profileId, review.resourceId, + ); + await refresh(); + } catch { setError(true); } + finally { setBusy(null); } + }; + + return ( +
+

{t('plugins.sharedResources.title')}

+

{t('plugins.sharedResources.disclosure')}

+ {isPending &&

{t('plugins.sharedResources.loading')}

} + {(isError || error) &&

{t('plugins.sharedResources.error')}

} + {!isPending && !isError && data.length === 0 &&

{t('plugins.sharedResources.empty')}

} +
    + {data.map((review) => { + const key = reviewKey(review); + return ( +
  • +
    +

    {review.displayName} · {review.profileName}

    + {t(`plugins.sharedResources.consent.${review.consent}`)} +
    +

    {t('plugins.sharedResources.runtime')}: {review.runtimeId}

    +

    + {t('plugins.sharedResources.games')}: {review.affectedGames.length + ? review.affectedGames.map((game) => game.name).join(', ') + : t('plugins.sharedResources.noGames')} +

    + {review.unavailable &&

    {t('plugins.sharedResources.unavailable')}

    } +
    + + +
    +
  • + ); + })} +
+
+ ); +}; diff --git a/ui/src/features/settings/PluginStorageAdmin.test.tsx b/ui/src/features/settings/PluginStorageAdmin.test.tsx new file mode 100644 index 000000000..1433215ed --- /dev/null +++ b/ui/src/features/settings/PluginStorageAdmin.test.tsx @@ -0,0 +1,301 @@ +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import { MantineProvider } from '@mantine/core'; +import { fireEvent, render, screen, waitFor, within } from '@testing-library/react'; +import React, { useState } from 'react'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { + commands, + type PluginStorageAccounting, + type StorageCleanupReport, + type StorageCleanupReview, +} from '../../api'; +import { appTheme } from '../../AppProviders'; +import { I18nProvider } from '../../i18n'; +import { PluginStorageAdmin } from './PluginStorageAdmin'; + +const poolPath = '/home/test/.local/share/gamenode/plugin-shared-data.gnpersistence'; +const privatePath = '/home/test/.local/share/gamenode/plugin-data/cdcd/dev.example.producer/a/storage.sqlite3'; + +const accounting: PluginStorageAccounting = { + profileId: 'a', + locations: [ + { + pluginId: 'dev.example.producer', + kind: 'durable_shared', + path: poolPath, + scope: 'pool', + fileBytes: 262_144, + logicalBytes: 153_600, + records: 12, + protectedRecords: 0, + archivedRecords: 0, + oldestUsedAt: 1_700_000_000, + maxBytes: 64 * 1024 * 1024, + maxAgeSeconds: 30 * 24 * 60 * 60, + }, + { + pluginId: 'dev.example.producer', + kind: 'private_persistence', + path: privatePath, + scope: 'namespace', + fileBytes: 57_344, + logicalBytes: 40_960, + records: 5, + protectedRecords: 2, + archivedRecords: 1, + oldestUsedAt: 1_700_000_000, + maxBytes: 16 * 1024 * 1024, + maxAgeSeconds: null, + }, + ], + pool: { + path: poolPath, + fileBytes: 262_144, + logicalBytes: 153_600, + overheadBytes: 108_544, + owners: 1, + maxOwnerBytes: 64 * 1024 * 1024, + }, + privateRootBytes: 57_344, +}; + +const review: StorageCleanupReview = { + token: 'review-token', + generatedAt: 1_700_000_000, + candidates: [ + { + candidateId: 'candidate-durable', + kind: 'durable_shared', + pluginId: 'dev.example.producer', + profileId: 'a', + records: 12, + protectedRecords: 0, + archivedRecords: 0, + logicalBytes: 153_600, + physicalBytesEstimate: 262_144, + oldestUpdatedAt: 1_700_000_000, + maxBytes: 64 * 1024 * 1024, + maxAgeSeconds: 30 * 24 * 60 * 60, + }, + { + candidateId: 'candidate-private', + kind: 'private_persistence', + pluginId: 'dev.example.producer', + profileId: 'a', + records: 5, + protectedRecords: 2, + archivedRecords: 1, + logicalBytes: 40_960, + physicalBytesEstimate: 57_344, + oldestUpdatedAt: 1_700_000_000, + maxBytes: 16 * 1024 * 1024, + maxAgeSeconds: null, + }, + ], +}; + +const report: StorageCleanupReport = { + token: 'review-token', + removedRecords: 12, + reclaimedBytes: 153_600, + skippedProtectedRecords: 0, + results: [ + { + candidateId: 'candidate-durable', + kind: 'durable_shared', + pluginId: 'dev.example.producer', + status: 'completed', + removedRecords: 12, + reclaimedBytes: 153_600, + error: null, + }, + ], +}; + +function renderAdmin(locale = 'en', profileId: string | null = 'a') { + const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + render( + + + + + + + , + ); + return client; +} + +function renderWithSibling() { + const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + const Harness: React.FC = () => { + const [opened, setOpened] = useState(0); + return ( + <> + + +

opened {opened}

+ + ); + }; + render( + + + + + + + , + ); + return client; +} + +describe('PluginStorageAdmin', () => { + beforeEach(() => { + vi.restoreAllMocks(); + }); + + it('shows host-managed physical paths and overhead only in the host screen', async () => { + vi.spyOn(commands, 'pluginStorageLocations').mockResolvedValue(accounting); + renderAdmin(); + + expect(await screen.findAllByText(poolPath)).toHaveLength(2); + expect(screen.getByText(privatePath)).toBeInTheDocument(); + expect(screen.getByText('Physical 56 KB · logical 40 KB')).toBeInTheDocument(); + expect(screen.getByText('File overhead: 16 KB (SQLite metadata and free pages)')) + .toBeInTheDocument(); + expect( + screen.getByText('This file is shared by every plugin that keeps durable shared data; the pool overhead below is pool-wide.'), + ).toBeInTheDocument(); + expect( + screen.getByText('Physical 256 KB · logical 150 KB · overhead 106 KB · plugins 1'), + ).toBeInTheDocument(); + expect(screen.getByText('Host administration')).toBeInTheDocument(); + expect( + screen.getByText(/Plugin IPC receives logical sizes only and cannot read a managed path\./), + ).toBeInTheDocument(); + expect(screen.getByText('Records: 5 · user-protected: 2')).toBeInTheDocument(); + // The per-plugin logical view stays on the plugin IPC-shaped surface; this screen is the + // only one that reads the managed paths. + expect(commands.pluginStorageLocations).toHaveBeenCalledTimes(1); + }); + + it('applies only the confirmed selection and reports the measured reclaimed bytes', async () => { + vi.spyOn(commands, 'pluginStorageLocations').mockResolvedValue(accounting); + vi.spyOn(commands, 'pluginStorageCleanupReview').mockResolvedValue(review); + const apply = vi.spyOn(commands, 'pluginStorageCleanupApply').mockResolvedValue(report); + renderAdmin(); + + fireEvent.click(await screen.findByRole('button', { name: 'Review cleanup candidates' })); + expect(await screen.findByText('2 candidates selected')).toBeInTheDocument(); + fireEvent.click(screen.getByRole('checkbox', { name: /Private plugin data/ })); + expect(screen.getByText('1 candidates selected')).toBeInTheDocument(); + + fireEvent.click(screen.getByRole('button', { name: 'Apply cleanup' })); + expect(apply).not.toHaveBeenCalled(); + const dialog = await screen.findByRole('dialog'); + expect(within(dialog).getByText(/Remove the reviewed datasets of the 1 selected candidates/)) + .toBeInTheDocument(); + fireEvent.click(within(dialog).getByRole('button', { name: 'Apply cleanup' })); + + await waitFor(() => + expect(apply).toHaveBeenCalledWith('review-token', ['candidate-durable'], true)); + expect( + await screen.findByText( + 'Removed 12 records · reclaimed 150 KB · kept 0 protected records', + ), + ).toBeInTheDocument(); + expect(screen.getByText('Completed: removed 12 records, reclaimed 150 KB')) + .toBeInTheDocument(); + // The review is consumed; a new one is needed for anything else. + expect(screen.queryByText('2 candidates selected')).not.toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'Review cleanup candidates' })) + .toBeInTheDocument(); + }); + + it('renders each candidate of a partial failure instead of collapsing the report', async () => { + vi.spyOn(commands, 'pluginStorageLocations').mockResolvedValue(accounting); + vi.spyOn(commands, 'pluginStorageCleanupReview').mockResolvedValue(review); + vi.spyOn(commands, 'pluginStorageCleanupApply').mockResolvedValue({ + ...report, + removedRecords: 12, + reclaimedBytes: 153_600, + skippedProtectedRecords: 2, + results: [ + report.results[0], + { + candidateId: 'candidate-private', + kind: 'private_persistence', + pluginId: 'dev.example.producer', + status: 'failed', + removedRecords: 0, + reclaimedBytes: 0, + error: 'plugin identity changed since the cleanup review', + }, + ], + }); + renderAdmin(); + + fireEvent.click(await screen.findByRole('button', { name: 'Review cleanup candidates' })); + await screen.findByText('2 candidates selected'); + fireEvent.click(screen.getByRole('button', { name: 'Apply cleanup' })); + fireEvent.click(within(await screen.findByRole('dialog')) + .getByRole('button', { name: 'Apply cleanup' })); + + expect( + await screen.findByText( + 'Removed 12 records · reclaimed 150 KB · kept 2 protected records', + ), + ).toBeInTheDocument(); + expect(screen.getByText('Completed: removed 12 records, reclaimed 150 KB')) + .toBeInTheDocument(); + expect(screen.getByText('Failed: plugin identity changed since the cleanup review')) + .toBeInTheDocument(); + }); + + it('keeps the rest of the settings usable while a slow review runs', async () => { + vi.spyOn(commands, 'pluginStorageLocations').mockResolvedValue(accounting); + let finishReview: (value: StorageCleanupReview) => void = () => undefined; + vi.spyOn(commands, 'pluginStorageCleanupReview').mockImplementation( + () => new Promise((resolve) => { finishReview = resolve; }), + ); + renderWithSibling(); + + fireEvent.click(await screen.findByRole('button', { name: 'Review cleanup candidates' })); + expect(screen.getByText('Reading cleanup candidates…')).toBeInTheDocument(); + + // The accounting query settled before the review was requested, and unrelated plugin + // navigation is not blocked by the pending host command. + expect((await screen.findAllByText(poolPath)).length).toBeGreaterThan(0); + fireEvent.click(screen.getByRole('button', { name: 'Open another plugin' })); + expect(await screen.findByText('opened 1')).toBeInTheDocument(); + expect(screen.getByText('Reading cleanup candidates…')).toBeInTheDocument(); + + finishReview(review); + expect(await screen.findByText('2 candidates selected')).toBeInTheDocument(); + }); + + it('renders the Portuguese accounting and cleanup copy', async () => { + vi.spyOn(commands, 'pluginStorageLocations').mockResolvedValue(accounting); + renderAdmin('pt-BR'); + + expect(await screen.findByText('Dados de plugins neste PC')).toBeInTheDocument(); + expect(screen.getByText('Administração do host')).toBeInTheDocument(); + expect(await screen.findByText('Físico 56 KB · lógico 40 KB')).toBeInTheDocument(); + expect(screen.getByText('Sobrecarga do arquivo: 16 KB (metadados e páginas livres do SQLite)')) + .toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'Revisar candidatos de limpeza' })) + .toBeInTheDocument(); + }); + + it('asks for sign-in instead of reading managed locations without a profile', async () => { + const locations = vi.spyOn(commands, 'pluginStorageLocations').mockResolvedValue(accounting); + renderAdmin('en', null); + + expect(await screen.findByText(/sign in/i)).toBeInTheDocument(); + expect(locations).not.toHaveBeenCalled(); + expect(screen.queryByText(poolPath)).not.toBeInTheDocument(); + }); +}); diff --git a/ui/src/features/settings/PluginStorageAdmin.tsx b/ui/src/features/settings/PluginStorageAdmin.tsx new file mode 100644 index 000000000..c656beb8c --- /dev/null +++ b/ui/src/features/settings/PluginStorageAdmin.tsx @@ -0,0 +1,395 @@ +import React, { useState } from 'react'; +import { useQuery, useQueryClient } from '@tanstack/react-query'; +import { IconAlertTriangle, IconDatabase, IconShieldLock } from '@tabler/icons-react'; +import { commands } from '../../api'; +import type { + StorageCleanupCandidate, + StorageCleanupReport, + StorageCleanupReview, +} from '../../api'; +import { AppModal } from '../../components/AppModal'; +import { Button, Pill } from '../../components/ui'; +import { pluginQueryKeys } from '../../api/pluginQueryKeys'; +import { useI18n } from '../../i18n'; +import { formatBytes } from '../ports/catalog/format'; +import { + settingsButtonSecondary, + settingsRowDescription, + settingsRowTitle, +} from './settingsClasses'; + +interface PluginStorageAdminProps { + profileId: string | null; +} + +function kindLabel(kind: string, t: (key: string) => string): string { + return kind === 'durable_shared' + ? t('plugins.storageAdmin.kind.durable_shared') + : t('plugins.storageAdmin.kind.private_persistence'); +} + +function limitText( + maxBytes: number | null, + maxAgeSeconds: number | null, + locale: string, + t: (key: string, values?: Record) => string, +): string { + const size = maxBytes === null + ? t('plugins.storageAdmin.noSizeLimit') + : t('plugins.storageAdmin.sizeLimit', { size: formatBytes(maxBytes, locale) }); + const age = maxAgeSeconds === null + ? t('plugins.storageAdmin.noAgeLimit') + : t('plugins.storageAdmin.ageLimit', { + days: Math.max(1, Math.round(maxAgeSeconds / 86_400)), + }); + return `${size} · ${age}`; +} + +/** + * Host administration of plugin data on this PC: the managed physical files, their measured + * allocation against the quota-charged logical bytes, the effective limits and a reviewed, + * confirmed cleanup of unused or over-limit datasets. The paths are shown only here; plugin IPC + * never receives them, and the review is a host command with a single-use token. + */ +export const PluginStorageAdmin: React.FC = ({ profileId }) => { + const { t, locale } = useI18n(); + const client = useQueryClient(); + const locations = useQuery({ + queryKey: pluginQueryKeys.storageLocations, + queryFn: commands.pluginStorageLocations, + enabled: profileId !== null, + }); + const [review, setReview] = useState(null); + const [selected, setSelected] = useState([]); + const [reviewing, setReviewing] = useState(false); + const [reviewFailed, setReviewFailed] = useState(false); + const [confirming, setConfirming] = useState(false); + const [applying, setApplying] = useState(false); + const [applyFailed, setApplyFailed] = useState(false); + const [report, setReport] = useState(null); + + const startReview = async () => { + setReviewing(true); + setReviewFailed(false); + setApplyFailed(false); + setReport(null); + try { + const next = await commands.pluginStorageCleanupReview(); + setReview(next); + setSelected(next.candidates.map((candidate) => candidate.candidateId)); + } catch { + setReviewFailed(true); + setReview(null); + setSelected([]); + } finally { + setReviewing(false); + } + }; + + const toggleCandidate = (candidateId: string) => { + setSelected((current) => current.includes(candidateId) + ? current.filter((id) => id !== candidateId) + : [...current, candidateId]); + }; + + const applyCleanup = async () => { + if (!review) return; + setApplying(true); + setApplyFailed(false); + try { + const outcome = await commands.pluginStorageCleanupApply(review.token, selected, true); + setReport(outcome); + setReview(null); + setSelected([]); + setConfirming(false); + await client.invalidateQueries({ queryKey: pluginQueryKeys.storageLocations }); + } catch { + setApplyFailed(true); + setConfirming(false); + // A partial or failed apply consumes the review; ask for a fresh one. + setReview(null); + setSelected([]); + } finally { + setApplying(false); + } + }; + + const candidateRow = (candidate: StorageCleanupCandidate) => ( +
  • + +
  • + ); + + return ( +
    +
    +
    +

    {t('plugins.storageAdmin.description')}

    +

    {t('plugins.storageAdmin.pathsHostOnly')}

    + + {profileId === null ? ( +

    + {t('plugins.signInRequired')} +

    + ) : locations.isPending ? ( +

    + {t('plugins.storageAdmin.locationsLoading')} +

    + ) : locations.isError || !locations.data ? ( +

    + {t('plugins.storageAdmin.locationsFailed')} +

    + ) : ( +
    + {locations.data.locations.length === 0 ? ( +

    + {t('plugins.storageAdmin.locationsEmpty')} +

    + ) : ( +
      + {locations.data.locations.map((location) => ( +
    • +

      + {location.pluginId} · {kindLabel(location.kind, t)} +

      +

      + {location.path} +

      +

      + {t('plugins.storageAdmin.locationBytes', { + physical: formatBytes(location.fileBytes, locale), + logical: formatBytes(location.logicalBytes, locale), + })} +

      +

      + {location.scope === 'namespace' + ? t('plugins.storageAdmin.namespaceOverhead', { + overhead: formatBytes( + Math.max(0, location.fileBytes - location.logicalBytes), + locale, + ), + }) + : t('plugins.storageAdmin.poolSharedFile')} +

      +

      + {t('plugins.storageAdmin.effectiveLimits')}:{' '} + {limitText(location.maxBytes, location.maxAgeSeconds, locale, t)} +

      +

      + {t('plugins.storageAdmin.locationRecords', { + records: location.records, + protected: location.protectedRecords, + })} +

      +
    • + ))} +
    + )} + {locations.data.pool && ( +
    +

    {t('plugins.storageAdmin.poolTitle')}

    +

    + {locations.data.pool.path} +

    +

    + {t('plugins.storageAdmin.poolTotals', { + physical: formatBytes(locations.data.pool.fileBytes, locale), + logical: formatBytes(locations.data.pool.logicalBytes, locale), + overhead: formatBytes(locations.data.pool.overheadBytes, locale), + owners: locations.data.pool.owners, + })} +

    +
    + )} +
    + )} + +
    +

    {t('plugins.storageAdmin.cleanupTitle')}

    +

    {t('plugins.storageAdmin.cleanupDescription')}

    +

    {t('plugins.storageAdmin.policyReadOnly')}

    +
    + + {report === null && ( + + )} +
    + {reviewing && ( +

    + {t('plugins.storageAdmin.reviewing')} +

    + )} + {reviewFailed && ( +

    + {t('plugins.storageAdmin.reviewFailed')} +

    + )} + {review && ( +
    + {review.candidates.length === 0 ? ( +

    + {t('plugins.storageAdmin.candidatesEmpty')} +

    + ) : ( +
      + {review.candidates.map(candidateRow)} +
    + )} +

    + {t('plugins.storageAdmin.selectedCount', { count: selected.length })} +

    +
    + )} + {applyFailed && ( +

    + {t('plugins.storageAdmin.applyFailed')} +

    + )} + {report && ( +
    +

    {t('plugins.storageAdmin.reportTitle')}

    +

    + {t('plugins.storageAdmin.reportTotals', { + records: report.removedRecords, + reclaimed: formatBytes(report.reclaimedBytes, locale), + skipped: report.skippedProtectedRecords, + })} +

    +
      + {report.results.map((result) => ( +
    • + + {result.pluginId} · {kindLabel(result.kind, t)} + + + {result.status === 'completed' + ? t('plugins.storageAdmin.resultCompleted', { + records: result.removedRecords, + reclaimed: formatBytes(result.reclaimedBytes, locale), + }) + : t('plugins.storageAdmin.resultFailed', { + error: result.error ?? t('plugins.storageAdmin.unknownError'), + })} + +
    • + ))} +
    +
    + )} + {applyFailed && ( +

    +

    + )} +
    + + !applying && setConfirming(false)} + closeOnEscape={!applying} + closeOnClickOutside={!applying} + > + + + + {t('plugins.storageAdmin.confirmTitle')} + + + +

    + {t('plugins.storageAdmin.confirmBody', { count: selected.length })} +

    +
    + + +
    +
    +
    +
    +
    + ); +}; diff --git a/ui/src/features/settings/RememberedConfirmations.test.tsx b/ui/src/features/settings/RememberedConfirmations.test.tsx new file mode 100644 index 000000000..80b889227 --- /dev/null +++ b/ui/src/features/settings/RememberedConfirmations.test.tsx @@ -0,0 +1,122 @@ +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { MantineProvider } from '@mantine/core'; +import { appTheme } from '../../AppProviders'; +import { commands, type PluginInfo, type RememberedConfirmation } from '../../api'; +import { I18nProvider } from '../../i18n'; +import { PluginInventory } from './PluginInventory'; +import { RememberedConfirmations } from './RememberedConfirmations'; + +const FINGERPRINT = 'cd'.repeat(32); + +const launch: RememberedConfirmation = { + id: 'r1', + gameName: 'Space Game', + operation: 'launch', + approvedAt: 1_700_000_000, +}; +const install: RememberedConfirmation = { + id: 'r2', + gameName: 'Other‮ Game', + operation: 'install', + approvedAt: 1_700_100_000, +}; + +function wrap(node: React.ReactNode, locale = 'en') { + const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + return render( + + + {node} + + , + ); +} + +describe('RememberedConfirmations', () => { + beforeEach(() => vi.restoreAllMocks()); + + it('lists what the plugin may start without asking, as plain text', async () => { + const list = vi + .spyOn(commands, 'pluginRememberedConfirmations') + .mockResolvedValue([launch, install]); + wrap(); + expect(await screen.findByText(/Start: Space Game/)).toBeInTheDocument(); + expect(list).toHaveBeenCalledWith('org.example', FINGERPRINT); + const item = screen.getByText(/Open install flow:/); + expect(item).toHaveTextContent('Other Game'); + expect(item.querySelector('b')).toBeNull(); + }); + + it('says so when there is nothing, and when it cannot load', async () => { + vi.spyOn(commands, 'pluginRememberedConfirmations').mockResolvedValue([]); + const { unmount } = wrap( + , + ); + expect(await screen.findByText('This plugin has no remembered confirmations.')).toBeInTheDocument(); + unmount(); + vi.spyOn(commands, 'pluginRememberedConfirmations').mockRejectedValue(new Error('x')); + wrap(); + expect(await screen.findByRole('alert')).toHaveTextContent('could not be loaded'); + }); + + it('revokes one confirmation and reads the list again from the host', async () => { + const list = vi + .spyOn(commands, 'pluginRememberedConfirmations') + .mockResolvedValueOnce([launch, install]) + .mockResolvedValue([install]); + const revoke = vi.spyOn(commands, 'pluginRevokeConfirmation').mockResolvedValue(true); + wrap(); + fireEvent.click(await screen.findByRole('button', { name: /Revoke permission to act on Space Game/ })); + await waitFor(() => expect(revoke).toHaveBeenCalledWith('org.example', FINGERPRINT, 'r1')); + await waitFor(() => expect(screen.queryByText(/Start: Space Game/)).not.toBeInTheDocument()); + expect(list).toHaveBeenCalledTimes(2); + expect(screen.getByText(/Open install flow:/)).toBeInTheDocument(); + }); + + it('reports a failed revocation and keeps what the host says', async () => { + vi.spyOn(commands, 'pluginRememberedConfirmations').mockResolvedValue([launch]); + vi.spyOn(commands, 'pluginRevokeConfirmation').mockRejectedValue(new Error('x')); + wrap(); + fireEvent.click(await screen.findByRole('button', { name: /Revoke permission/ })); + expect(await screen.findByText('The confirmation could not be revoked.')).toBeInTheDocument(); + expect(screen.getByText(/Start: Space Game/)).toBeInTheDocument(); + }); + + it('is localized in Portuguese', async () => { + vi.spyOn(commands, 'pluginRememberedConfirmations').mockResolvedValue([launch]); + wrap( + , + 'pt-BR', + ); + expect(await screen.findByText(/Iniciar: Space Game/)).toBeInTheDocument(); + expect(screen.getByRole('button', { name: /Revogar a permissão para agir em Space Game/ })).toBeInTheDocument(); + }); + + it('appears in the plugin details only for a plugin with a pinned publisher', async () => { + const community: PluginInfo = { + providerId: 'community', + pluginId: 'org.example.community', + pluginKind: 'provider', + name: 'Community', + source: 'community', + status: 'installed', + capabilities: ['game.launch'], + session: 'active', + nativeAccess: [], + publisherFingerprint: FINGERPRINT, + }; + const bundled: PluginInfo = { ...community, providerId: 'steam', pluginId: 'steam.plugin', name: 'Steam', source: 'official', publisherFingerprint: undefined }; + const list = vi.spyOn(commands, 'pluginRememberedConfirmations').mockResolvedValue([]); + vi.spyOn(commands, 'pluginInventory').mockResolvedValue([bundled, community]); + wrap(); + // The bundled plugin is selected first: no list, and nothing was asked of the host. + await screen.findAllByText('Steam'); + expect(screen.queryByText('Allowed without asking')).not.toBeInTheDocument(); + expect(list).not.toHaveBeenCalled(); + fireEvent.click(screen.getByRole('button', { name: /Community/ })); + expect(await screen.findByText('Allowed without asking')).toBeInTheDocument(); + expect(list).toHaveBeenCalledWith('org.example.community', FINGERPRINT); + }); +}); diff --git a/ui/src/features/settings/RememberedConfirmations.tsx b/ui/src/features/settings/RememberedConfirmations.tsx new file mode 100644 index 000000000..1f2192d06 --- /dev/null +++ b/ui/src/features/settings/RememberedConfirmations.tsx @@ -0,0 +1,87 @@ +import React from 'react'; +import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; +import { commands, plainText, CONFIRMATION_GAME_MAX } from '../../api'; +import { useI18n } from '../../i18n'; +import { + settingsButtonSecondary, + settingsRowDescription, +} from './settingsClasses'; + +const rememberedKey = (pluginId: string, publisher: string) => + ['plugin-remembered-confirmations', pluginId, publisher] as const; + +/** + * What the user allowed one plugin to start without asking again (the "don't ask again" choice of + * the confirmation dialog), with a way to take each one back. The game names come from the + * plugin's provider and are shown as plain text. + */ +export const RememberedConfirmations: React.FC<{ + pluginId: string; + publisherFingerprint: string; +}> = ({ pluginId, publisherFingerprint }) => { + const { t, locale } = useI18n(); + const queryClient = useQueryClient(); + const key = rememberedKey(pluginId, publisherFingerprint); + const { data = [], isPending, isError } = useQuery({ + queryKey: key, + queryFn: () => commands.pluginRememberedConfirmations(pluginId, publisherFingerprint), + }); + const revoke = useMutation({ + mutationFn: (id: string) => + commands.pluginRevokeConfirmation(pluginId, publisherFingerprint, id), + // The host stays authoritative: whatever happened, read the list again. + onSettled: () => queryClient.invalidateQueries({ queryKey: key }), + }); + + return ( +
    +

    {t('plugins.remembered.title')}

    + {isPending ? ( +

    + {t('plugins.loading')} +

    + ) : isError ? ( +

    + {t('plugins.remembered.loadFailed')} +

    + ) : data.length === 0 ? ( +

    {t('plugins.remembered.empty')}

    + ) : ( +
      + {data.map((item) => { + const game = plainText(item.gameName, CONFIRMATION_GAME_MAX) || t('plugins.confirm.unnamedGame'); + const what = + item.operation === 'install' + ? t('plugins.remembered.install') + : t('plugins.remembered.launch'); + return ( +
    • + + {what}: {game} + + {new Date(item.approvedAt * 1000).toLocaleDateString(locale)} + + + +
    • + ); + })} +
    + )} + {revoke.isError && ( +

    + {t('plugins.remembered.revokeFailed')} +

    + )} +

    {t('plugins.remembered.note')}

    +
    + ); +}; diff --git a/ui/src/features/settings/SettingsModal.test.tsx b/ui/src/features/settings/SettingsModal.test.tsx index 82d2169e0..79c0531c4 100644 --- a/ui/src/features/settings/SettingsModal.test.tsx +++ b/ui/src/features/settings/SettingsModal.test.tsx @@ -250,6 +250,29 @@ describe('SettingsModal Feature Suite', () => { expect(screen.getByRole('heading', { level: 2, name: 'About' })).toBeInTheDocument(); }); + it('keeps settings topic navigation responsive while Configure awaits the external window', async () => { + vi.spyOn(commands, 'pluginInventory').mockResolvedValue([{ + providerId: 'fixture', pluginId: 'org.example.fixture', pluginKind: 'extension', name: 'Fixture', source: 'community', + status: 'installed', capabilities: ['ui.configure'], session: 'active', nativeAccess: [], + }]); + vi.spyOn(commands, 'pluginConfigurationModes').mockResolvedValue({ + externalDeclared: true, externalAuthorized: true, + declarativeDeclared: false, declarativeAuthorized: false, + }); + let finishConfigure!: (result: { status: 'open'; windowId: string; message: null }) => void; + vi.spyOn(commands, 'pluginConfigurationOpen').mockReturnValue(new Promise((resolve) => { finishConfigure = resolve; })); + + openSettingsModal('plugins'); + renderSettings('en'); + fireEvent.click(await screen.findByRole('button', { name: 'Details' })); + fireEvent.click(await screen.findByRole('button', { name: 'Configure' })); + fireEvent.click(screen.getByRole('button', { name: 'Stores' })); + + expect(screen.getByRole('heading', { level: 2, name: 'Stores' })).toBeInTheDocument(); + await act(async () => { finishConfigure({ status: 'open', windowId: 'window-1', message: null }); }); + expect(uiStore.state.settingsTopic).toBe('stores'); + }); + it('persists selected topic across closing and reopening in the same session', () => { openSettingsModal(); renderSettings('en'); diff --git a/ui/src/features/settings/ToastContainer.test.tsx b/ui/src/features/settings/ToastContainer.test.tsx index 202825909..20f9e70d5 100644 --- a/ui/src/features/settings/ToastContainer.test.tsx +++ b/ui/src/features/settings/ToastContainer.test.tsx @@ -4,6 +4,7 @@ import { MantineProvider } from '@mantine/core'; import { ToastContainer } from './ToastContainer'; import { pushNotification, + pushToast, resetUiStore, uiStore, updateNotification, @@ -263,4 +264,50 @@ describe('ToastContainer', () => { expect(uiStore.state.toasts).toHaveLength(1); }); + + it('renders a plugin toast as attributed plain text, never as markup or a link', () => { + const hostile = ''; + pushToast('warning', hostile, { + body: '[click](javascript:alert(3))\npay https://evil.test/x', + source: 'org.example.plugin', + }); + const { container } = renderToasts(); + + // The strings are on screen as text. + expect(screen.getByText(hostile)).toBeInTheDocument(); + expect(screen.getByText('From plugin org.example.plugin')).toBeInTheDocument(); + expect(container.textContent).toContain('pay'); + // Nothing of it became an element: no script, image, link or bold text anywhere. + for (const tag of ['script', 'img', 'a', 'b', 'iframe', 'svg[onload]']) { + expect(document.querySelector(tag), tag).toBeNull(); + } + expect(document.querySelectorAll('[href], [src], [onerror], [onclick]')).toHaveLength(0); + // The line break in the body is kept. + expect(screen.getByText(/\[click\]\(javascript:alert\(3\)\)/).className).toContain( + 'whitespace-pre-line', + ); + }); + + it('keeps a plugin toast for its own duration', () => { + pushToast('info', 'Slow', { durationMs: 10000 }); + pushToast('info', 'Next'); + renderToasts(); + + act(() => { + vi.advanceTimersByTime(9999); + }); + expect(screen.getByText('Slow')).toBeInTheDocument(); + act(() => { + vi.advanceTimersByTime(1); + }); + expect(screen.queryByText('Slow')).toBeNull(); + }); + + it('has a look for every kind', () => { + for (const kind of ['success', 'danger', 'info', 'warning'] as const) { + pushToast(kind, `message ${kind}`); + } + renderToasts(); + expect(screen.getAllByRole('status')).toHaveLength(4); + }); }); diff --git a/ui/src/features/settings/ToastContainer.tsx b/ui/src/features/settings/ToastContainer.tsx index 6ed60e5d9..18326d0ac 100644 --- a/ui/src/features/settings/ToastContainer.tsx +++ b/ui/src/features/settings/ToastContainer.tsx @@ -3,6 +3,7 @@ import { Notification, Progress } from '@mantine/core'; import { IconCircleCheck, IconCircleX, + IconAlertTriangle, IconDownload, IconInfoCircle, IconX, @@ -20,6 +21,7 @@ const accentBarClass: Record = { success: 'bg-success', danger: 'bg-danger', info: 'bg-brand', + warning: 'bg-warning', progress: 'bg-brand', }; @@ -27,6 +29,7 @@ const iconClass: Record = { success: 'text-success', danger: 'text-danger', info: 'text-text-secondary', + warning: 'text-warning', progress: 'text-brand', }; @@ -37,6 +40,9 @@ function ToastIcon({ kind }: { kind: ToastKind }) { if (kind === 'danger') { return