Skip to content
Open
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
10 changes: 10 additions & 0 deletions crates/openlogi-assets/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,16 @@ pub enum AssetError {
/// The offending value.
component: String,
},
/// A remote-supplied depot-relative path had a segment that is not a
/// single safe path component (empty, `.`/`..`, a root or prefix, or a
/// backslash).
#[error("{label} must be a relative path of safe components, got {path:?}")]
UnsafeRelativePath {
/// Which input was rejected (e.g. `"asset file name"`).
label: String,
/// The offending value.
path: String,
},
/// Every built-in asset mirror failed its catalog probe.
#[error(
"all asset sources are unavailable (assets.openlogi.org: {production}; Pages: {pages}; jsDelivr: {jsdelivr})"
Expand Down
156 changes: 148 additions & 8 deletions crates/openlogi-assets/src/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -200,9 +200,9 @@ impl AssetClient {
dir: &Path,
file: &FileEntry,
) -> Result<FetchOutcome, AssetError> {
// `name` comes from remote metadata; validate it down to a single
// path component before any path is built.
let dst = safe_component_path(dir, &file.name, "asset file name")?;
// `name` comes from remote metadata; validate every segment of it
// before any path is built.
let dst = safe_relative_path(dir, &file.name, "asset file name")?;
if cached_matches(&dst, &file.sha256) {
return Ok(FetchOutcome::CacheHit);
}
Expand Down Expand Up @@ -293,9 +293,10 @@ pub fn read_bytes(path: &Path) -> Result<Vec<u8>, AssetError> {

/// Join one untrusted registry component onto a trusted directory.
///
/// Remote asset metadata is expected to carry depot and file *names*, not
/// paths. Rejecting separators, absolute prefixes, and `.`/`..` keeps every
/// sync write inside the cache or bundle directory chosen by the caller.
/// For depot names, which are always a single component. Rejecting
/// separators, absolute prefixes, and `.`/`..` keeps every sync write inside
/// the cache or bundle directory chosen by the caller. Files inside a depot
/// go through [`safe_relative_path`] instead.
pub fn safe_component_path(
base: &Path,
component: &str,
Expand All @@ -317,18 +318,42 @@ pub fn safe_component_path(
}
}

/// Join one untrusted depot-relative file path onto a trusted depot directory.
///
/// Registry file names and manifest `src` values are relative to the depot.
/// Most are a bare name, but G HUB depots keep their renders in
/// sub-directories (`images/device/<uuid>`). The path is split on `/`, the
/// separator the registry and the asset URLs use, and every segment must pass
/// [`safe_component_path`], so the result never leaves `base`.
pub fn safe_relative_path(base: &Path, relative: &str, label: &str) -> Result<PathBuf, AssetError> {
relative
.split('/')
.try_fold(base.to_path_buf(), |dir, segment| {
safe_component_path(&dir, segment, label)
})
.map_err(|_| AssetError::UnsafeRelativePath {
label: label.to_owned(),
path: relative.to_owned(),
})
}

/// Write `bytes` beside `dst` and atomically rename into place.
///
/// The temporary file is created in the destination directory and committed via
/// rename, so a concurrent reader sees the old file or the new one, never a
/// half-written one. A planted symlink at `dst` is replaced, not followed.
/// half-written one. A planted symlink at `dst` is replaced, not followed. The
/// destination directory is created when missing, since a depot file can sit
/// in a sub-directory of the depot.
pub(crate) fn write_replace(dst: &Path, bytes: &[u8]) -> Result<(), AssetError> {
use std::io::Write as _;

let fail = |source| AssetError::WriteFile {
path: dst.to_owned(),
source,
};
if let Some(parent) = dst.parent() {
fs::create_dir_all(parent).map_err(fail)?;
}
let mut file = AtomicWriteFile::open(dst).map_err(fail)?;
file.write_all(bytes).map_err(fail)?;
file.commit().map_err(fail)
Expand Down Expand Up @@ -362,7 +387,11 @@ pub fn cached_matches(path: &Path, expected_sha: &str) -> bool {

#[cfg(test)]
mod tests {
use super::{AssetClient, is_retryable, safe_component_path, write_replace};
use super::{
AssetClient, FetchOutcome, is_retryable, safe_component_path, safe_relative_path,
sha256_hex, write_replace,
};
use crate::index::FileEntry;
use std::path::Path;
use ureq::Error;

Expand Down Expand Up @@ -440,6 +469,117 @@ mod tests {
}
}

#[test]
fn safe_relative_path_accepts_names_and_depot_sub_paths() {
let depot = Path::new("/cache/g502x_plus");
assert_eq!(
safe_relative_path(depot, "front.png", "asset").ok(),
Some(depot.join("front.png"))
);
assert_eq!(
safe_relative_path(
depot,
"images/device/e0e9dacc-b5c0-4434-8b8d-410a7aa81d2f",
"asset"
)
.ok(),
Some(
depot
.join("images")
.join("device")
.join("e0e9dacc-b5c0-4434-8b8d-410a7aa81d2f")
)
);
}

#[test]
fn safe_relative_path_rejects_any_unsafe_segment() {
for name in [
"",
".",
"..",
"/etc/passwd",
"../front.png",
"images/../../front.png",
"images/./front.png",
"images//front.png",
"images/",
"images\\device\\front.png",
"images/..\\front.png",
] {
assert!(
safe_relative_path(Path::new("/cache/depot"), name, "asset").is_err(),
"{name:?} should be rejected"
);
}
}

/// #2457: G HUB depots name their renders `images/device/<uuid>`. The
/// fetch must request that path and land the file in the same
/// sub-directory of the depot, which does not exist yet.
#[test]
fn fetch_entry_writes_a_sub_path_file_into_its_depot_sub_directory() {
use std::io::{Read, Write};
use std::net::{TcpListener, TcpStream};

let body = b"\x89PNG\r\n\x1a\n render".to_vec();
let entry = FileEntry {
name: "images/device/e0e9dacc-b5c0-4434-8b8d-410a7aa81d2f".into(),
sha256: sha256_hex(&body),
bytes: body.len() as u64,
};
let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
let address = listener.local_addr().expect("local address");
let response = body.clone();
let server = std::thread::spawn(move || {
let (mut stream, _) = listener.accept().expect("accept");
let mut request = Vec::new();
let mut byte = [0];
while stream.read(&mut byte).expect("read request") != 0 {
request.push(byte[0]);
if request.ends_with(b"\r\n\r\n") {
break;
}
}
if !request.is_empty() {
write!(
stream,
"HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
response.len()
)
.expect("write head");
stream.write_all(&response).expect("write body");
}
request
});
let root = tempfile::tempdir().expect("create temp dir");
let depot = root.path().join("g502x_plus");
std::fs::create_dir(&depot).expect("create depot dir");
let client = AssetClient::new(&format!("http://{address}"));

let outcome = client.fetch_entry_if_stale("v1/devices/g502x_plus/", &depot, &entry);
// Release the server even when a regression skips the HTTP request.
drop(TcpStream::connect(address));
let request = server.join().expect("server thread");

assert!(
matches!(outcome, Ok(FetchOutcome::Fetched { .. })),
"{outcome:?}"
);
assert!(request.starts_with(
b"GET /v1/devices/g502x_plus/images/device/e0e9dacc-b5c0-4434-8b8d-410a7aa81d2f "
));
let landed = depot
.join("images")
.join("device")
.join("e0e9dacc-b5c0-4434-8b8d-410a7aa81d2f");
assert_eq!(std::fs::read(&landed).expect("read landed file"), body);
assert!(matches!(
client.fetch_entry_if_stale("v1/devices/g502x_plus/", &depot, &entry),
Ok(FetchOutcome::CacheHit)
));
}

#[test]
fn retries_transient_failures_not_permanent_ones() {
// Transient: server errors, the two "back off" 4xx codes, and
Expand Down
6 changes: 4 additions & 2 deletions crates/openlogi-assets/src/manifest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,10 @@ pub struct ManifestDevice {
}

/// One (`key`, `src`) pair. `key` is a stable Logitech identifier
/// (`device_image`, `device_buttons_image`, …); `src` is a filename
/// relative to the depot directory.
/// (`device_image`, `device_buttons_image`, …); `src` is a path relative to
/// the depot directory — usually a bare filename, but G HUB depots point
/// into sub-directories (`images/device/<uuid>`). Join it with
/// [`http::safe_relative_path`].
#[derive(Debug, Deserialize)]
pub struct ManifestResource {
pub key: String,
Expand Down
32 changes: 16 additions & 16 deletions crates/openlogi-desktop/src/services/assets.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;

use openlogi_assets::http::safe_component_path;
use openlogi_assets::http::{safe_component_path, safe_relative_path};
use openlogi_assets::{
BUTTONS_RENDER_FILES, DepotManifest, DeviceEntry, FRONT_RENDER_FILES, Index, METADATA_FILES,
Metadata,
Expand Down Expand Up @@ -168,23 +168,22 @@ fn main_view(path: PathBuf, side: Option<&SideView>, front: Option<&PathBuf>) ->
fn resolve_side_view(
dir: &Path,
entry: &DeviceEntry,
depot: &str,
manifest: Option<&DepotManifest>,
extended_model_id: u8,
metadata: &Metadata,
) -> Option<SideView> {
metadata
.image(SIDE_VIEW_KEY)
.filter(|image| !image.assignments.is_empty())?;
let variant = manifest.and_then(|m| {
entry.model_id_candidates().find_map(|base| {
m.resource_for_variant(base, extended_model_id, SIDE_VIEW_KEY)
.map(str::to_string)
})
});
// The same manifest bases the sync downloads by: G HUB depots key their
// variants on the depot name (`g502x_plus_ext1`), not on a model id.
let variant = manifest
.and_then(|m| find_variant_in_manifest(m, entry, depot, extended_model_id, side_image_for));
let (image_path, (png_width, png_height)) = variant
.into_iter()
.chain(["side.png".to_string()])
.filter_map(|n| safe_component_path(dir, &n, "asset file").ok())
.filter_map(|n| safe_relative_path(dir, &n, "asset file").ok())
.find_map(|p| read_image_dimensions(&p).ok().map(|dims| (p, dims)))?;
Some(SideView {
image_path,
Expand Down Expand Up @@ -304,7 +303,7 @@ impl AssetResolver {
/// constructing one just to reuse [`Self::resolve`] would conflate a
/// physical protocol identity with a model-level asset identity. The
/// registry lookup remains exact and case-insensitive, while all local
/// filenames still pass through the same safe component checks.
/// filenames still pass through the same safe path checks.
pub fn resolve_registry_model(&self, registry_model_id: &str) -> Option<ResolvedAsset> {
let index = self.index.as_ref()?;
let (depot, entry) = index.find_by_model_id(registry_model_id)?;
Expand Down Expand Up @@ -396,7 +395,7 @@ impl AssetResolver {
.clone()
.into_iter()
.chain(FRONT_RENDER_FILES.map(str::to_string))
.filter_map(|n| safe_component_path(&dir, &n, "asset file").ok())
.filter_map(|n| safe_relative_path(&dir, &n, "asset file").ok())
.find(|p| is_drawable_image(p));
let image_name = buttons_name
.clone()
Expand All @@ -414,7 +413,7 @@ impl AssetResolver {
candidates.extend(FRONT_RENDER_FILES.map(str::to_string));
let Some(image_path) = candidates
.iter()
.filter_map(|n| safe_component_path(&dir, n, "asset file").ok())
.filter_map(|n| safe_relative_path(&dir, n, "asset file").ok())
.find(|p| is_drawable_image(p))
else {
continue;
Expand All @@ -429,7 +428,8 @@ impl AssetResolver {
debug!(depot, root = %root.display(), "depot ships no hotspot metadata — rendering image without hotspots");
Metadata::default()
};
let side_view = resolve_side_view(&dir, entry, manifest.as_ref(), ext, &metadata);
let side_view =
resolve_side_view(&dir, entry, depot, manifest.as_ref(), ext, &metadata);
let image_path = main_view(image_path, side_view.as_ref(), hero_image_path.as_ref());
let (png_width, png_height) = match read_image_dimensions(&image_path) {
Ok(dims) => dims,
Expand Down Expand Up @@ -497,7 +497,7 @@ impl AssetResolver {
else {
continue;
};
let Ok(image_path) = safe_component_path(&dir, image_name, "asset file") else {
let Ok(image_path) = safe_relative_path(&dir, image_name, "asset file") else {
continue;
};
if !image_path.is_file() {
Expand Down Expand Up @@ -559,7 +559,7 @@ fn drawable_variant(
let renders: Vec<PathBuf> = [variant_image_for, buttons_image_for, side_image_for]
.into_iter()
.filter_map(|lookup| find_variant_in_manifest(manifest, entry, depot, ext, lookup))
.filter_map(|name| safe_component_path(dir, &name, "asset file").ok())
.filter_map(|name| safe_relative_path(dir, &name, "asset file").ok())
.filter(|path| path.is_file())
.collect();
if renders.is_empty() || renders.iter().any(|path| is_drawable_image(path)) {
Expand All @@ -580,7 +580,7 @@ fn drawable_variant(
/// keys its metadata `core_metadata_left.json` / `core_metadata_right.json` —
/// so a name-only lookup skips the depot outright and the GUI falls back to the
/// generic silhouette. Manifest-sourced names are attacker-influenced, so they
/// pass the same component check as every other asset file.
/// pass the same path check as every other asset file.
fn resolve_metadata(
dir: &Path,
entry: &DeviceEntry,
Expand All @@ -594,7 +594,7 @@ fn resolve_metadata(
.collect();
candidates.extend(METADATA_FILES.map(str::to_string));
candidates.into_iter().find_map(|name| {
let path = safe_component_path(dir, &name, "asset file").ok()?;
let path = safe_relative_path(dir, &name, "asset file").ok()?;
path.exists().then_some((name, path))
})
}
Expand Down
Loading
Loading