Skip to content

perf & security: hillclimb optimizations (-72.8% composite) and full-stack security hardening - #1005

Open
mneves75 wants to merge 31 commits into
libracoder:mainfrom
mneves75:perf-security-hillclimb
Open

mneves75 wants to merge 31 commits into
libracoder:mainfrom
mneves75:perf-security-hillclimb

Conversation

@mneves75

Copy link
Copy Markdown
Contributor

What this changes and why

This pull request combines two tracks of work developed on a local fork and tested on macOS (Apple Silicon):

  1. Performance optimization across the daemon, image store, protocol, client, and UI — guided by a deterministic local benchmark harness (tests/bench / hillclimb_bench) measuring latency, payload bytes, and UI frame lag across 42 workloads:

    • Composite score: 100.00 -> 27.22 (-72.8%) across 20 kept iterations (42/42 benchmarks, 0 errors):
      • Latency index: 100.00 -> 15.81 (-84.2%)
      • Bytes index: 100.00 -> 64.55 (-35.5%)
      • UI lag index: 100.00 -> 19.77 (-80.2%)
    • Daemon, image store & protocol:
      • Cache images.json index by file stamp and avoid cloning on /info and /images/json (30aece1).
      • Cache compiled seccomp BPF programs in a bounded LRU with exact profile validation (23bcc26).
      • Switch Engine container/network state to RwLock and use zero-alloc container filtering (55facbb).
      • Coalesce HTTP responses with writev, serialize hot endpoints directly, omit empty/default Docker API fields, and coalesce same-stream log mux frames (b078a8a, 49b627b).
      • Cache RFC3339 timestamp prefix, use SWAR log splitting, and add a zero-alloc log tail reader (5230633).
      • Buffer image blob/archive I/O at 128 KiB and batch index updates via put_images (c84fb0a).
      • Pre-reserve exact kiri-proto frame capacities and emit direct share headers (4022f26).
      • Add an HTTP/1.1 keep-alive connection pool in client.rs and an O(N) cursor in detail.rs streams (27861fe).
    • Desktop UI & localization:
      • Lazy-load xterm.js/addons/xterm.css on terminal open and non-boot panels.js on demand (817ce6b, 8e1d664).
      • Cache stripped HTML templates and strings_js, tighten static JS/CSS compaction, deduplicate inline SVG brand paths, and encode k8s_items::summarize as compact string-table tuples with default omission (5a0f168, 9be2b97, 60128bf, b3d5c80).
      • Eliminate layout thrashing in fitColumns/actionsWidth/spanRows, use zero-alloc morphKids, add an O(1) container map + cached live-pill buckets in the 1s ticker, early-bail unchanged list fingerprints, keyed incremental row patching (guarded against multi-<tr> rows and trailing siblings), in-place statusbar/CPU ticks, and pre-applied rtl_ready in lang::tr (811470c, 605f70d, 10a1313, 3406485, 79c7ca4, e05fde4).
  2. Defense-in-depth security hardening across VM, guest init, daemon, CLI, UI, Windows/WSL, and CI:

    • Guest kernel & kiri-init: hardened kernel configuration (CONFIG_SECURITY_YAMA, stricter mount flags such as nosuid,nodev on host shares), normalized VM ancestor bind paths, and hardened root dot xattr/image registry handling (0981931, 130509b).
    • Daemon mount isolation, caller confinement & DoS bounds: tightened bind/volume device validation, host-socket ancestor guards (including symlink, dangling-symlink, parent-dir traversal, and start-time re-resolution checks for non-Host callers), synthetic macOS /etc read-only enforcement (both create-time and start-time), auth/caller gates, relays, and request bounds (0f50d23, b3df90a, b6d98ee, fd45a2a).
    • CLI, share, USB, setup, diagnostics, webviews, Windows/WSL, packaging & CI: hardened host-access boundaries, webview handling, Windows updater/WSL plumbing, packaging scripts, CI workflows, and updated rustix for RUSTSEC-2026-0486 (6ab1952, 41a9cfb, f4c9bd6).

Note for maintainers: Per CONTRIBUTING.md, this is a large combined branch (31 commits). If you prefer reviewing it split into separate performance and security PRs (or by subsystem), I am happy to break it up after discussing the preferred slices.

How you tested it

# Workspace Rust unit & integration tests
cargo test --workspace
# -> 1,404 tests passing, 0 failed (including new daemon/api bind-recheck, path-guard, volume, seccomp, and UI tests)

# Guest musl target check
cargo check -p kiri-init --target aarch64-unknown-linux-musl
# -> clean

# UI test suite (including macOS/Linux/Windows parity checks)
python3 scripts/ui-test.py
# -> 136 files, 747 assertions passing

# Translation check
python3 scripts/i18n-check.py
# -> PASS 2038 keys, 41 language file(s), 0 problem(s)

# Performance benchmark suite
# -> 42/42 benchmarks, 0 errors; composite 100.00 -> 27.22 (-72.8%)

Tested on: macOS (Apple Silicon, arm64)

How you found it

  • I use Kiri and ran into this myself
  • I found it by reading the code or comparing with Docker
  • Someone else reported it (link the issue above)

AI tools used to write this change: yes (used for benchmark harness design, security audit/hardening analysis, implementation, and regression test authoring; reviewed and verified locally on macOS).

Checklist

  • I have at most 3 pull requests open on Kiri, this one included
  • Tests (cargo test --workspace, scripts/ui-test.py, scripts/i18n-check.py, kiri-init musl check) pass
  • Cross-platform code paths (macOS, Linux, Windows/WSL) updated together; macOS built and verified locally

…figs

Resolve all 14 VM/guest/image audit findings (SEC-V-01 through SEC-V-14)
plus the kiri-init pieces of SEC-D-04, FS-10 (SEC-D-28), and FS-11 (SEC-D-31):

- SEC-V-01: strip S_ISUID|S_ISGID on caller_owner virtiofs inodes/setattr
  in kernel patches 0008/0009; mount /mnt/mac with MS_NOSUID|MS_NODEV.
- SEC-V-02: track Process.device_filtered and drop CAP_MKNOD in exec when
  the cgroup device filter is unavailable on non-privileged containers.
- SEC-V-03: read /proc/sys/kernel/cap_last_cap dynamically, check
  PR_CAPBSET_DROP errors, clear ambient caps, and apply capset(v3).
- SEC-V-04: cap tarnum PAX headers at 1 MiB and bound import_upper via
  layers::Capped (64 GiB).
- SEC-V-05: disable raw tar xattr unpacking and apply only allowlisted
  security.capability and non-user.kiri.* user.* xattrs via O_NOFOLLOW fd.
- SEC-V-06: verify live container PID and pass /proc/<pid>/root fd over
  SCM_RIGHTS before reaping, validate layer_job IDs, and use O_NOFOLLOW
  openat/fchownat/fchmod in unpack_in.
- SEC-V-07: enable KASLR, stackprotector-strong, hardened usercopy,
  fortify source, slab freelist hardening, init-on-alloc, and Yama.
- SEC-V-08: pin and verify linux-6.18.58.tar.xz SHA-256 in build.sh.
- SEC-V-09: allowlist only the 8 IPC-namespaced kernel/* sysctls in Ns::Ipc.
- SEC-V-10: apply recursive read-only remounts to container ReadonlyPaths.
- SEC-V-11: encapsulate OnQueue<T> behind a QueueToken and keep VZ/vsock
  operations and timed-out receiver drops on the serial dispatch queue.
- SEC-V-12: sanitize PATH when spawning kiri-init and firewall tools;
  resolve firewall binaries only from trusted system directories.
- SEC-V-13: validate OCI index manifest digests and Docker Hub repo names.
- SEC-V-14: verify lockfile PID belongs to kiri-init before signaling.
- SEC-D-04 (kiri-init): enforce fstype/flag/source validation in volmount
  and container mount parsing.
- FS-10 (SEC-D-28): enforce /dev containment, skip symlinks, and cap
  depth/node count in hostopts --device walk.
- FS-11 (SEC-D-31): harden default seccomp profile (deny unknown syscalls
  >475, restrict socket/socketpair families, gate chroot, block legacy x86).
…xattrs

Address verifier review findings (libracoder#42):
- SEC-D-04: normalize empty and '.' path segments in is_vm_share_ancestor()
  so '/.', '/mnt/.', '//mnt', '/mnt//mac', '/mnt/./mac', and '/mnt/mac/.'
  are rejected in both volmount::validate_mount and container::valid_bind_source.
- SEC-V-05: allow apply_xattrs() to apply allowlisted xattrs on root '.'/'./'
  archive entries directly to the opened layer root fd while still rejecting
  ParentDir/Prefix escape components.
…oundaries

Resolves SEC-D-01, SEC-D-02, SEC-D-03, SEC-D-14, SEC-D-15, SEC-D-16, SEC-D-17, SEC-D-21, SEC-D-22, SEC-D-23, SEC-D-24, SEC-D-25, SEC-D-29, SEC-D-32, SEC-D-33, and SEC-D-34 with focused regression tests.
…ng, and CI

Remediates SEC-U-01 through SEC-U-33 across UI/WebView, Windows app,
Linux packaging, xtask, scripts, CI workflows, and deny.toml:

- UI & WebView (SEC-U-01, SEC-U-02, SEC-U-09..11, SEC-U-23..25):
  - Lock macOS WKWebView and Linux WebKitGTK to https://kiri.invalid/
    with navigation/popup delegates, drag-drop blocking, strict CSP,
    origin/main-frame checks, and per-launch IPC nonce
  - Escape </script> and line separators in lang::boot_js/strings_js,
    validate lang picks, harden allowed_open_url and dev.kiri.domain,
    validate USB detach keys, escape HTTP path segments, encode GVariant
    file:// URIs, harden detail::terminal, block non-macOS host ~/Kiri
    reads, and preserve mode 0o600 on ~/.docker/config.json
- Windows (SEC-U-03..07, SEC-U-10, SEC-U-12..16, SEC-U-22, SEC-U-28..30, SEC-U-33):
  - Gate KIRI_UPDATE_URL to debug builds, restrict release update URLs,
    verify Authenticode (WinVerifyTrust) and SHA-256 on downloaded and
    staged MSIs in update.rs and contrib/windows/kiri.ps1, add
    -RequireSigned to installer/windows/verify.ps1
  - Resolve usbipd via SHGetKnownFolderPath(FOLDERID_ProgramFiles),
    eliminate PowerShell/diskpart injection in compact_vhdx, switch
    wsl.exe to -e, harden wslsync symlink safety, verify engine bundles
    before sync_engine/restart_engine
  - Harden WebView2 CSP and subframe blocking, hub.rs curl/SSRF/token
    handling, relay.rs port deny-list, ports.rs TCP connection cap and
    SO_EXCLUSIVEADDRUSE + Win32 FFI bounds, UTF-8 char-boundary safety,
    pipe SID Vec<usize> alignment, and clipboard GlobalSize bounds
- Packaging, xtask, scripts & CI (SEC-U-01, SEC-U-08, SEC-U-17..21, SEC-U-26, SEC-U-31..32):
  - Scope Polkit policy to /usr/libexec/kiri/host-access with auth_admin
    and harden deb/postrm unmount loop
  - Hash-pin dmgbuild via scripts/dmgbuild-requirements.txt, pin Docker
    builder image digests, enforce --locked on release cargo builds,
    pass --options runtime in app-dev, enforce --proto =https and
    pinned SHA-256 in kernel-source.sh, validate Simple Icons metadata
    in ui-icons.py, eliminate fixed /tmp paths, add bounds checks in
    macho.rs
  - Add page-read-reset.yml and audit.yml workflows, configure
    advisories/bans/sources in deny.toml, and document perf.yml model
…zy log lowercase cache, and ESC-gated ANSI strip
@mneves75
mneves75 force-pushed the perf-security-hillclimb branch from fd45a2a to 281ebd8 Compare November 28, 2026 07:18
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant