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
53 changes: 50 additions & 3 deletions astraweave-asset/src/image_limits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
//! A 4096-pixel edge is four times that. 4096² RGBA8 is 64 MiB, which is
//! also the allocation cap.

use anyhow::{Context, Result};
use std::io::Cursor;
use anyhow::{bail, Context, Result};
use std::io::{Cursor, Read};
use std::path::Path;

/// Longest edge `open_limited_image` and `decode_limited_image` accept.
Expand All @@ -29,10 +29,41 @@ pub fn decode_limited_image(bytes: &[u8]) -> Result<image::DynamicImage> {
reader.decode().context("decode image")
}

/// Read an image file without exceeding [`MAX_IMAGE_ALLOC`].
///
/// A regular file longer than the cap is rejected from its metadata, before
/// any byte is read, and is then read only up to that length. A fifo or other
/// non-regular file stops at the cap. It is not probed one byte past the cap,
/// which would block if the writer stalled after exactly that many bytes.
pub fn read_limited_image_bytes(path: &Path) -> Result<Vec<u8>> {
let cap = MAX_IMAGE_ALLOC;
let meta = std::fs::metadata(path).with_context(|| format!("open image {}", path.display()))?;
let file =
std::fs::File::open(path).with_context(|| format!("open image {}", path.display()))?;
if meta.is_file() {
if meta.len() > cap {
bail!("image is {} bytes, cap is {cap}", meta.len());
}
let mut bytes = Vec::new();
file.take(meta.len())
.read_to_end(&mut bytes)
.with_context(|| format!("read image {}", path.display()))?;
return Ok(bytes);
}
let mut bytes = Vec::new();
file.take(cap)
.read_to_end(&mut bytes)
.with_context(|| format!("read image {}", path.display()))?;
if bytes.len() as u64 == cap {
bail!("image exceeds {cap} bytes");
}
Ok(bytes)
}

/// Open an image file with the same caps as [`decode_limited_image`].
pub fn open_limited_image(path: impl AsRef<Path>) -> Result<image::DynamicImage> {
let path = path.as_ref();
let bytes = std::fs::read(path).with_context(|| format!("open image {}", path.display()))?;
let bytes = read_limited_image_bytes(path)?;
decode_limited_image(&bytes).with_context(|| format!("decode image {}", path.display()))
}

Expand Down Expand Up @@ -60,4 +91,20 @@ mod tests {
"{msg}"
);
}

#[test]
fn open_limited_image_rejects_a_file_over_64_mib() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("huge.bin");
let file = std::fs::File::create(&path).expect("create");
let cap = MAX_IMAGE_ALLOC;
file.set_len(cap + 1).expect("set_len");
drop(file);
let err = open_limited_image(&path).expect_err("oversized file must be rejected");
let msg = format!("{err:#}");
assert!(
msg.contains(&cap.to_string()) && msg.contains(&(cap + 1).to_string()),
"{msg}"
);
}
}
15 changes: 13 additions & 2 deletions astraweave-asset/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@ use tokio::sync::watch;
pub mod nanite_preprocess;

pub mod image_limits;
pub use image_limits::{capped_image_limits, decode_limited_image, open_limited_image};
pub use image_limits::{
capped_image_limits, decode_limited_image, open_limited_image, read_limited_image_bytes,
};

// World Partition cell loader
pub mod cell_loader;
Expand Down Expand Up @@ -827,7 +829,16 @@ pub mod gltf_loader {
decode_image_bytes(data)
}
gltf::image::Source::Uri { uri, .. } => {
let bytes = load_uri_bytes(uri)?;
let bytes = if uri.starts_with("data:") {
load_uri_bytes(uri)?
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
} else {
let base = std::env::current_dir().context("asset jail base")?;
let path =
astraweave_security::path::safe_under(&base, std::path::Path::new(uri))
.map_err(|err| anyhow!("path traversal rejected: {err}"))?;
crate::read_limited_image_bytes(&path)
.with_context(|| format!("Read image uri {uri}"))?
};
decode_image_bytes(&bytes)
}
}
Expand Down
28 changes: 27 additions & 1 deletion astraweave-render/src/hiz_pyramid.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,9 @@ impl HizPyramid {
height: u32,
src_depth_view: &wgpu::TextureView,
) -> Self {
let mip_count = (width.max(height) as f32).log2().ceil() as u32;
let edge = width.max(height).max(1);
// log2(1) is 0. wgpu rejects mip_level_count 0, so a 1×1 frame is one mip.
let mip_count = (edge as f32).log2().ceil().max(1.0) as u32;
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
let fmt = wgpu::TextureFormat::R32Float;

let hiz_texture = device.create_texture(&wgpu::TextureDescriptor {
Expand Down Expand Up @@ -367,5 +369,29 @@ mod tests {
!pyramid.copies_from(&other),
"a second view of the same texture is a different copy source"
);

let one = device.create_texture(&wgpu::TextureDescriptor {
label: Some("one pixel depth"),
size: wgpu::Extent3d {
width: 1,
height: 1,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Depth32Float,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::RENDER_ATTACHMENT,
view_formats: &[],
});
let one_view = one.create_view(&wgpu::TextureViewDescriptor::default());
let tiny = HizPyramid::new(&device, 1, 1, &one_view);
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
assert_eq!(tiny.dimensions(), (1, 1));
assert_eq!(tiny.mip_count(), 1, "a 1x1 frame is one mip, not zero");
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("1x1 hiz"),
});
tiny.build(&mut encoder);
drop(encoder);
}
}
4 changes: 2 additions & 2 deletions astraweave-render/src/material_loader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -304,8 +304,8 @@ struct VsOut { @builtin(position) pos: vec4<f32>, @location(0) uv: vec2<f32> };
pub(crate) fn load_ktx2_to_rgba(path: &Path) -> Result<image::RgbaImage> {
use basis_universal::*;

let data =
std::fs::read(path).with_context(|| format!("read ktx2 file {}", path.display()))?;
let data = astraweave_asset::read_limited_image_bytes(path)
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
.with_context(|| format!("read ktx2 file {}", path.display()))?;
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved

let reader = ktx2::Reader::new(&data).context("failed to parse KTX2 header")?;

Expand Down
3 changes: 2 additions & 1 deletion astraweave-render/src/renderer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9083,7 +9083,8 @@ fn vs(input: VSIn) -> VSOut {
e
);
// Fallback: manually read and guess format because image::open fails on .ktx2 extensions it doesn't know
let bytes = std::fs::read(path).expect("Failed to read fallback file");
let bytes = astraweave_asset::read_limited_image_bytes(path_ref)
.expect("Failed to read fallback file");
astraweave_asset::decode_limited_image(&bytes)
.expect("Failed to decode fallback texture (unknown format)")
.to_rgba8()
Expand Down
43 changes: 8 additions & 35 deletions astraweave-render/src/texture.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,40 +13,13 @@ use std::path::Path;
/// there: probing one byte past the cap would block if the writer stalled
/// after exactly that many bytes.
pub(crate) async fn read_capped_image(path: &str) -> Result<Vec<u8>, String> {
use tokio::io::AsyncReadExt;

let cap = astraweave_asset::image_limits::MAX_IMAGE_ALLOC;
let meta = tokio::fs::metadata(path)
.await
.map_err(|err| format!("read failed: {err}"))?;
if meta.is_file() {
if meta.len() > cap {
return Err(format!("image is {} bytes, cap is {cap}", meta.len()));
}
let mut file = tokio::fs::File::open(path)
.await
.map_err(|err| format!("read failed: {err}"))?;
let mut bytes = Vec::new();
(&mut file)
.take(meta.len())
.read_to_end(&mut bytes)
.await
.map_err(|err| format!("read failed: {err}"))?;
return Ok(bytes);
}
let mut file = tokio::fs::File::open(path)
.await
.map_err(|err| format!("read failed: {err}"))?;
let mut bytes = Vec::new();
(&mut file)
.take(cap)
.read_to_end(&mut bytes)
.await
.map_err(|err| format!("read failed: {err}"))?;
if bytes.len() as u64 == cap {
return Err(format!("image exceeds {cap} bytes"));
}
Ok(bytes)
let path = path.to_string();
tokio::task::spawn_blocking(move || {
astraweave_asset::read_limited_image_bytes(std::path::Path::new(&path))
.map_err(|err| format!("{err:#}"))
})
.await
.map_err(|err| format!("read failed: {err}"))?
}

/// Defines how a texture should be interpreted for correct color space handling
Expand Down Expand Up @@ -228,7 +201,7 @@ impl Texture {
));
}

let bytes = std::fs::read(path)?;
let bytes = astraweave_asset::read_limited_image_bytes(path)?;
Self::from_bytes_with_usage(device, queue, &bytes, &path.to_string_lossy(), usage)
}

Expand Down
64 changes: 64 additions & 0 deletions astraweave-render/src/texture_streaming.rs
Original file line number Diff line number Diff line change
Expand Up @@ -999,6 +999,70 @@ mod tests {
);
}

#[cfg(feature = "textures")]
#[test]
fn from_file_with_usage_rejects_a_file_over_the_cap() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("huge.bin");
let file = std::fs::File::create(&path).expect("create");
let cap = astraweave_asset::image_limits::MAX_IMAGE_ALLOC;
file.set_len(cap + 1).expect("set_len");
drop(file);
let instance = wgpu::Instance::new(&wgpu::InstanceDescriptor::default());
let Ok(adapter) =
pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {
power_preference: wgpu::PowerPreference::LowPower,
compatible_surface: None,
force_fallback_adapter: false,
}))
else {
eprintln!("skip from_file_with_usage cap: no wgpu adapter");
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
return;
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
};
let (device, queue) =
pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor::default()))
.expect("device");
let err = crate::texture::Texture::from_file_with_usage(
&device,
&queue,
&path,
crate::texture::TextureUsage::Albedo,
)
.expect_err("file over the cap must fail");
let msg = format!("{err:#}");
assert!(
msg.contains(&cap.to_string()) && msg.contains(&(cap + 1).to_string()),
"{msg}"
);
}

#[cfg(feature = "textures")]
#[test]
fn smoke_ktx2_fallback_rejects_a_file_over_the_cap() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("huge.ktx2");
let file = std::fs::File::create(&path).expect("create");
let cap = astraweave_asset::image_limits::MAX_IMAGE_ALLOC;
file.set_len(cap + 1).expect("set_len");
drop(file);
let mut renderer =
pollster::block_on(crate::Renderer::new_headless(64, 64)).expect("headless renderer");
let path_string = path.to_string_lossy().into_owned();
let panicked = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
renderer.set_smoke_test_texture(&path_string);
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
}));
let payload = panicked.expect_err("oversized ktx2 fallback must fail");
let msg = payload
.downcast_ref::<String>()
.map(String::as_str)
.or_else(|| payload.downcast_ref::<&str>().copied())
.unwrap_or("non-string panic");
assert!(
msg.contains(&cap.to_string()) && msg.contains(&(cap + 1).to_string()),
"{msg}"
);
}

#[cfg(feature = "textures")]
#[test]
fn decode_bytes_rejects_an_edge_past_4096() {
Expand Down
10 changes: 5 additions & 5 deletions docs/architecture/asset.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ domain: rendering
lifecycle_status: active
integration_status: wired
owns: [astraweave-asset, astraweave-asset-pipeline]
doc_version: "1.5"
last_verified_commit: 7c29b8182
doc_version: "1.6"
last_verified_commit: 417f267f
---

# Architecture Trace: Asset System
Expand All @@ -20,8 +20,8 @@ last_verified_commit: 7c29b8182
|---|---|
| **System name** | Asset System (loading, cell loader, Nanite preprocess, asset pipeline) |
| **Primary crates** | `astraweave-asset`, `astraweave-asset-pipeline` |
| **Document version** | 1.5 |
| **Last verified against commit** | `7c29b8182` |
| **Document version** | 1.6 |
| **Last verified against commit** | `417f267f` (parent of the bounded file read; that helper is not in this parent) |
| **Last verified date** | 2026-06-30 |
| **Status** | Active (mixed): glTF CPU loaders + cell loader + AssetDatabase are wired (`astraweave-asset` is VERIFIED-PRODUCTION); Nanite preprocess and the entire `astraweave-asset-pipeline` crate are in-design / dormant scaffolding. **R-series M1 trace-honesty (2026-06-30):** `astraweave-asset-pipeline` was individually **FALSE-PRODUCTION-READY** (R.0.B) — a present-tense over-claim at `lib.rs:4` over an ISLAND crate (no live caller). **R-series M2/E4 relabel-and-defer (2026-06-30):** E4 **resolved by relabel** — the `lib.rs:4` over-claim was rewritten to honest in-design status and the unused editor dep (`aw_editor/Cargo.toml:99`) was dropped, moving the crate **FALSE-PRODUCTION-READY → DORMANT-HONEST**. The BC7/KTX2 **cook path is NOT a v1.0 blocker** — the v1.0 render path consumes raw PNG→RGBA8 with no GPU-compressed-upload path, so cooking is a deferrable optimization **deferred to a post-v1.0 engine/compression-pipeline owner**. See `docs/audits/e4_cook_path_recon_2026-06.md`. |
| **Owner notes** | First trace for this subsystem. `astraweave-asset` is one of the most-consumed untraced crates (9+ Cargo consumers). Derived from forensic data-flow analysis on 2026-06-24. |
Expand Down Expand Up @@ -134,7 +134,7 @@ The system is three loosely-coupled data paths. They share the `astraweave-asset
**Role:** Pure-CPU glTF/GLB decode behind the default-on `gltf` feature.
**Inputs:** Raw `&[u8]` (GLB binary or `.gltf` JSON, including `data:` URI buffers).
**Outputs:** `MeshData` (positions/normals/tangents/texcoords/indices, lib.rs:330-336), `MaterialData` (full PBR factor set + KHR_materials_transmission/ior/emissive_strength/clearcoat fields, lib.rs:357-415), `ImageData`, `SkinnedMeshData`/`Skeleton`/`AnimationClip` (lib.rs:857-941).
**Notes:** Embedded image decode uses `decode_limited_image` (`image_limits.rs`): a 4096-pixel edge and a 64 MiB allocation cap (measured in-repo packs top out at 1024²). `open_limited_image` is the same cap for file paths. Render, the editor, blend texture import, and the asset CLI call that decoder. `load_gltf_bytes` (lib.rs:303) is a Phase-0 header-only validator that does not decode. Real decode entrypoints are `load_first_mesh_from_glb_bytes` (lib.rs:419), `load_all_meshes_merged` (lib.rs:487), `load_first_mesh_and_material` (lib.rs:574), and the skinned variants `load_skinned_mesh_complete` (lib.rs:1276) / `load_first_skinned_mesh_and_idle` (lib.rs:1475). Material defaults follow glTF spec defaults (e.g. `metallic_factor: 1.0`, `ior: 1.5`, lib.rs:392-415).
**Notes:** Embedded image decode uses `decode_limited_image` (`image_limits.rs`): a 4096-pixel edge and a 64 MiB allocation cap (measured in-repo packs top out at 1024²). `read_limited_image_bytes` stops the file read at 64 MiB before decode. `open_limited_image` and a glTF image URI use that read. Render, the editor, blend texture import, and the asset CLI call that decoder. `load_gltf_bytes` (lib.rs:303) is a Phase-0 header-only validator that does not decode. Real decode entrypoints are `load_first_mesh_from_glb_bytes` (lib.rs:419), `load_all_meshes_merged` (lib.rs:487), `load_first_mesh_and_material` (lib.rs:574), and the skinned variants `load_skinned_mesh_complete` (lib.rs:1276) / `load_first_skinned_mesh_and_idle` (lib.rs:1475). Material defaults follow glTF spec defaults (e.g. `metallic_factor: 1.0`, `ior: 1.5`, lib.rs:392-415).
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved

#### Stage B1: Cell RON deserialize
**File:** `astraweave-asset/src/cell_loader.rs:104-220`.
Expand Down
Loading
Loading