Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,11 @@ pub fn identity(app: &AppHandle) -> Result<Value, String> {

fn identity_at(resources: &Path) -> Result<Value, String> {
let path = resources.join("runtime/identity.json");
let value: Value =
serde_json::from_slice(&fs::read(path).map_err(|_| "runtime_bundle_missing")?)
.map_err(|_| "runtime_bundle_invalid")?;
parse_identity(&fs::read(path).map_err(|_| "runtime_bundle_missing")?)
}

pub(crate) fn parse_identity(bytes: &[u8]) -> Result<Value, String> {
let value: Value = serde_json::from_slice(bytes).map_err(|_| "runtime_bundle_invalid")?;
if value["schema_version"] != "desktop_runtime_bundle_v1"
|| !value["source_revision"]
.as_str()
Expand Down
95 changes: 94 additions & 1 deletion apps/desktop/loopx-control-plane/src-tauri/src/macos_update.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,57 @@
//! the existing updater. This is only its macOS filesystem effect adapter.
use std::{
fs,
io::{self, Cursor},
io::{self, Cursor, Read},
path::{Component, Path},
};

use flate2::read::GzDecoder;
use serde_json::Value;
use tauri_plugin_updater::Update;

const PUBLIC_DEFAULT_CONTRACT: &str =
include_str!("../../../../../loopx/cli_commands/public_default_contract.json");

/// Read the publisher's observed contract inside the signature-verified bytes
/// before an update can be cached, close the workspace, or replace its App.
pub(crate) fn qualify_candidate(
channel: &str,
version: &str,
verified_bytes: &[u8],
) -> Result<(), String> {
// Historical stable bundles predate the attestation and remain usable.
// A preview stays subject to the check even if cache metadata changes channel.
if channel != "main"
&& !semver::Version::parse(version)
.is_ok_and(|value| value.pre.as_str().starts_with("main."))
{
return Ok(());
}
let invalid = "runtime_bundle_invalid";
let unavailable = "update_platform_unavailable";
let supported: Value = serde_json::from_str(PUBLIC_DEFAULT_CONTRACT).map_err(|_| invalid)?;
let identity_path = Path::new("LoopX.app/Contents/Resources/runtime/identity.json");
let mut archive = tar::Archive::new(GzDecoder::new(Cursor::new(verified_bytes)));
let mut qualified = false;
for entry in archive.entries().map_err(|_| invalid)? {
let mut entry = entry.map_err(|_| invalid)?;
if entry.path().map_err(|_| invalid)? != identity_path {
continue;
}
if qualified || !entry.header().entry_type().is_file() || entry.size() > 16 * 1024 {
return Err(invalid.into());
}
let mut raw = Vec::new();
entry.read_to_end(&mut raw).map_err(|_| invalid)?;
let identity = crate::bundled_runtime::parse_identity(&raw)?;
if identity["default_contract"] != supported {
return Err(unavailable.into());
}
qualified = true;
}
qualified.then_some(()).ok_or_else(|| unavailable.into())
}

// Provider-local errors, never a new persisted or caller-facing vocabulary.
#[derive(Debug, PartialEq)]
enum InstallError {
Expand Down Expand Up @@ -132,6 +176,55 @@ mod tests {
builder.into_inner().unwrap().finish().unwrap()
}

#[test]
fn only_qualified_preview_can_replace_the_prepared_candidate() {
let root = tempfile::tempdir().unwrap();
let candidate = root.path().join("candidate");
let resources = candidate.join("Contents/Resources/runtime");
fs::create_dir_all(&resources).unwrap();
let cache = root.path().join("prepared");
let version = "0.0.0-main.2.1";
let identity_path = resources.join("identity.json");
let mut identity = serde_json::json!({
"schema_version": "desktop_runtime_bundle_v1",
"source_revision": "1111111111111111111111111111111111111111"
});
let rejected = [
None,
Some(serde_json::json!({"surface": "unknown"})),
Some(serde_json::json!({
"surface": "complete_turn",
"schema_version": "loopx_turn_envelope_v1",
"interaction_schema_version": "loopx_interaction_contract_v0"
})),
];
for contract in rejected {
if let Some(contract) = contract {
identity["default_contract"] = contract;
}
fs::write(&identity_path, identity.to_string()).unwrap();
let bytes = archive(&candidate);
assert_eq!(
crate::prepared_update::save(&cache, "main", version, "unused", &bytes),
Err("update_platform_unavailable".into())
);
assert!(!cache.exists());
assert_eq!(
qualify_candidate("stable", version, &bytes),
Err("update_platform_unavailable".into())
);
assert!(qualify_candidate("stable", "2.3.0", &bytes).is_ok());
}

identity["default_contract"] = serde_json::from_str(PUBLIC_DEFAULT_CONTRACT).unwrap();
fs::write(identity_path, identity.to_string()).unwrap();
let bytes = archive(&candidate);
crate::prepared_update::save(&cache, "main", version, "unused", &bytes).unwrap();
let pointer = fs::read(cache.join("prepared.json")).unwrap();
assert!(crate::prepared_update::save(&cache, "main", version, "unused", b"bad").is_err());
assert_eq!(fs::read(cache.join("prepared.json")).unwrap(), pointer);
}

#[test]
fn verified_candidate_replaces_app_and_retains_intact_previous_bundle() {
let root = tempfile::tempdir().unwrap();
Expand Down
17 changes: 15 additions & 2 deletions apps/desktop/loopx-control-plane/src-tauri/src/maintenance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -896,14 +896,27 @@ async fn perform(
let bytes = if let Some(cached) = cached {
cached.bytes
} else {
download_update(&update, |chunk, total| {
let bytes = download_update(&update, |chunk, total| {
received += chunk as u64;
state.publish(
"downloading",
json!({"received":received,"total":total,"version":update.version}),
);
})
.await?
.await?;
#[cfg(target_os = "macos")]
{
let version = update.version.clone();
let channel = channel.to_owned();
tauri::async_runtime::spawn_blocking(move || {
crate::macos_update::qualify_candidate(&channel, &version, &bytes)?;
Ok::<_, String>(bytes)
})
.await
.map_err(|_| "runtime_bundle_invalid".to_string())??
}
#[cfg(not(target_os = "macos"))]
bytes
};
let target = update.version.clone();
install_verified_app(app, target, move || {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,8 @@ pub(crate) fn save(
if !matches!(channel, "main" | "stable") || semver::Version::parse(version).is_err() {
return Err(INVALID.into());
}
#[cfg(target_os = "macos")]
crate::macos_update::qualify_candidate(channel, version, bytes)?;
fs::create_dir_all(root).map_err(|_| INVALID)?;
let old = metadata(root).ok().flatten();
let value = json!({"schema_version":"desktop_prepared_update_v1", "channel":channel,
Expand Down Expand Up @@ -156,6 +158,8 @@ fn read(
let signature = Signature::decode(std::str::from_utf8(&signature).map_err(|_| INVALID)?)
.map_err(|_| INVALID)?;
key.verify(&bytes, &signature, true).map_err(|_| INVALID)?;
#[cfg(target_os = "macos")]
crate::macos_update::qualify_candidate(channel, version, &bytes)?;
Ok(Some(PreparedUpdate {
version: version.into(),
signature: value["signature"].as_str().ok_or(INVALID)?.into(),
Expand Down
5 changes: 5 additions & 0 deletions loopx/cli_commands/public_default_contract.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"surface": "quota_packet",
"schema_version": null,
"interaction_schema_version": "loopx_interaction_contract_v0"
}
15 changes: 12 additions & 3 deletions loopx/cli_commands/update_artifact.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,9 @@
from ..capabilities.issue_fix.repository_snapshot import _REPO_PATTERN as REPOSITORY_PATTERN

RUNTIME_ARTIFACT_SCHEMA_VERSION = "loopx_runtime_artifact_v1"
PUBLIC_DEFAULT_CONTRACT = {"surface": "quota_packet", "schema_version": None,
"interaction_schema_version": "loopx_interaction_contract_v0"}
PUBLIC_DEFAULT_CONTRACT = json.loads(
Path(__file__).with_name("public_default_contract.json").read_text(encoding="utf-8")
)
SHA = re.compile(r"[0-9a-f]{40}")
MAX_MANIFEST = 256 * 1024
MAX_ARCHIVE = 256 * 1024 * 1024
Expand Down Expand Up @@ -61,7 +62,15 @@ def standalone_source() -> str:
if source.count(old) != 1:
raise ValueError("Bootstrap grammar binding no longer matches its source import")
source = source.replace(old, "\n" + binding + "\n", 1)
return source
# The public installer is one file, so embed the policy that the Python
# publishers and the native updater read from the distribution contract.
binding_start = source.index("\nPUBLIC_DEFAULT_CONTRACT = ")
binding_end = source.index("\nSHA = ", binding_start)
return (
source[:binding_start]
+ f"\nPUBLIC_DEFAULT_CONTRACT = {PUBLIC_DEFAULT_CONTRACT!r}"
+ source[binding_end:]
)


def safe_url(url: str) -> str:
Expand Down
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ include = ["loopx*"]

[tool.setuptools.package-data]
"loopx" = ["web/chat/*.html", "web/chat/*.json", "web/chat/assets/*", "web/chat/manifest.webmanifest", "web/chat/pwa/*"]
"loopx.cli_commands" = ["public_default_contract.json"]
"loopx.control_plane" = ["*.json", "*.ts", "presentation/*.ts"]
"loopx.semantics" = ["*.json"]
"loopx.control_plane.agents" = ["*.ts"]
Expand Down
Loading